diff --git a/README.md b/README.md index 47eb52b..ad12d6c 100755 --- a/README.md +++ b/README.md @@ -1,66 +1,42 @@ -

๐Ÿš€ LEANN: A Low-Storage Vector Index

+

+ LEANN Logo +

Python 3.9+ MIT License - PRs Welcome -Platform + Platform

+

+ The smallest vector index in the world. RAG Everything with LEANN! +

+ +LEANN is a revolutionary vector database that makes personal AI accessible to everyone. Transform your laptop into a powerful RAG system that can index and search through millions of documents while using **97% less storage** than traditional solutions **without accuracy loss**. + +RAG your **[emails](#-search-your-entire-life)**, **[browser history](#-time-machine-for-the-web)**, **[WeChat](#-wechat-detective)**, or 60M documents on your laptop, in nearly zero cost. No cloud, no API keys, completely private. + +LEANN achieves this through *graph-based selective recomputation* with *high-degree preserving pruning*, computing embeddings on-demand instead of storing them all. [Read more โ†’](#๏ธ-architecture--how-it-works) | [Paper โ†’](https://arxiv.org/abs/2506.08276) + +## Why LEANN? +

- ๐Ÿ’พ Extreme Storage Saving โ€ข ๐Ÿ”’ 100% Private โ€ข ๐Ÿ“š RAG Everything โ€ข โšก Easy & Accurate + LEANN vs Traditional Vector DB Storage Comparison

-

- Quick Start โ€ข - Features โ€ข - Benchmarks โ€ข - Paper -

+**The numbers speak for themselves:** Index 60 million Wikipedia articles in just 6GB instead of 201GB. From emails to browser history, everything fits on your laptop. [See detailed benchmarks below โ†“](#storage-usage-comparison) ---- +## Why This Matters -## ๐ŸŒŸ What is LEANN-RAG? +๐Ÿ”’ **Privacy:** Your data never leaves your laptop. No OpenAI, no cloud, no "terms of service". -**LEANN-RAG** is a lightweight, locally deployable **Retrieval-Augmented Generation (RAG)** engine designed for personal devices. It combines **compact storage**, **clean usability**, and **privacy-by-design**, making it easy to build personalized retrieval systems over your own data โ€” emails, notes, documents, chats, or anything else. +๐Ÿชถ **Lightweight:** Smart graph pruning means less storage, less memory usage, better performance on your existing hardware. -Unlike traditional vector databases that rely on massive embedding storage, LEANN reduces storage needs dramatically by using **graph-based recomputation** and **pruned HNSW search**, while maintaining responsive and reliable performance โ€” all without sending any data to the cloud. +๐Ÿ“ˆ **Scalability:** Organize our messy personal data that would crash traditional vector DBs, with performance that gets better as your data grows more personalized. ---- +โœจ **No Accuracy Loss:** Maintain the same search quality as heavyweight solutions while using 97% less storage. -## ๐Ÿ”ฅ Key Highlights - -### ๐Ÿ’พ 1. Extreme Storage Efficiency -LEANN reduces storage usage by **up to 97%** compared to conventional vector DBs (e.g., FAISS), by storing only pruned graph structures and computing embeddings at query time. -> For example: 60M chunks can be indexed in just **6GB**, compared to **200GB+** with dense storage. - -### ๐Ÿ”’ 2. Fully Private, Cloud-Free -LEANN runs entirely locally. No cloud services, no API keys, and no risk of leaking sensitive data. -> Converse with your own files **without compromising privacy**. - -### ๐Ÿง  3. RAG Everything -Build truly personalized assistants by querying over **your own** chat logs, email archives, browser history, or agent memory. -> LEANN makes it easy to integrate personal context into RAG workflows. - -### โšก 4. Easy, Accurate, and Fast -LEANN is designed to be **easy to install**, with a **clean API** and minimal setup. It runs efficiently on consumer hardware without sacrificing retrieval accuracy. -> One command to install, one click to run. - ---- - -## ๐Ÿš€ Why Choose LEANN? - -Traditional RAG systems often require trade-offs between storage, privacy, and usability. **LEANN-RAG aims to simplify the stack** with a more practical design: - -- โœ… **No embedding storage** โ€” compute on demand, save disk space -- โœ… **Low memory footprint** โ€” lightweight and hardware-friendly -- โœ… **Privacy-first** โ€” 100% local, no network dependency -- โœ… **Simple to use** โ€” developer-friendly API and seamless setup - -> ๐Ÿ“„ For more details, see our [academic paper](https://arxiv.org/abs/2506.08276) -## ๐Ÿš€ Quick Start - -### Installation +## Quick Start in 1 minute ```bash git clone git@github.com:yichuan-w/LEANN.git leann @@ -73,29 +49,36 @@ git submodule update --init --recursive brew install llvm libomp boost protobuf export CC=$(brew --prefix llvm)/bin/clang export CXX=$(brew --prefix llvm)/bin/clang++ + +# Install with HNSW backend (default, recommended for most users) uv sync + +# Or add DiskANN backend if you want to test more options +uv sync --extra diskann ``` **Linux (Ubuntu/Debian):** ```bash sudo apt-get install libomp-dev libboost-all-dev protobuf-compiler libabsl-dev libmkl-full-dev libaio-dev + +# Install with HNSW backend (default, recommended for most users) uv sync + +# Or add DiskANN backend if you want to test more options +uv sync --extra diskann ``` **Ollama Setup (Optional for Local LLM):** +*We support both hf-transformers and Ollama for local LLMs. Ollama is recommended for faster performance.* + *macOS:* First, [download Ollama for macOS](https://ollama.com/download/mac). -```bash -# Install Ollama -brew install ollama +```bash # Pull a lightweight model (recommended for consumer hardware) ollama pull llama3.2:1b - -# For better performance but higher memory usage -ollama pull llama3.2:3b ``` *Linux:* @@ -108,18 +91,17 @@ ollama serve & # Pull a lightweight model (recommended for consumer hardware) ollama pull llama3.2:1b - -# For better performance but higher memory usage -ollama pull llama3.2:3b ``` -**Note:** For Hugging Face models >1B parameters, you may encounter OOM errors on consumer hardware. Consider using smaller models like Qwen3-0.6B or switch to Ollama for better memory management. +You can also replace `llama3.2:1b` to `deepseek-r1:1.5b` or `qwen3:4b` for better performance but higher memory usage. -### 30-Second Example -Try it out in [**demo.ipynb**](demo.ipynb) +## Dead Simple API + +Just 3 lines of code. Our declarative API makes RAG as easy as writing a config file: ```python from leann.api import LeannBuilder, LeannSearcher + # 1. Build index (no embeddings stored!) builder = LeannBuilder(backend_name="hnsw") builder.add_text("C# is a powerful programming language") @@ -128,63 +110,45 @@ builder.add_text("Machine learning transforms industries") builder.add_text("Neural networks process complex data") builder.add_text("Leann is a great storage saving engine for RAG on your macbook") builder.build_index("knowledge.leann") + # 2. Search with real-time embeddings searcher = LeannSearcher("knowledge.leann") results = searcher.search("C++ programming languages", top_k=2, recompute_beighbor_embeddings=True) print(results) ``` -### Run the Demo (support .pdf,.txt,.docx, .pptx, .csv, .md etc) +**That's it.** No cloud setup, no API keys, no "fine-tuning". Just your data, your questions, your laptop. + +[Try the interactive demo โ†’](demo.ipynb) + +## Wild Things You Can Do + +LEANN supports RAGing a lot of data sources, like .pdf, .txt, .md, and also supports RAGing your WeChat, Google Search History, and more. + +### ๐Ÿ“š Process Any Documents (.pdf, .txt, .md) + +Above we showed the Python API, while this CLI script demonstrates the same concepts while directly processing PDFs and documents. ```bash +# Drop your PDFs, .txt, .md files into examples/data/ uv run ./examples/main_cli_example.py -``` -or you want to use python - -```bash +# Or use python directly source .venv/bin/activate python ./examples/main_cli_example.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/md documents using Leann. +Uses Ollama `qwen3:8b` by default. For other models: `--llm openai --model gpt-4o` (requires `OPENAI_API_KEY` environment variable) or `--llm hf --model Qwen/Qwen3-4B`. -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. +**Works with any text format** - research papers, personal notes, presentations. Built with LlamaIndex for document parsing. - - -## โœจ Features - -### ๐Ÿ”ฅ Core Features - -- **๐Ÿ”„ Real-time Embeddings** - Eliminate heavy embedding storage with dynamic computation using optimized ZMQ servers and highly optimized search paradigm (overlapping and batching) with highly optimized embedding engine -- **๐Ÿ“ˆ Scalable Architecture** - Handles millions of documents on consumer hardware; the larger your dataset, the more LEANN can save -- **๐ŸŽฏ Graph Pruning** - Advanced techniques to minimize the storage overhead of vector search to a limited footprint -- **๐Ÿ—๏ธ Pluggable Backends** - DiskANN, HNSW/FAISS with unified API - -### ๐Ÿ› ๏ธ Technical Highlights -- **๐Ÿ”„ Recompute Mode** - Highest accuracy scenarios while eliminating vector storage overhead -- **โšก Zero-copy Operations** - Minimize IPC overhead by transferring distances instead of embeddings -- **๐Ÿš€ High-throughput Embedding Pipeline** - Optimized batched processing for maximum efficiency -- **๐ŸŽฏ Two-level Search** - Novel coarse-to-fine search overlap for accelerated query processing (optional) -- **๐Ÿ’พ Memory-mapped Indices** - Fast startup with raw text mapping to reduce memory overhead -- **๐Ÿš€ MLX Support** - Ultra-fast recompute/build with quantized embedding models, accelerating building and search ([minimal example](test/build_mlx_index.py)) - -### ๐ŸŽจ 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 - -## Applications on your MacBook - -### ๐Ÿ“ง Lightweight RAG on your Apple Mail - -LEANN can create a searchable index of your Apple Mail emails, allowing you to query your email history using natural language. - -#### Quick Start +### ๐Ÿ•ต๏ธ Search Your Entire Life +```bash +python examples/mail_reader_leann.py +# "What did my boss say about the Christmas party last year?" +# "Find all emails from my mom about birthday plans" +``` +**90K emails โ†’ 14MB.** Finally, search your email like you search Google.
๐Ÿ“‹ Click to expand: Command Examples @@ -193,52 +157,45 @@ LEANN can create a searchable index of your Apple Mail emails, allowing you to q # Use default mail path (works for most macOS setups) python examples/mail_reader_leann.py - # Run with custom index directory python examples/mail_reader_leann.py --index-dir "./my_mail_index" -# embedd and search all of your email(this may take a long preprocessing time but it will encode all your emails) +# Process all emails (may take time but indexes everything) python examples/mail_reader_leann.py --max-emails -1 # Limit number of emails processed (useful for testing) python examples/mail_reader_leann.py --max-emails 1000 # Run a single query -python examples/mail_reader_leann.py --query "Whats the number of class recommend to take per semester for incoming EECS students" +python examples/mail_reader_leann.py --query "What did my boss say about deadlines?" ```
- - -#### Example Queries -
-๐Ÿ’ฌ Click to expand: Example queries you can try +๐Ÿ“‹ Click to expand: Example queries you can try Once the index is built, you can ask questions like: - "Find emails from my boss about deadlines" - "What did John say about the project timeline?" - "Show me emails about travel expenses" -
-### ๐ŸŒ Lightweight RAG on your Google Chrome History - -LEANN can create a searchable index of your Chrome browser history, allowing you to query your browsing history using natural language. - -#### Quick Start +### ๐ŸŒ Time Machine for the Web +```bash +python examples/google_history_reader_leann.py +# "What was that AI paper I read last month?" +# "Show me all the cooking videos I watched" +``` +**38K browser entries โ†’ 6MB.** Your browser history becomes your personal search engine.
๐Ÿ“‹ Click to expand: Command Examples -Note you need to quit google right now to successfully run this. - ```bash -# Use default Chrome profile (auto-finds all profiles) and recommand method to run this because usually default file is enough +# Use default Chrome profile (auto-finds all profiles) python examples/google_history_reader_leann.py - # Run with custom index directory python examples/google_history_reader_leann.py --index-dir "./my_chrome_index" @@ -247,17 +204,12 @@ python examples/google_history_reader_leann.py --max-entries 500 # Run a single query python examples/google_history_reader_leann.py --query "What websites did I visit about machine learning?" - -# Use only a specific profile (disable auto-find) -python examples/google_history_reader_leann.py --chrome-profile "~/Library/Application Support/Google/Chrome/Default" --no-auto-find-profiles ```
-#### Finding Your Chrome Profile -
-๐Ÿ” Click to expand: How to find your Chrome profile +๐Ÿ“‹ Click to expand: How to find your Chrome profile The default Chrome profile path is configured for a typical macOS setup. If you need to find your specific Chrome profile: @@ -272,12 +224,11 @@ The default Chrome profile path is configured for a typical macOS setup. If you
-#### Example Queries -
๐Ÿ’ฌ Click to expand: Example queries you can try Once the index is built, you can ask questions like: + - "What websites did I visit about machine learning?" - "Find my search history about programming" - "What YouTube videos did I watch recently?" @@ -285,12 +236,13 @@ Once the index is built, you can ask questions like:
+### ๐Ÿ’ฌ WeChat Detective -### ๐Ÿ’ฌ Lightweight RAG on your WeChat History - -LEANN can create a searchable index of your WeChat chat history, allowing you to query your conversations using natural language. - -#### Prerequisites +```bash +python examples/wechat_history_reader_leann.py +# "Show me all group chats about weekend plans" +``` +**400K messages โ†’ 64MB.** Search years of chat history in any language.
๐Ÿ”ง Click to expand: Installation Requirements @@ -302,11 +254,8 @@ sudo packages/wechat-exporter/wechattweak-cli install ``` **Troubleshooting**: If you encounter installation issues, check the [WeChatTweak-CLI issues page](https://github.com/sunnyyoung/WeChatTweak-CLI/issues/41). -
-#### Quick Start -
๐Ÿ“‹ Click to expand: Command Examples @@ -325,84 +274,60 @@ python examples/wechat_history_reader_leann.py --max-entries 1000 # Run a single query python examples/wechat_history_reader_leann.py --query "Show me conversations about travel plans" - ```
-#### Example Queries -
๐Ÿ’ฌ Click to expand: Example queries you can try Once the index is built, you can ask questions like: + - "ๆˆ‘ๆƒณไนฐ้ญ”ๆœฏๅธˆ็บฆ็ฟฐ้€Š็š„็ƒ่กฃ๏ผŒ็ป™ๆˆ‘ไธ€ไบ›ๅฏนๅบ”่Šๅคฉ่ฎฐๅฝ•?" (Chinese: Show me chat records about buying Magic Johnson's jersey)
-## โšก Performance Comparison +## ๐Ÿ—๏ธ Architecture & How It Works -### LEANN vs Faiss HNSW +

+ LEANN Architecture +

-We benchmarked LEANN against the popular Faiss HNSW implementation to demonstrate the significant memory and storage savings our approach provides: +**The magic:** Most vector DBs store every single embedding (expensive). LEANN stores a pruned graph structure (cheap) and recomputes embeddings only when needed (fast). +**Core techniques:** +- **Graph-based selective recomputation:** Only compute embeddings for nodes in the search path +- **High-degree preserving pruning:** Keep important "hub" nodes while removing redundant connections +- **Dynamic batching:** Efficiently batch embedding computations for GPU utilization +- **Two-level search:** Smart graph traversal that prioritizes promising nodes + +**Backends:** DiskANN or HNSW - pick what works for your data size. + +## Benchmarks + +Run the comparison yourself: ```bash -# Run the comparison benchmark python examples/compare_faiss_vs_leann.py ``` -#### ๐ŸŽฏ Results Summary +| System | Storage | +|--------|---------| +| FAISS HNSW | 5.5 MB | +| LEANN | 0.5 MB | +| **Savings** | **91%** | -| Metric | Faiss HNSW | LEANN HNSW | **Improvement** | -|--------|------------|-------------|-----------------| -| **Storage Size** | 5.5 MB | 0.5 MB | **11.4x smaller** (5.0 MB saved) | +Same dataset, same hardware, same embedding model. LEANN just works better. -#### ๐Ÿ“ˆ Key Takeaways - - -- **๐Ÿ’พ Storage Optimization**: LEANN requires **91% less storage** for the same dataset - -- **โš–๏ธ Fair Comparison**: Both systems tested on identical hardware with the same 2,573 document dataset and the same embedding model and chunk method - -> **Note**: Results may vary based on dataset size, hardware configuration, and query patterns. The comparison excludes text storage to focus purely on index structures. - - - -*Benchmark results obtained on Apple Silicon with consistent environmental conditions* - -## ๐Ÿ“Š Benchmarks - -### How to Reproduce Evaluation Results - -Reproducing our benchmarks is straightforward. The evaluation script is designed to be self-contained, automatically downloading all necessary data on its first run. - -#### 1. Environment Setup - -First, ensure you have followed the installation instructions in the [Quick Start](#-quick-start) section. This will install all core dependencies. - -Next, install the optional development dependencies, which include the `huggingface-hub` library required for automatic data download: +## Reproduce Our Results ```bash -# This command installs all development dependencies -uv pip install -e ".[dev]" +uv pip install -e ".[dev]" # Install dev dependencies +python examples/run_evaluation.py data/indices/dpr/dpr_diskann # DPR dataset +python examples/run_evaluation.py data/indices/rpj_wiki/rpj_wiki.index # Wikipedia ``` -#### 2. Run the Evaluation - -Simply run the evaluation script. The first time you run it, it will detect that the data is missing, download it from Hugging Face Hub, and then proceed with the evaluation. - -**To evaluate the DPR dataset:** -```bash -python examples/run_evaluation.py data/indices/dpr/dpr_diskann -``` - -**To evaluate the RPJ-Wiki dataset:** -```bash -python examples/run_evaluation.py data/indices/rpj_wiki/rpj_wiki.index -``` - -The script will print the recall and search time for each query, followed by the average results. +The evaluation script downloads data automatically on first run. ### Storage Usage Comparison @@ -429,13 +354,6 @@ The script will print the recall and search time for each query, followed by the *Benchmarks run on Apple M3 Pro 36 GB* - -## ๐Ÿ—๏ธ Architecture - -

- LEANN Architecture -

- ## ๐Ÿ”ฌ Paper If you find Leann useful, please cite: @@ -454,6 +372,28 @@ If you find Leann useful, please cite: } ``` +## โœจ Features + +### ๐Ÿ”ฅ Core Features + +- **๐Ÿ”„ Real-time Embeddings** - Eliminate heavy embedding storage with dynamic computation using optimized ZMQ servers and highly optimized search paradigm (overlapping and batching) with highly optimized embedding engine +- **๐Ÿ“ˆ Scalable Architecture** - Handles millions of documents on consumer hardware; the larger your dataset, the more LEANN can save +- **๐ŸŽฏ Graph Pruning** - Advanced techniques to minimize the storage overhead of vector search to a limited footprint +- **๐Ÿ—๏ธ Pluggable Backends** - DiskANN, HNSW/FAISS with unified API + +### ๐Ÿ› ๏ธ Technical Highlights +- **๐Ÿ”„ Recompute Mode** - Highest accuracy scenarios while eliminating vector storage overhead +- **โšก Zero-copy Operations** - Minimize IPC overhead by transferring distances instead of embeddings +- **๐Ÿš€ High-throughput Embedding Pipeline** - Optimized batched processing for maximum efficiency +- **๐ŸŽฏ Two-level Search** - Novel coarse-to-fine search overlap for accelerated query processing (optional) +- **๐Ÿ’พ Memory-mapped Indices** - Fast startup with raw text mapping to reduce memory overhead +- **๐Ÿš€ MLX Support** - Ultra-fast recompute/build with quantized embedding models, accelerating building and search ([minimal example](test/build_mlx_index.py)) + +### ๐ŸŽจ 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 ## ๐Ÿค Contributing diff --git a/asset/arch.png b/assets/arch.png similarity index 100% rename from asset/arch.png rename to assets/arch.png diff --git a/assets/effects.png b/assets/effects.png new file mode 100644 index 0000000..925cd24 Binary files /dev/null and b/assets/effects.png differ diff --git a/assets/logo-text.png b/assets/logo-text.png new file mode 100644 index 0000000..41e142a Binary files /dev/null and b/assets/logo-text.png differ diff --git a/assets/logo.png b/assets/logo.png new file mode 100644 index 0000000..c2eb33d Binary files /dev/null and b/assets/logo.png differ diff --git a/packages/leann-backend-diskann/pyproject.toml b/packages/leann-backend-diskann/pyproject.toml index 70383e8..8f02feb 100644 --- a/packages/leann-backend-diskann/pyproject.toml +++ b/packages/leann-backend-diskann/pyproject.toml @@ -13,4 +13,7 @@ cmake.source-dir = "third_party/DiskANN" # ๅ…ณ้”ฎ๏ผšPython ๅŒ…ๅœจๆ น็›ฎๅฝ•๏ผŒ่ทฏๅพ„ๅฎŒๅ…จๅŒน้… wheel.packages = ["leann_backend_diskann"] # ไฝฟ็”จ้ป˜่ฎค็š„ redirect ๆจกๅผ -editable.mode = "redirect" \ No newline at end of file +editable.mode = "redirect" +cmake.build-type = "Release" +build.verbose = true +build.tool-args = ["-j8"] \ No newline at end of file diff --git a/packages/leann-backend-hnsw/pyproject.toml b/packages/leann-backend-hnsw/pyproject.toml index 580fd56..12df4d6 100644 --- a/packages/leann-backend-hnsw/pyproject.toml +++ b/packages/leann-backend-hnsw/pyproject.toml @@ -13,5 +13,6 @@ dependencies = ["leann-core==0.1.0", "numpy"] [tool.scikit-build] wheel.packages = ["leann_backend_hnsw"] editable.mode = "redirect" -cmake.build-type = "Debug" -build.verbose = true \ No newline at end of file +cmake.build-type = "Release" +build.verbose = true +build.tool-args = ["-j8"] \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 9cd0db9..3a0c027 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,6 @@ requires-python = ">=3.10" dependencies = [ "leann-core", - "leann-backend-diskann", "leann-backend-hnsw", "numpy>=1.26.0", "torch", @@ -48,6 +47,10 @@ dev = [ "huggingface-hub>=0.20.0", ] +diskann = [ + "leann-backend-diskann", +] + [tool.setuptools] py-modules = []