LlamaIndex + InternLM2 RAG实践指南
- 任务要求:基于 LlamaIndex 构建自己的 RAG 知识库,寻找一个问题 A 在使用 LlamaIndex 之前InternLM2-Chat-1.8B模型不会回答,借助 LlamaIndex 后 InternLM2-Chat-1.8B 模型具备回答 A 的能力,截图保存。
环境准备
- 创建并激活Conda虚拟环境:
conda create -n llamaindex python=3.10
conda activate llamaindex
- 安装PyTorch和相关依赖:
conda install pytorch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 pytorch-cuda=11.7 -c pytorch -c nvidia
pip install einops protobuf
- 安装LlamaIndex及其相关组件:
pip install llama-index==0.10.38 llama-index-llms-huggingface==0.2.0 "transformers[torch]==4.41.1" "huggingface_hub[inference]==0.23.1" huggingface_hub==0.23.1 sentence-transformers==2.7.0 sentencepiece==0.2.0
- 创建工作目录并下载必要的模型:
mkdir -p ~/llamaindex_demo/model
cd ~/llamaindex_demo
- 创建并运行下载脚本
download_hf.py
:
import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
os.system('huggingface-cli download --resume-download sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 --local-dir /root/model/sentence-transformer')
- 下载并配置NLTK资源:
cd /root
git clone https://gitee.com/yzy0612/nltk_data.git --branch gh-pages
cd nltk_data
mv packages/* ./
cd tokenizers && unzip punkt.zip
cd ../taggers && unzip averaged_perceptron_tagger.zip
LlamaIndex与HuggingFaceLLM集成
创建 llamaindex_internlm.py
文件,内容如下:
from llama_index.llms.huggingface import HuggingFaceLLM
from llama_index.core.llms import ChatMessage
llm = HuggingFaceLLM(
model_name="/root/model/internlm2-chat-1_8b",
tokenizer_name="/root/model/internlm2-chat-1_8b",
model_kwargs={"trust_remote_code":True},
tokenizer_kwargs={"trust_remote_code":True}
)
rsp = llm.chat(messages=[ChatMessage(content="xtuner是什么?")])
print(rsp)
运行脚本并观察输出:
python llamaindex_internlm.py
我们发现internlm2-chat-1_8b模型并不知道xtuner具体是什么,回答也是基于已经训练的知识库的内容去描述,并没有达到我们想要的效果,接下来就结合RAG的方式来查看效果。
LlamaIndex RAG实现
- 安装额外的依赖:
pip install llama-index-embeddings-huggingface llama-index-embeddings-instructor
- 准备知识库:
mkdir data
cd data
git clone https://github.com/InternLM/xtuner.git
mv xtuner/README_zh-CN.md ./
cd ..
- 创建
llamaindex_RAG.py
文件,内容如下:
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.huggingface import HuggingFaceLLM
# 初始化嵌入模型
embed_model = HuggingFaceEmbedding(
model_name="/root/model/sentence-transformer"
)
Settings.embed_model = embed_model
# 初始化语言模型
llm = HuggingFaceLLM(
model_name="/root/model/internlm2-chat-1_8b",
tokenizer_name="/root/model/internlm2-chat-1_8b",
model_kwargs={"trust_remote_code":True},
tokenizer_kwargs={"trust_remote_code":True}
)
Settings.llm = llm
# 加载文档并创建索引
documents = SimpleDirectoryReader("/root/llamaindex_demo/data").load_data()
index = VectorStoreIndex.from_documents(documents)
# 创建查询引擎并执行查询
query_engine = index.as_query_engine()
response = query_engine.query("xtuner是什么?")
print(response)
运行脚本并观察结果:
python llamaindex_RAG.py
经过RAG优化,可以看到模型已经具备了回答“什么是xtunner”的能力