浦语学习笔记

官方文档地址:
https://github.com/InternLM/Tutorial/tree/camp4/docs/L1/LlamaIndex

前置知识

检索增强生成(Retrieval Augmented Generation,RAG)技术用于更新模型的权重,另一个就是外部的方式,给模型注入格外的上下文或者说外部信息,不改变它的的权重,相较于训练模型更易于实现。
通过丰富外部信息使大模型生成更准确更丰富的文档。
RAG的工作原理
非参数记忆,利于处理知识密集型任务,挺准确的事实性回答,通过检索增强可以生成多样性的内容。
向量数据库(Vector-DB)
承担整体数据存储任务,相当于将数据向量化(固定长度)后与问题相匹配(余弦相似度计算),之后返回最合适的索引。向量表示包括使用更高级的文本编码技术例如句子嵌入或段落嵌入等,现在通常使用的是基于大模型的嵌入模型,开源应用也最多。
RAG常见优化方法
LlamaIndex
针对大模型的工具,帮助构建知识库、进行搜索,提供高效、可扩展的文本索引和检索功能。
对于大规模数据有很好的处理方式,能够提交高效的检索机制,并且支持很多模型的API,常见模型基本都能支持。
提供完整工具包
 

首先建立虚拟机与本地之间的映射
ssh -p 45162 root@ssh.intern-ai.org.cn -C -L 8501:127.0.0.1:8501 -o StrictHostKeyChecking=no

环境、模型准备

  1. 创建30%的A100、Cuda11.7-conda的镜像
  2. 进入开发机之后运行
conda create -n llamaindex python=3.10
conda env list
conda activate llamaindex
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==0.7.0 protobuf==5.26.1 #安装依赖包
conda activate 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
  1. 下载Sentence Transformer模型
cd ~
mkdir llamaindex_demo
mkdir model
cd ~/llamaindex_demo
touch download_hf.py
将下列代码内容写入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')
关于镜像使用可以移步至 HF Mirror

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

cd ~/model
ln -s /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-1_8b/ ./
cd ~/llamaindex_demo
touch llamaindex_internlm.py
将下列代码写入llamaindex_internlm.py
运行后显示
显然这个回答是错误的,是因为现在模型的训练数据并没有相关的知识,这个回答没有依据。

LlamaIndex RAG

  1. 下载词嵌入向量依赖与知识库
conda activate llamaindex
pip install llama-index-embeddings-huggingface==0.2.0 llama-index-embeddings-instructor==0.1.3

cd ~/llamaindex_demo
mkdir data
cd data
git clone https://github.com/InternLM/xtuner.git
mv xtuner/README_zh-CN.md ./

cd ~/llamaindex_demo
touch llamaindex_RAG.py
然后将下列内容写入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

#初始化一个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)
在运行之前也需要先查看pytorch的版本,降到2.0.1才能正常运行
现在模型已经能够回答相关问题了。并且我们注意到RAG给出了文档来源,也就是这个方法能够帮助我们进行文本的溯源。这样就建立了一个简单的demo。

LlamaIndex web

  1. 配置环境并创建文件
pip install streamlit==1.36.0

cd ~/llamaindex_demo
touch app.py
将下列内容写入app.py
import streamlit as st
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.huggingface import HuggingFaceLLM

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="/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()

    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)
运行文件,显示:

基础任务 (完成此任务即完成闯关)

  • 任务要求:基于 LlamaIndex 构建自己的 RAG 知识库,寻找一个问题 A 在使用 LlamaIndex 之前InternLM2-Chat-1.8B模型不会回答,借助 LlamaIndex 后 InternLM2-Chat-1.8B 模型具备回答 A 的能力,截图保存。
添加相关内容之后它能够进行正常回答

闯关材料提交 (完成任务并且提交材料时为闯关成功)

 
posted @ 2024-10-27 19:16  yuooo  阅读(14)  评论(0编辑  收藏  举报