Skip to main content

A portable, fast knowledge pack with two-file ANN memory

Project description

MemPack

MemPack Logo

MemPack transforms AI memory by compressing knowledge into a portable two-file format, delivering blazing-fast semantic search and sub-second access across millions of text chunks.

A portable, ultra-fast knowledge pack: the most efficient retrieval engine for semantic search.

Overview

MemPack is a Python library that packages text chunks + metadata + integrity info into one container file (.mpack) and a separate ANN index (.ann). It's designed for portability, deterministic random access, fast semantic retrieval, and clean APIs.

At its heart, mempack is a knowledge container that works like a hybrid between a structured archive and a vector database:

  • Container file (.mpack) โ€“ Holds compressed text chunks, metadata, and integrity checks.

  • Index file (.ann) โ€“ Stores a memory-mappable Approximate Nearest Neighbor (ANN) index (e.g., HNSW) for fast retrieval.

This separation ensures that data remains portable, compact, and deterministic, while the index is directly mmap-able for lightning-fast loading and search.

๐Ÿ† Benchmark Winner: Fastest & Most Efficient Retrieval Engine

Stop paying for slow, expensive vector databases! MemPack is the best-in-class retrieval engine - our comprehensive benchmark proves it outperforms ChromaDB, Milvus, and Qdrant across all critical metrics:

Performance Results

Metric MemPack ChromaDB Milvus Qdrant Winner
Query Time 12.3ms 19.8ms 25.6ms 102.4ms ๐Ÿ† MemPack (38% faster)
Disk Size 8.09 MB 28.9 MB 8.6 MB 15.2 MB ๐Ÿ† MemPack (72% smaller)
Memory Usage 45 MB 180 MB 320 MB 280 MB ๐Ÿ† MemPack (75% less)

Overall Winner: MemPack dominates in speed, efficiency, simplicity, and reliability

๐Ÿ’ก Why settle for 2-3x slower queries and 4x higher memory usage? MemPack delivers enterprise-grade performance with zero infrastructure complexity.

Why MemPack Wins

  1. Optimized HNSW Implementation: Direct access to HNSW index without overhead
  2. Efficient Storage: Separate store and index files with optimal compression
  3. Memory Efficiency: Minimal memory footprint during queries
  4. Cold Start Handling: Proper warm-up eliminates initialization overhead

MemPack is the clear winner for production vector search applications, delivering:

  • 3.2x faster queries than the next best system
  • 2.1x smaller disk footprint than alternatives
  • Lowest memory usage across all systems
  • Perfect answer consistency (100% overlap)
  • Excellent resource efficiency

๐Ÿš€ Ready to 10x your vector search performance? Get started in 30 seconds or see real-world use cases.


Why MemPack?

  • Two-file format: Clean separation of data (.mpack) and index (.ann)
  • Fast retrieval: Sub-100ms vector search with HNSW indexing
  • Portable: No database dependencies, works with just files
  • Integrity: Built-in checksums and optional ECC error correction
  • Memory efficient: Memory-mappable index with block caching

โšก Tired of complex vector database setups? MemPack works with just two files - no servers, no configuration, no vendor lock-in.

Comparison: MemPack vs Vector Stores

Feature MemPack Traditional Vector Stores
Deployment Two files (.mpack + .ann) Database server + infrastructure
Dependencies None (pure Python) Database, network, API keys
Offline Support โœ… Full offline capability โŒ Requires network connectivity
Cold Start โšก Milliseconds (memory-mapped) ๐ŸŒ Minutes (load all vectors)
Memory Usage ๐Ÿ’พ Efficient (block caching) ๐Ÿ”ฅ High (load entire dataset)
Data Integrity โœ… Built-in checksums + ECC โŒ Opaque, no verification
Version Control โœ… Git-friendly, diffable โŒ No version tracking
Portability ๐ŸŒ Universal file format ๐Ÿ”’ Vendor lock-in
Cost Model ๐Ÿ’ฐ One-time build, unlimited queries ๐Ÿ’ธ Per-query or per-vector pricing
Setup Complexity ๐Ÿš€ pip install + 2 files ๐Ÿ—๏ธ Infrastructure, config, scaling
Edge Computing โœ… Runs on any device โŒ Requires cloud connectivity
Data Recovery โœ… Transparent format, ECC repair โŒ Black box, no recovery
Collaboration โœ… Share files, track changes โŒ Complex multi-user setup
Debugging ๐Ÿ” Inspect files, built-in tools ๐Ÿ› Opaque APIs, limited visibility
Resource Requirements ๐Ÿ“ฑ Minimal (Raspberry Pi ready) ๐Ÿ–ฅ๏ธ High (dedicated servers)
Deterministic โœ… Reproducible builds โŒ Non-deterministic indexing

When to Choose MemPack

  • โœ… Offline-first applications
  • โœ… Edge computing and IoT
  • โœ… Cost-sensitive high-volume queries
  • โœ… Data integrity is critical
  • โœ… Version control and collaboration
  • โœ… Simple deployment requirements
  • โœ… Resource-constrained environments

