InternLM + LlamaIndex RAG 实践 - 第四期书生大模型实战营实验记录(基础岛-第4关)

213 阅读7分钟

我目前正在参加“书生大模型实战营”。这是一个旨在帮助学员掌握大模型开发和应用的实战课程。

为了更好地记录完成过程,我根据官方提供的教程文档提取了核心步骤,并去掉了详细的背景知识介绍和说明,这样后续一个手册查找起来会更加直观。

但建议大家在实际学习过程中还是多看看原文,因为原文档确实非常的详细和完整,方便了解每一步的具体原因和背后的原理,这样有助于更牢固地掌握知识,提高实战能力。

基础岛-第4关

本地环境:Win11。

原文:github.com/InternLM/Tu…

完成任务步骤记录

任务一:Llamaindex RAG + InternLM(API)

目标:基于 LlamaIndex 构建自己的 RAG 知识库,寻找一个问题 A 在使用 LlamaIndex 之前 浦语 API 不会回答,借助 LlamaIndex 后 浦语 API 具备回答 A 的能力,截图保存。

完成所需时间:30分钟,主要个别包下载安装比较慢。

步骤

  1. 前置准备: 按照入门岛-第1关,启动开发机,并连接上开发机即可。教程中建议开发机资源配置采用:30% A100 * 1。 我更喜欢VS Code连接开发机,后续截图都以VS Code为准。

需要注意,镜像选择 Cuda12.0-conda 镜像。

  1. 配置基础环境

VS Code远程链接开发机后,在VS Code的终端中运行命令:

# 创建新的conda环境,命名为 llamaindex。
conda create -n llamaindex python=3.10

# 激活 llamaindex conda环境。
conda activate llamaindex

# 安装python 依赖包
pip install einops==0.7.0 protobuf==5.26.1

image.png

其中激活conda环境后可以在命令行前面看到标识,如下:

image.png

  1. 安装 Llamaindex

这段时间会稍微长一点,喝杯茶吧。

conda activate llamaindex
pip install llama-index==0.11.20
pip install llama-index-llms-replicate==0.3.0
pip install llama-index-llms-openai-like==0.2.0
pip install llama-index-embeddings-huggingface==0.3.1
pip install llama-index-embeddings-instructor==0.2.1
pip install torch==2.5.0 torchvision==0.20.0 torchaudio==2.5.0 --index-url https://download.pytorch.org/whl/cu121

5. 下载 Sentence Transformer 模型

根据文档,为了速度,直接采用modelscope下载。

cd ~
mkdir llamaindex_demo
mkdir model
cd ~/llamaindex_demo

# 配置git lfs
apt install git-lfs
git lfs install
# 下载
git clone https://www.modelscope.cn/Ceceliachenen/paraphrase-multilingual-MiniLM-L12-v2.git
mv paraphrase-multilingual-MiniLM-L12-v2 /root/model/sentence-transformer

最终模型应该在/root/model/sentence-transformer, 后续代码会到/root/model/sentence-transformer找模型

如果碰到如下提示,就是git lfs未安装,请参考如上命令。

image.png

  1. 下载 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

9. 对比

未使用Llamaindex的结果:

image.png

使用Llamaindex的结果:

image.png

任务二:Llamaindex RAG + InternLM (本地部署)

目标:基于 LlamaIndex 构建自己的 RAG 知识库,寻找一个问题 A 在使用 LlamaIndex 之前 InternLM2-Chat-1.8B 模型不会回答,借助 LlamaIndex 后 InternLM2-Chat-1.8B 模型具备回答 A 的能力,截图保存。

完成所需时间:60分钟,pytorch下载安装较慢,且中间由于操作失误,一次安装浪费了10分钟。

步骤

  1. 前置准备(镜像不同,步骤与任务一相同)

按照入门岛-第1关,新建开发机,镜像选择 Cuda11.7-conda 镜像,连接上开发机即可。 教程中建议开发机资源配置采用:30% A100 * 1。 我更喜欢VS Code连接开发机,后续截图都以VS Code为准。

需要注意,镜像选择 Cuda11.7-conda 镜像,教程建议,避免版本兼容问题。

  1. 配置基础环境(conda环境名称不同,步骤与任务一相同)

VS Code远程链接开发机后,在VS Code的终端中运行命令:

为了与任务一API方式区分,此处conda环境命名为llamaindex2。

# 创建新的conda环境,命名为 llamaindex2。
conda create -n llamaindex2 python=3.10

# 激活 llamaindex conda环境。
conda activate llamaindex2

# 安装python 依赖包
pip install einops==0.7.0 protobuf==5.26.1

其中激活conda环境后可以在命令行前面看到标识,如下:

image.png

  1. 安装 Llamaindex 与 Pytorch

安装Llamaindex 和相关的包:

conda activate llamaindex2
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
pip install llama-index-embeddings-huggingface==0.2.0 llama-index-embeddings-instructor==0.1.3

使用pip freeze确定llama-index-embeddings-huggingface安装成功。

image.png

安装 Pytorch:

有点久,茶都喝了两杯了。

conda install pytorch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 pytorch-cuda=11.7 -c pytorch -c nvidia

5. 下载 Sentence Transformer 模型(可使用任务一环境)

根据文档,为了速度,直接采用modelscope下载。

cd ~
mkdir llamaindex_demo
mkdir model
cd ~/llamaindex_demo

# 配置git lfs
apt install git-lfs
git lfs install
# 下载
git clone https://www.modelscope.cn/Ceceliachenen/paraphrase-multilingual-MiniLM-L12-v2.git
mv paraphrase-multilingual-MiniLM-L12-v2 /root/model/sentence-transformer

