MemoRAG
repository·main·Indexed 25 days ago
https://github.com/qhjqhj00/memoragA next-generation Retrieval-Augmented Generation (RAG) framework that uses a memory-inspired model to provide global understanding of large datasets. MemoRAG utilizes a memory-based data interface to recall query-specific clues, enhancing evidence retrieval and response generation. It supports long-context LLMs, external APIs (OpenAI, DeepSeek, Azure) as generators, and provides a simplified 'MemoRAG Lite' version for quick experimentation.
What's inside MemoRAG
- MemoRAG is a RAG (Retrieval-Augmented Generation) framework that utilizes a memory-based data interface to achieve a global understanding of entire databases. Unlike standard RAG which focuses on explicit information needs in queries, MemoRAG uses a memory model to recall query-specific clues, enhancing evidence retrieval and generating more contextually rich responses. It is designed to handle massive datasets by bridging raw input to answers through contextual clues generated from global memory.
Install MemoRAG from source
mainTo install MemoRAG from the source code, clone the repository and install it in editable mode:
# clone this repo first cd MemoRAG pip install -e .Install MemoRAG dependencies
mainMemoRAG requires
torchandfaiss-gpu. Use the following commands to install the necessary dependencies:pip install torch==2.3.1 conda install -c pytorch -c nvidia faiss-gpu=1.8.0Evaluate MemoRAG on benchmarks
mainTo evaluate the performance of MemoRAG, use the provided evaluation scripts in the
examplesdirectory.cd examples bash longbench/eval.shInstall MemoRAG via pip
mainYou can install the MemoRAG package directly using pip:
pip install memoragUse APIs (OpenAI, DeepSeek, Azure) as generators
mainYou can use external APIs as the generation model by passing an
Agentobject to thecustomized_gen_modelparameter of theMemoRAGconstructor.Supported Sources:
openaideepseekazure(via customapi_dictconfiguration)
Configuration Formats:
For
deepseek:model = "..." source = "deepseek" api_dict = { "base_url": "", "api_key": "" }For
openai:model = "..." source = "openai" api_dict = { "api_key": "" }from memorag import Agent, MemoRAG # API configuration for Azure api_dict = { "endpoint": "", "api_version": "2024-02-15-preview", "api_key": "" } model = "gpt-35-turbo-16k" source = "azure" # Initialize Agent with the API agent = Agent(model, source, api_dict) # Initialize MemoRAG pipeline with a customized generator model pipe = MemoRAG( mem_model_name_or_path="TommyChien/memorag-qwen2-7b-inst", ret_model_name_or_path="BAAI/bge-m3", cache_dir="path_to_model_cache", customized_gen_model=agent, ) # Use the loaded context query = "How are the mutual relationships between the main characters?" context = open("harry_potter.txt").read() res = pipe(context=context, query=query, task_type="memorag", max_new_tokens=256)Use MemoRAG Lite for quick experimentation
mainMemoRAG Lite is a simplified version of the pipeline designed for a quick, user-friendly experience. It supports English or Chinese contexts up to millions of tokens. While it works with other languages, performance may degrade due to English-default prompts.
Hardware Note: While a 24GiB GPU is recommended, a 16GiB GPU can typically handle the pipeline under default settings.
from memorag import MemoRAGLite pipe = MemoRAGLite() context = open("examples/harry_potter.txt").read() pipe.memorize(context, save_dir="harry_potter", print_stats=True) query = "What's the book's main theme?" print(pipe(query))Use long-context LLMs as memory models
mainMemoRAG supports leveraging long-context LLMs (like Llama 3.1) as memory models by utilizing
MInferenceto optimize context prefilling. This allows the system to benefit from the native large context windows of these models.from memorag import MemoRAG model = MemoRAG( mem_model_name_or_path="shenzhi-wang/Llama3.1-8B-Chinese-Chat", # For Chinese # mem_model_name_or_path="meta-llama/Meta-Llama-3.1-8B-Instruct", # For English ret_model_name_or_path="BAAI/bge-m3", # cache_dir="path_to_model_cache", # access_token="hugging_face_access_token" )Initialize and use the MemoRAG pipeline
mainThe standard
MemoRAGclass allows for full control over the memory, retrieval, and generation models. You can initialize it directly with HuggingFace model paths.Context Capacity:
TommyChien/memorag-qwen2-7b-inst: ~400K tokens (can reach 1M tokens withbeacon_ratio=16).TommyChien/memorag-mistral-7b-inst: ~128K tokens.
Caching: When you call
.memorize(), the encoded KV cache, Faiss index, and chunked passages are stored in thesave_dir. You can reload this data later using.load()to avoid re-processing the context.from memorag import MemoRAG # Initialize MemoRAG pipeline pipe = MemoRAG( mem_model_name_or_path="TommyChien/memorag-mistral-7b-inst", ret_model_name_or_path="BAAI/bge-m3", gen_model_name_or_path="mistralai/Mistral-7B-Instruct-v0.2", # Optional cache_dir="path_to_model_cache", # Optional access_token="hugging_face_access_token", # Optional beacon_ratio=4 ) context = open("examples/harry_potter.txt").read() query = "How many times is the Chamber of Secrets opened in the book?" # Memorize the context and save to cache pipe.memorize(context, save_dir="cache/harry_potter/", print_stats=True) # Generate response using the memorized context res = pipe(context=context, query=query, task_type="memorag", max_new_tokens=256) print(f"MemoRAG generated answer: \n{res}") # To reload from cache later: pipe.load("cache/harry_potter/", print_stats=True)Quick Start with MemoRAG via Google Colab
mainYou can try MemoRAG for free using a Google Colab notebook. This setup allows you to run the complete MemoRAG pipeline (Memory Model + Retriever + Generation Model) on a single T4 GPU (15GiB memory). It is capable of processing approximately 68K tokens (e.g., half of the provided Harry Potter example book) and performing all core functions.
https://colab.research.google.com/drive/1fPMXKyi4AwWSBkC7Xr5vBdpPpx9gDeFX?usp=sharingUnderstand the Beacon forward pass mechanism
mainThe
_beacon_forwardmethod implements a specialized execution loop that interacts with aMemoryobject. Unlike a standard transformer forward pass, it operates in steps:- Prepare:
self.memory.prepare(...)is called withinput_ids,attention_mask, andlabels. - Step Loop: While
self.memory.finishis false, the model callsself.memory.step()to retrieve the next chunk ofinput_ids,attention_mask,position_ids,past_key_values, andlabels. - Native Forward: The model executes
_native_forward(...)on the retrieved chunk. - Update: The model updates the memory state using
self.memory.update_memory(outputs.past_key_values)andself.memory.update_loss(...). - Output: Once the loop finishes,
self.memory.output(outputs)provides the final model outputs.
- Prepare:
Validate rope_scaling configuration
mainThe
rope_scalingparameter inMistralConfigmust be a dictionary containing exactly two keys:typeandfactor.type: Must be either'linear'or'dynamic'.factor: Must be afloatstrictly greater than1.0.