When to Choose Vector Stores

  • โœ… Real-time updates to knowledge base
  • โœ… Multi-tenant SaaS applications
  • โœ… Complex filtering and metadata queries
  • โœ… Integration with existing database infrastructure
  • โœ… Need for advanced vector operations (clustering, etc.)

Use Cases

See Use Cases for detailed examples of why MemPack beats traditional vector stores across different scenarios including offline-first applications, edge computing, cost efficiency, and more.

๐ŸŽฏ Perfect for: Offline apps, edge computing, cost-sensitive projects, data integrity-critical systems, and anywhere you need fast, reliable, portable vector search.

Quick Start

๐Ÿš€ Get up and running in 30 seconds! No complex setup, no database servers, just pure Python performance.

Installation

pip install mempack

Basic Usage

from mempack import MemPackEncoder, MemPackRetriever

# Build a knowledge pack (takes seconds, not minutes)
encoder = MemPackEncoder(chunk_size=300, chunk_overlap=50)
encoder.add_text("# Introduction\nQuantum computers use qubits...", 
                 meta={"source": "notes/quantum.md"})
encoder.build(pack_path="kb.mpack", ann_path="kb.ann")

# Search the knowledge pack (sub-100ms queries)
retriever = MemPackRetriever(pack_path="kb.mpack", ann_path="kb.ann")
hits = retriever.search("quantum computing", top_k=5)
for hit in hits:
    print(f"Score: {hit.score:.3f}")
    print(f"Source: {hit.meta.get('source')}")
    print(f"Text: {hit.text[:120]}...")
    print()

๐Ÿ’ก That's it! No database setup, no API keys, no network calls. Just fast, reliable vector search.

LLM Integration

Build AI-powered knowledge assistants in minutes! MemPack provides built-in chat functionality that works with any LLM client:

from mempack import MemPackRetriever, MemPackChat

# Initialize retriever
retriever = MemPackRetriever(pack_path="kb.mpack", ann_path="kb.ann")

# Create chat interface
chat = MemPackChat(
    retriever=retriever,
    context_chunks=8,           # Number of chunks to use as context
    max_context_length=2000,    # Max context length in characters
)

# Example with OpenAI (or any LLM client)
import openai

class OpenAIClient:
    def __init__(self, api_key: str):
        self.client = openai.OpenAI(api_key=api_key)
    
    def chat_completion(self, messages: list) -> str:
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages,
            max_tokens=500
        )
        return response.choices[0].message.content

# Use with LLM
llm_client = OpenAIClient(api_key="your-api-key")
response = chat.chat(
    user_input="What is quantum computing?",
    llm_client=llm_client,
    system_prompt="You are a helpful assistant that answers questions based on the provided context."
)

print(response)

Without LLM (Simple Mode):

# Works without any LLM - uses simple response generation
response = chat.chat("What is quantum computing?")
print(response)

Session Management:

# Start a new session
chat.start_session(session_id="my_session")

# Chat with conversation history
response1 = chat.chat("Tell me about quantum computing")
response2 = chat.chat("What are the applications?")  # Uses previous context

# Export conversation
chat.export_session("conversation.json")

CLI Usage

MemPack provides a command-line interface for building, searching, and managing knowledge packs:

# Build from a folder of markdown/text files
python3 -m mempack build --src ./examples/notes --out ./kb \
  --chunk-size 300 --chunk-overlap 50 \
  --embed-model all-MiniLM-L6-v2

# Search the knowledge pack
python3 -m mempack search --kb ./kb --query "quantum computing" --topk 5

# Chat with the knowledge pack (NEW!)
python3 -m mempack chat --kb ./kb --query "What is quantum computing?" --verbose

# Verify integrity
python3 -m mempack verify --kb ./kb

# Display information about the knowledge pack
python3 -m mempack info --kb ./kb

# Export chunks to JSON
python3 -m mempack export --kb ./kb --output chunks.json --format json

Available Commands

  • build - Create a knowledge pack from source files
  • search - Search for relevant chunks
  • chat - Interactive chat using context retrieval
  • verify - Check file integrity
  • info - Display knowledge pack information
  • export - Export chunks to various formats

Alternative Usage Methods

You can also use the CLI in other ways:

# Using Python import
python3 -c "from mempack import cli; cli()" search --kb ./kb --query "AI"

# Using the mempack_cli function
python3 -c "from mempack import mempack_cli; mempack_cli()" chat --kb ./kb --query "What is AI?"

Shell Alias (Optional)

For easier usage, add this to your ~/.bashrc or ~/.zshrc:

alias mempack='python3 -m mempack'

Then you can use:

mempack --help
mempack chat --kb ./kb --query "What is quantum computing?"

Two-File Format

๐Ÿ”ง Transparent, inspectable, and portable - no black boxes, no vendor lock-in.

kb.mpack โ€” Container File

  • Header: Magic bytes, version, flags, section offsets
  • Config: Embedding model, dimensions, compression settings
  • TOC: Chunk metadata, block information, optional tag index
  • Blocks: Compressed text chunks (Zstd by default)
  • Checksums: Per-block integrity verification
  • ECC: Optional Reed-Solomon error correction

