【RAG】使用Llamaindex框架部署InternLM2-1.8B

【RAG】使用Llamaindex框架部署InternLM2-1.8B

一、前置知识

  • 给模型注入新知识的方式
    • 内部方式:更新模型的权重,但训练代价较大。
    • 外部方式:给模型注入额外的上下文或外部信息,不改变其权重。
  • RAG 工作原理
    • 将问题编码成向量,在向量数据库中找到最相关的文档块(top-k chunks)。
    • 将知识源分割成小块,编码成向量并存储在向量数据库中。
    • 将检索到的文档块与原始问题一起作为提示输入到 LLM 中,生成最终的回答。
  • RAG 效果比对
    • 由于 xtuner 是较新的框架,InternLM2-Chat-1.8B 训练数据库中未收录相关信息,使用 RAG 前问答均未给出准确答案,使用后能获得想要的答案。

二、环境、模型准备

(一)配置基础环境

  • Intern Studio 服务器上部署 LlamaIndex

    • 打开 Intern Studio 界面,点击 创建开发机 配置开发机系统。
    • 填写 开发机名称 后,点击 选择镜像 使用 Cuda11.7-conda 镜像,在资源配置中选择 30% A100 * 1 的选项,立即创建开发机器。
    • 进入开发机后,创建新的 conda 环境,命名为 llamaindex,运行以下命令:
    1
    2
    3
    4
    5
    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
    • 环境激活后,命令行左边会显示当前环境名称。

(二)安装 LlamaIndex

  • 安装 LlamaIndex 和相关的包:

    1
    2
    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 词嵌入模型

  • 新建一个 python 文件,贴入以下代码:

    1
    2
    3
    4
    5
    6
    7
    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')
  • /root/llamaindex_demo 目录下执行该脚本自动开始下载。

(四)下载 NLTK 相关资源

阅读更多