当前位置: 首页 > news >正文

LLMs之RAG:MemoRAG(利用其记忆模型来实现对整个数据库的全局理解)的简介、安装和使用方法、案例应用之详细攻略

LLMs之RAG:MemoRAG(利用其记忆模型来实现对整个数据库的全局理解)的简介、安装和使用方法、案例应用之详细攻略

目录

MemoRAG的简介

0、更新日志

1、特性

2、路线图

MemoRAG的安装和使用方法

1、安装

安装依赖项

T1、从源码安装

T2、通过pip安装

2、使用方法

MemoRAG的Lite模式

MemoRAG的基本使用

使用长LLM作为记忆模型

摘要任务

使用API作为生成器

支持的生成器API

记忆模型的使用

记忆增强检索的使用

基准评估

评估

数据集

3、MemoRAG演示

T1、脚本演示

T2、在Google Colab上免费试用MemoRAG

MemoRAG的案例应用


MemoRAG的简介

MemoRAG:通过记忆启发的知识发现迈向下一代RAG为RAG赋予基于记忆的数据接口,适用于各种用途的应用!

MemoRAG是一个建立在高效、超长记忆模型之上的创新RAG框架。与主要处理具有明确信息需求查询的标准RAG不同,MemoRAG利用其记忆模型来实现对整个数据库的全局理解。通过从记忆中回忆特定于查询的线索,MemoRAG增强了证据检索,从而生成更准确且上下文丰富的响应。

GitHub地址:GitHub - qhjqhj00/MemoRAG: Empowering RAG with a memory-based data interface for all-purpose applications!

0、更新日志

[21/09/24] MemoRAG引入了Lite模式,只需几行代码即可启用针对数百万个token的记忆增强型RAG处理。更多细节请参阅示例笔记本。
[13/09/24] MemoRAG增加了Meta-Llama-3.1-8B-Instruct和Llama3.1-8B-Chinese-Chat作为记忆模型,请参见示例。
[10/09/24] 我们发布了MemoRAG的技术报告。
[09/09/24] 您可以在Google Colab上免费试用MemoRAG。
[05/09/24] 可以在TommyChien/memorag-qwen2-7b-inst获取基于Qwen2的记忆模型
[03/09/24] 可以在TommyChien/memorag-mistral-7b-inst获取基于Mistral的记忆模型
[01/09/24] 项目启动!

1、特性

>> 全局记忆:单个上下文中处理多达一百万个token,提供对大量数据集的全面理解。
>> 优化&灵活:轻松适应新任务,仅需几个小时的额外训练即可达到优化性能。
>> 上下文线索:从全局记忆生成精确线索,将原始输入与答案联系起来,并解锁复杂数据中的隐藏见解。
>> 高效缓存:加快上下文预填充速度达30倍,支持缓存分块、索引和编码。
>> 上下文重用:一次编码长上下文并支持重复使用,在需要反复访问数据的任务中提高效率。

2、路线图

MemoRAG目前正处于积极开发阶段,资源和原型会持续发布在这个仓库中。
代码 / 模型 / 数据集发布
支持OpenAI/Azure模型
技术报告发布
支持中文
演示代码发布
记忆模型训练代码发布
轻量化优化
加速推理
集成任何检索方法
丰富记忆能力

注意:MemoRAG近期的目标是通过工程改进实现轻量化优化,并增强其记忆能力,使其能够适应更广泛的应用并支持更长的上下文(例如超过一百万个token)。

MemoRAG的安装和使用方法

1、安装

要使用Memorizer和MemoRAG,您需要安装Python以及所需的库。可以使用以下命令安装必要的依赖项:

安装依赖项

pip install torch==2.3.1
conda install -c pytorch -c nvidia faiss-gpu=1.8.0
T1、从源码安装

首先克隆此仓库

cd MemoRAG
pip install -e .

T2、通过pip安装

pip install memorag

