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

书生大模型实战营学习[7] InternLM + LlamaIndex RAG 实践

在这里插入图片描述

环境配置

选择30%A100做本次任务

conda create -n llamaindex python=3.10
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
pip install  protobuf

安装Llamaindex

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

下载 Sentence Transformer 模型
Sentence Transformer模型是一种用于句子嵌入(sentence embedding)技术的深度学习模型,旨在将句子或文本段落转换为固定长度的向量表示。这种表示可以用于多种自然语言处理任务,例如文本相似度计算、检索和分类等。

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

执行该脚本

cd /root/llamaindex_demo
conda activate llamaindex
python download_hf.py

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

对原始internlm2-chat-1_8b进行测试

首先把InternLM2 1.8B 软连接出来

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

创建一个python文件:

cd ~/llamaindex_demo
touch llamaindex_internlm.py

将一下代码粘贴到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)

运行查看结果:

conda activate llamaindex
cd ~/llamaindex_demo/
python llamaindex_internlm.py

输出:

xtuner是一款用于播放音乐的软件,它支持多种音频格式,包括MP3、WAV、WMA、FLAC、AAC、APE、OGG、WMA、WAV、WMA

在这里插入图片描述

模型并不能很好的回答出正确答案。

RAG增强internlm2-chat-1_8b测试

首先安装词嵌入向量依赖:

conda activate llamaindex
pip install llama-index-embeddings-huggingface llama-index-embeddings-instructor

然后获取知识库:

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

创建一个pythonllamaindex_RAG.py文件:

cd ~/llamaindex_demo
touch llamaindex_RAG.py

将以下代码粘贴到llamaindex_RAG.py中:


from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settingsfrom 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_modelllm = 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)
conda activate llamaindex
cd ~/llamaindex_demo/
python llamaindex_RAG.py

输出:
在这里插入图片描述

LlamaIndex web

pip install streamlit==1.36.0
#创建py文件
cd ~/llamaindex_demo
touch 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 HuggingFaceLLMst.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_modelllm = 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 = llmdocuments = 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)

运行

streamlit run app.py

访问:

ssh -CNg -L 8501:127.0.0.1:8501 root@ssh.intern-ai.org.cn -p 48693(需要换成自己的端口号)

在这里插入图片描述

http://www.lryc.cn/news/447488.html

相关文章:

  • 【MySQL】数据库--索引
  • [大语言模型-论文精读] ACL2024-长尾知识在检索增强型大型语言模型中的作用
  • “迷茫野路子到AI大模型高手:一张图解产品经理晋升之路和能力构建“
  • 可看见车辆行人的高清实时视频第2辑
  • 基于饥饿游戏搜索优化随机森林的数据回归预测 MATLAB 程序 HGS-RF
  • 一天面了8个Java后端,他们竟然还在背5年前的八股文!
  • python功能测试
  • 【秋招笔试】09.25华子秋招(已改编)-三语言题解
  • 【中级通信工程师】终端与业务(四):通信产品
  • 数据科学 - 字符文本处理
  • python之装饰器、迭代器、生成器
  • Go语言实现后台管理系统如何根据角色来动态显示栏目
  • 【深度学习】【TensorRT】【C++】模型转化、环境搭建以及模型部署的详细教程
  • LeetCode(Python)-贪心算法
  • 【C/C++】【基础数论】33、算数基本定理
  • 聚簇索引与非聚簇索引
  • “类型名称”在Go语言规范中的演变
  • c++----继承(初阶)
  • 数据库系列(1)常见的四种非关系型数据库(NoSQL)
  • 大规模预训练语言模型的参数高效微调
  • 一场大模型面试,三个小时,被撞飞了
  • Python每次for循环向list中添加多个元素
  • Java爬虫抓取数据的艺术
  • Unity场景内画车道线(根据五阶曲线系数)
  • IPLOOK百万级用户容量核心网惊艳亮相北京PT展
  • 家庭网络的ip安全性高吗
  • LLM阅读推荐
  • 计算机网络笔记001
  • 如何用IDEA连接HBase
  • 【JS代码规范】如何优化if-else代码规范