最终模型应该在/root/model/sentence-transformer, 后续代码会到/root/model/sentence-transformer找模型

如果碰到如下提示,就是git lfs未安装,请参考如上命令。

image.png

  1. 下载 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

9. 对比

把 InternLM2 1.8B 软连接出来.

cd ~/model
ln -s /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-1_8b/ ./

知识库任务一已经获取,不需要重复执行命令。

未使用Llamaindex的结果:

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)

image.png

使用Llamaindex的结果:


from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings

from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.huggingface import HuggingFaceLLM

#初始化一个HuggingFaceEmbedding对象,用于将文本转换为向量表示
embed_model = HuggingFaceEmbedding(
#指定了一个预训练的sentence-transformer模型的路径
    model_name="/root/model/sentence-transformer"
)
#将创建的嵌入模型赋值给全局设置的embed_model属性,
#这样在后续的索引构建过程中就会使用这个模型。
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}
)
#设置全局的llm属性,这样在索引查询时会使用这个模型。
Settings.llm = llm

#从指定目录读取所有文档,并加载数据到内存中
documents = SimpleDirectoryReader("/root/llamaindex_demo/data").load_data()
#创建一个VectorStoreIndex,并使用之前加载的文档来构建索引。
# 此索引将文档转换为向量,并存储这些向量以便于快速检索。
index = VectorStoreIndex.from_documents(documents)
# 创建一个查询引擎,这个引擎可以接收查询并返回相关文档的响应。
query_engine = index.as_query_engine()
response = query_engine.query("xtuner是什么?")

print(response)

image.png

任务三:部署到Hugging Face

目标:将 Streamlit+LlamaIndex+浦语API的 Space 部署到 Hugging Face。

完成所需时间:60分钟,主要熟悉Space使用。

步骤

前置条件:登录Huggin Face。 文件修改可以通过git clone后修改提交并push,也可以直接通过Hugging Face UI直接在线操作。

  1. 新建Streamlit应用

按照入门岛教程新建Space应用,不过这次选择Streambit应用。

image.png

Files(仓库)下README.md中修改Streamlit版本。

sdk_version: 1.39.0

2. 配置环境

Files(仓库)中建立requirements.txt文件,然后将需要安装的pip包加入其中。

# 安装 Llamaindex和相关的包
llama-index==0.11.20
llama-index-llms-replicate==0.3.0
llama-index-llms-openai-like==0.2.0
llama-index-embeddings-huggingface==0.3.1
llama-index-embeddings-instructor==0.2.1
torch==2.5.0  --index-url https://download.pytorch.org/whl/cu121
torchvision==0.20.0  --index-url https://download.pytorch.org/whl/cu121
torchaudio==2.5.0 --index-url https://download.pytorch.org/whl/cu121
# Sentence Transformer 相关包
transformers
sentence-transformers
# NLTK 相关资源
nltk

所需的知识库直接上传到Files中。

image.png

  1. 应用代码

根据教程代码,修改如下。

api_key 在 Settings中设置Secret。

import streamlit as st
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.legacy.callbacks import CallbackManager
from llama_index.llms.openai_like import OpenAILike
import os

# Create an instance of CallbackManager
callback_manager = CallbackManager()

api_base_url =  "https://internlm-chat.intern-ai.org.cn/puyu/api/v1/"
model = "internlm2.5-latest"
api_key = os.getenv('INTERN_KEY')

llm =OpenAILike(model=model, api_base=api_base_url, api_key=api_key, is_chat_model=True,callback_manager=callback_manager)

st.set_page_config(page_title="llama_index_demo", page_icon="🦜🔗")
st.title("llama_index_demo")

# 初始化模型
@st.cache_resource
def init_models():
    embed_model = HuggingFaceEmbedding(
        model_name="paraphrase-multilingual-MiniLM-L12-v2"
    )
    Settings.embed_model = embed_model

    #用初始化llm
    Settings.llm = llm

    documents = SimpleDirectoryReader("./data").load_data()
    index = VectorStoreIndex.from_documents(documents)
    query_engine = index.as_query_engine()

    return query_engine

# 检查是否需要初始化模型
if 'query_engine' not in st.session_state:
    st.session_state['query_engine'] = init_models()

def greet2(question):
    response = st.session_state['query_engine'].query(question)
    return response

      
# Store LLM generated responses
if "messages" not in st.session_state.keys():
    st.session_state.messages = [{"role": "assistant", "content": "你好,我是你的助手,有什么我可以帮助你的吗?"}]    

    # Display or clear chat messages
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.write(message["content"])

def clear_chat_history():
    st.session_state.messages = [{"role": "assistant", "content": "你好,我是你的助手,有什么我可以帮助你的吗?"}]

st.sidebar.button('Clear Chat History', on_click=clear_chat_history)

# Function for generating LLaMA2 response
def generate_llama_index_response(prompt_input):
    return greet2(prompt_input)

# User-provided prompt
if prompt := st.chat_input():
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.write(prompt)

# Gegenerate_llama_index_response last message is not from assistant
if st.session_state.messages[-1]["role"] != "assistant":
    with st.chat_message("assistant"):
        with st.spinner("Thinking..."):
            response = generate_llama_index_response(prompt)
            placeholder = st.empty()
            placeholder.markdown(response)
    message = {"role": "assistant", "content": response}
    st.session_state.messages.append(message)

4. 运行

所有文件修改后,Hugging Face会自动构建。

image.png