对于快速开始,我们提供了一个笔记本,用于说明MemoRAG的所有功能。

2、使用方法

MemoRAG的Lite模式

我们介绍了MemoRAG的Lite模式,旨在为MemoRAG管道提供快捷友好的体验。只需几行代码,您就可以轻松尝试MemoRAG。虽然建议从拥有24GiB内存的GPU开始,但在大多数情况下,默认设置下16GiB GPU也能处理该管道。

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))

MemoRAG Lite易于使用,支持多达数百万token的英文或中文上下文。虽然它可能与其他语言一起工作,但性能可能会下降,因为默认提示是英文的。关于MemoRAG Lite的更多详情,请参阅示例笔记本。

MemoRAG的基本使用

MemoRAG易于使用,可以直接使用HuggingFace模型初始化。通过使用MemoRAG.memorize()方法,记忆模型会在较长的输入上下文中构建全局记忆。根据经验,使用默认参数设置时,TommyChien/memorag-qwen2-7b-inst可以处理高达400K token的上下文,而TommyChien/memorag-mistral-7b-inst可以管理高达128K token的上下文。通过增加beacon_ratio参数,可以扩展模型处理更长上下文的能力。例如,当beacon_ratio=16时,TommyChien/memorag-qwen2-7b-inst可以处理高达一百万个token。

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: if not specify, use memery model as the generatorcache_dir="path_to_model_cache",  # Optional: specify local model cache directoryaccess_token="hugging_face_access_token",  # Optional: Hugging Face access tokenbeacon_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}")

运行上述代码时,编码后的键值(KV)缓存、Faiss索引和分块段落将存储在指定的save_dir中。之后,如果再次使用相同的上下文,则可以从磁盘快速加载数据:

pipe.load("cache/harry_potter/", print_stats=True)

通常,加载缓存权重是非常高效的。例如,使用TommyChien/memorag-qwen2-7b-inst作为记忆模型时,编码、分块和索引200K-token上下文大约需要35秒,但从缓存文件加载只需要1.5秒。

使用长LLM作为记忆模型

最近的LLM由于它们不断扩大的上下文窗口,已经成为了有效的记忆模型。MemoRAG现在支持利用这些长上下文LLM作为记忆模型,并利用MInference优化上下文预填充。我们测试了Meta-Llama-3.1-8B-Instruct和Llama3.1-8B-Chinese-Chat作为记忆模型,两者都原生支持128K的上下文长度。我们目前正在探索其他合适的LLM并优化策略以进一步增强记忆机制和上下文长度。有关详细使用说明,请参阅提供的脚本和笔记本:

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 Englishret_model_name_or_path="BAAI/bge-m3",# cache_dir="path_to_model_cache",  # to specify local model cache directory (optional)# access_token="hugging_face_access_token"  # to specify local model cache directory (optional))

之后,您可以像往常一样使用MemoRAG的功能。

摘要任务

要执行摘要任务,请使用以下脚本:

res = pipe(context=context, task_type="summarize", max_new_tokens=512)
print(f"MemoRAG summary of the full book:\n {res}")

使用API作为生成器

如果您想使用API作为生成器,请参考下面的脚本:

from memorag import Agent, MemoRAG# API configuration
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)
print(agent.generate("hi!"))  # Test the API# 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",  # Optional: specify local model cache directorycustomized_gen_model=agent,
)# Load previously cached context
pipe.load("cache/harry_potter_qwen/", print_stats=True)# Use the loaded context for question answering
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)
print(f"MemoRAG with GPT-3.5 generated answer: \n{res}")

支持的生成器API

内置的Agent对象支持来自openai和deepseek的模型。以下是初始化这些模型的配置:

# Using deepseek models
model = ""
source = "deepseek"
api_dict = {"base_url": "","api_key": ""
}# Using openai models
model = ""
source = "openai"
api_dict = {"api_key": ""
}

记忆模型的使用