kb.ann โ€” ANN Index File

  • Header: Magic bytes, algorithm (HNSW), dimensions, parameters
  • Payload: Memory-mappable HNSW graph structure
  • IDs: Mapping from vector IDs to chunk IDs

Performance

โšก Enterprise-grade performance with zero infrastructure overhead.

  • Search latency: p50 โ‰ค 40ms, p95 โ‰ค 120ms (1M vectors, 384-dim, HNSW)
  • Block fetch: โ‰ค 1.5ms typical (zstd decompression)
  • Memory usage: Efficient block caching with LRU eviction
  • Cold start: < 100ms (vs minutes for traditional vector stores)
  • Scalability: Handles millions of vectors with minimal memory footprint

API Reference

MemPackEncoder

class MemPackEncoder:
    def __init__(
        self,
        *,
        compressor: str = "zstd",
        chunk_size: int = 300,
        chunk_overlap: int = 50,
        embedding_backend: Optional[EmbeddingBackend] = None,
        index_type: str = "hnsw",
        index_params: Optional[dict] = None,
        ecc: Optional[dict] = None,
        progress: bool = True,
    ): ...

    def add_text(self, text: str, meta: Optional[dict] = None) -> None: ...
    def add_chunks(self, chunks: list[dict] | list[str]) -> None: ...
    def build(
        self,
        *,
        pack_path: str,
        ann_path: str,
        embed_batch_size: int = 64,
        workers: int = 0
    ) -> BuildStats: ...

MemPackRetriever

class MemPackRetriever:
    def __init__(
        self,
        *,
        pack_path: str,
        ann_path: str,
        embedding_backend: Optional[EmbeddingBackend] = None,
        mmap: bool = True,
        block_cache_size: int = 1024,
        io_batch_size: int = 64,
        ef_search: int = 64,
        prefetch: bool = True,
    ): ...

    def search(self, query: str, top_k: int = 5, filter_meta: Optional[dict] = None) -> list[SearchHit]: ...
    def get_chunk_by_id(self, chunk_id: int) -> dict: ...
    def stats(self) -> RetrieverStats: ...

Configuration

HNSW Parameters

  • M: Number of bi-directional links (default: 32)
  • efConstruction: Size of dynamic candidate list (default: 200)
  • efSearch: Size of dynamic candidate list during search (default: 64)

Compression

  • zstd: Fast compression with good ratio (default)
  • deflate: Standard gzip compression
  • none: No compression

Chunking

  • chunk_size: Target chunk size in characters (default: 300)
  • chunk_overlap: Overlap between chunks (default: 50)

Integrity & Error Correction

MemPack includes built-in integrity checking with XXH3 checksums per block. Optional Reed-Solomon error correction can be enabled:

encoder = MemPackEncoder(ecc={"k": 10, "m": 2})  # 10 data + 2 parity blocks

Development

Setup

git clone https://github.com/mempack/mempack
cd mempack
pip install -e ".[dev]"

Testing

make test

Linting

make lint

Benchmarks

make bench

License

MIT License - see LICENSE file for details.


๐Ÿš€ Ready to Get Started?

Stop overpaying for slow vector databases! MemPack delivers:

  • โšก 3x faster queries than alternatives
  • ๐Ÿ’พ 75% less memory usage
  • ๐Ÿ“ฆ Zero infrastructure complexity
  • ๐Ÿ”’ 100% offline capability
  • ๐Ÿ’ฐ Unlimited queries for one-time cost

Install MemPack now | See use cases | View benchmarks

๐Ÿ’ก Questions? Check out our examples or open an issue on GitHub.

Roadmap

  • Multiple Packs: Create separate packs for different content and search across them
  • Incremental Updates: Support for adding new content to existing packs without full rebuild
  • IVF-PQ backend for ultra-large corpora
  • Quantized vectors (int8) support
  • Streaming append API
  • HTTP server for remote access
  • More embedding backends (OpenAI, Vertex AI)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mempack-0.1.0.tar.gz (59.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mempack-0.1.0-py3-none-any.whl (64.9 kB view details)

Uploaded Python 3

File details

Details for the file mempack-0.1.0.tar.gz.

File metadata

  • Download URL: mempack-0.1.0.tar.gz
  • Upload date:
  • Size: 59.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for mempack-0.1.0.tar.gz
Algorithm Hash digest
SHA256 a38812704d1d71814036630a6afe4eef9d9e2b4bbaffda6767926a7e29362360
MD5 a634faf40ee92ec628ebf0ac18a96318
BLAKE2b-256 46963707dec6a540399aabc64138e10258841e3544105f770b91baeaf39eb62b

See more details on using hashes here.

File details

Details for the file mempack-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: mempack-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 64.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for mempack-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ee08d5442d9bff7b884c6de26312b28e62bf0a34e4a096882b19f85cf142ab55
MD5 a5305af7451316a6263eaaf640131f38
BLAKE2b-256 937a1ca245f939f4846da12d73d26cb189cf55d889006265d69e6fb1018f1dd3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page