记忆模型可以独立使用来存储、回忆和交互上下文。这里有一个例子:

from memorag import Agent, MemoRAG# API configuration
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)
print(agent.generate("hi!"))  # Test the API# 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",  # Optional: specify local model cache directorycustomized_gen_model=agent,
)# Load previously cached context
pipe.load("cache/harry_potter_qwen/", print_stats=True)# Use the loaded context for question answering
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)
print(f"MemoRAG with GPT-3.5 generated answer: \n{res}")

记忆增强检索的使用

除了独立的记忆模型之外,MemoRAG还提供了记忆增强检索功能。这允许基于从记忆中回忆起的线索来改善证据检索。

from memorag import MemoRAG# Initialize MemoRAG pipeline
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",  # Optional: specify local model cache directoryaccess_token="hugging_face_access_token"  # Optional: Hugging Face access token
)# Load and memorize the context
test_txt = open("harry_potter.txt").read()
pipe.memorize(test_txt, save_dir="cache/harry_potter/", print_stats=True)# Define the query
query = "How are the mutual relationships between the main characters?"# Recall clues from memory
clues = pipe.mem_model.recall(query).split("\n")
clues = [q for q in clues if len(q.split()) > 3]  # Filter out short or irrelevant clues
print("Clues generated from memory:\n", clues)# Retrieve relevant passages based on the recalled clues
retrieved_passages = pipe._retrieve(clues)
print("\n======\n".join(retrieved_passages[:3]))

基准评估

以下是结合三种生成模型对记忆模型进行实验的结果。我们在三个基准上测试了MemoRAG。每个区块的最佳结果已加粗显示。

DatasetNarrativeQAQasperMultifieldQAMusique2WikiHotpotQAMultiNewsGovReportEn.sumEn.qaFinLegalMix
LongBenchInfBenchUltraDomain
Generator: Llama3-8B-Instruct-8K
Full21.343.446.623.538.247.124.623.613.16.734.233.242.7
BGE-M322.144.350.222.236.748.422.120.112.115.141.440.646.4
Stella-v512.335.244.422.133.341.922.120.711.714.841.933.744.9
RQ-RAG20.243.949.122.736.144.520.621.012.013.339.536.844.5
HyDE22.144.350.222.236.748.4---19.141.440.646.4
MemoRAG22.845.750.728.451.457.027.427.914.116.147.847.955.5
Generator: Phi-3-mini-128K
Full21.435.047.319.035.542.125.623.713.015.244.840.544.7
BGE-M320.333.044.321.135.442.117.719.89.616.341.741.243.7
Stella-v513.732.443.521.035.640.620.318.210.019.542.835.143.9
RQ-RAG19.634.146.521.936.141.720.118.610.416.141.840.943.2
HyDE18.736.047.520.536.842.7---19.643.141.644.2
MemoRAG27.543.952.233.954.154.832.926.315.722.951.551.055.6
Generator: Mistral-7B-Instruct-v0.2-32K
Full20.829.246.318.920.637.623.020.412.412.336.535.842.1
BGE-M317.329.546.318.520.336.224.326.113.512.240.542.041.1
Stella-v513.523.742.118.622.231.921.118.513.29.740.934.942.1
RQ-RAG17.129.247.019.121.537.022.118.613.112.744.344.643.4
HyDE17.429.546.318.520.136.2---12.242.835.143.9
MemoRAG23.131.250.026.930.342.927.131.617.915.448.051.253.6
MemoRAG-qwen222.232.749.631.433.744.427.031.516.817.648.752.348.6

评估

要评估MemoRAG,请使用以下脚本:

cd examples
bash longbench/eval.sh

我们将很快更新其他评估脚本。

数据集

UltraDomain基准: this repo.

其他评估数据: this repo.

3、MemoRAG演示

T1、脚本演示

我们将提供一个玩具演示来展示MemoRAG的功能,您可以使用以下脚本进行尝试:

streamlit run demo/demo.py

之后,您可以看到如下所示的演示

T2、在Google Colab上免费试用MemoRAG

您可以直接在Google Colab上免费试用MemoRAG。

地址:https://colab.research.google.com/drive/1fPMXKyi4AwWSBkC7Xr5vBdpPpx9gDeFX?usp=sharing

在此笔记本中,我们在由Google Colab提供的具有15GiB内存的单一T4 GPU上运行完整的MemoRAG管道(记忆模型+检索器+生成模型)。尽管资源有限,MemoRAG仍能处理示例书籍内容的大约一半(~68K token),并执行所有功能。

MemoRAG的案例应用

持续更新中……

相关文章:

  • 【自学笔记】支持向量机(4)——支持向量回归SVR
  • 国内可用ChatGPT-4中文镜像网站整理汇总【持续更新】
  • 三.python入门语法2
  • OSPF相关基础介绍及基础配置,网络工程师必修
  • redis Redis-Cluster常用命令与Redis性能监控
  • SSH防止暴力破解
  • 2024东湖高新下半年水测公示名单啦
  • 把命令的语气改成聊天的方式
  • 部署Activiti Modeler全流程(工作流引擎Activiti设计插件)
  • 软件测试CNAS实验室认证|检测报告三级审核,每一级审核什么?
  • tensorflow底层架构
  • 恢复丢失的数据:恢复数据库网络解决方案
  • 水平分库分表的方法策略
  • Android开发小贴士
  • 高级java每日一道面试题-2024年9月26日-运维篇[分布式篇]-如何保证每个服务器的时间都是同步的?
  • [分享]iOS开发-关于在xcode中引用文件夹右边出现问号的解决办法
  • 【5+】跨webview多页面 触发事件(二)
  • 【前端学习】-粗谈选择器
  • 【跃迁之路】【699天】程序员高效学习方法论探索系列(实验阶段456-2019.1.19)...
  • Hexo+码云+git快速搭建免费的静态Blog
  • JAVA SE 6 GC调优笔记
  • mongo索引构建
  • Node项目之评分系统(二)- 数据库设计
  • Redis字符串类型内部编码剖析
  • vue2.0项目引入element-ui
  • vue-router 实现分析
  • windows下mongoDB的环境配置
  • 开年巨制!千人千面回放技术让你“看到”Flutter用户侧问题
  • 聊聊spring cloud的LoadBalancerAutoConfiguration
  • 前端技术周刊 2019-02-11 Serverless
  • 巧用 TypeScript (一)
  • 我是如何设计 Upload 上传组件的
  • 小程序 setData 学问多
  • 协程
  • “十年磨一剑”--有赞的HBase平台实践和应用之路 ...
  • 翻译 | The Principles of OOD 面向对象设计原则
  • ​3ds Max插件CG MAGIC图形板块为您提升线条效率!
  • ​LeetCode解法汇总2182. 构造限制重复的字符串
  • # Swust 12th acm 邀请赛# [ A ] A+B problem [题解]
  • #{}和${}的区别是什么 -- java面试
  • #LLM入门|Prompt#1.7_文本拓展_Expanding
  • $NOIp2018$劝退记
  • ()、[]、{}、(())、[[]]命令替换
  • (1)虚拟机的安装与使用,linux系统安装
  • (C语言)fgets与fputs函数详解
  • (C语言)求出1,2,5三个数不同个数组合为100的组合个数
  • (第一天)包装对象、作用域、创建对象
  • (动手学习深度学习)第13章 计算机视觉---微调
  • (翻译)Entity Framework技巧系列之七 - Tip 26 – 28
  • (四)Android布局类型(线性布局LinearLayout)
  • (原创)攻击方式学习之(4) - 拒绝服务(DOS/DDOS/DRDOS)
  • (自用)仿写程序
  • *** 2003
  • **python多态
  • .net core webapi Startup 注入ConfigurePrimaryHttpMessageHandler