独立隔绝环境LLM外挂知识库与数据库(表格查询方向,text2sql)

1,029 阅读8分钟

数据库与知识库外挂,LLM模型微调,参考操作流程

外挂text2sql数据库模型大小:

image.png

加载文件参考《LLM项目配置》

image.png image.png

一、环境

1.基本环境:

miniconda(自行验证,仅作参考)

wget -c https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
# wget --no-check-certificate https....sh
chmod 777 Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
source ~/.zshrc  # or`.bashrc`
conda -V
(确保已下载3.10.12、3.10,miniconda)
位置:project
. ~/.profile
conda activate base
conda create --prefix=.condas python=3.10
conda activate ./.condas/

2.下载模型:

cd ./model
git lfs install
git clone https://huggingface.co/BAAI/bge-large-zh
等hf网址有关模型

3.注意:

  1. conda新环境不要安装GPU有关事项,如:conda install pytorch torchvision -c pytorch
  2. 默认换源或挂梯子
  3. 电脑默认已安装CUDA,cudnn适配pytroch的GPU形式,或直接CPU(不建议)
  4. 显存运行至少为LLM同等大小,微调为LLM1.5倍大小
  5. 配置参考(最重要的是显存大小)LLM check (rahulschand.github.io)
  6. GPU有关报错,优先pip uninstall、pip install重装,如bitsandbytes
  7. OS有关报错,优先检查路径
  8. hf高分模型参考,需要梯子:Open LLM Leaderboard - a Hugging Face Space by HuggingFaceH4
  9. 不建议国内榜单,水分较大

4.project整体结构:

- project
│  .env
│  run_startup.sh           启动web页面
└──── .condas               整体环境
└───── Langchain-Chatchat   运行所在位置,知识库
└───── model                LLM模型位置,embedding
└───── table                表格模型位置,数据库
|    └─────  table_SQL          
│        │  data_db         数据库样例(select * from A groupy by A.a limit 
│        │  web/main.py     后台表格模型运行
│        │  model           表格模型
└───── fine_tunning_lora    独立环境,模型微调

二、知识库

来源:github,gitee
Langchain-Chatchat 版本:0.2.8

1.下载基础项目与配置环境

位置:project
git clone -b v0.2.8 https://github.com/chatchat-space/Langchain-Chatchat.git
cd Langchain-Chatchat

pip install -r requirements.txt 
pip install -r requirements_api.txt
pip install -r requirements_webui.txt 
pip install jq faiss-gpu modelscope sentencepiece httpie pipenv
# 在配置完成后初始化,不然会下载hf网站模型作为默认模型

# 初始化配置文件
python copy_config_example.py
# 初始化案例知识库
python init_database.py --recreate-vs
# 启动
python startup.py -a
# 网页位置:./Langchain-Chatchat/configs/server_config.py
http://10.200.6.204:8501
http://10.200.6.204:7861

2.配置GPU等硬件参数

  • 无结构文本数据知识库向量化web等待响应时间
最开始初始化案例知识库
python project\Langchain-Chatchat\init_database.py --recreate-vs


上传文件,在web界面反馈等待(长文件加衍长时间)
\Langchain-Chatchat\configs\server_config.py
第5行
HTTPX_DEFAULT_TIMEOUT = 300.0(单位:s)
  • GPU数量设定
\Langchain-Chatchat\configs\server_config.py
第49行
            "num_gpus": 2, # 使用GPU的数量


\Langchain-Chatchat\startup.py
第173行
            args.gpus = "0,1" # GPU的编号,如果有多个GPU,可以设置为"0,1,2,3"
第175行
            args.num_gpus = 2  # model worker的切分是model并行,这里填写显卡的数量
  • 新增LLM模型:
\Langchain-Chatchat\configs\server_config.py
第35行:FSCHAT_MODEL_WORKERS = {  # 添加对应LLM
    "Llama2-Chinese-7b-Chat": {
        "device": "auto",
        "num_gpus": 2,
},


 
\Langchain-Chatchat\configs\model_config.py
第6行所有model、embedding放置路径:
MODEL_ROOT_PATH = "project/model/"
第22行:
LLM_MODELS = ["Llama2-Chinese-7b-Chat"]
# LLM_MODELS = ["Llama2-Chinese-7b-Chat", "neural-chat-7b-v3-1","juanako-7b-UNA"] 
#显存不足,谨慎添加模型,建议长期换用榜一第一个
第128行属性
MODEL_PATH = {
的第161行属性
    "llm_model": {
添加:
        "Llama2-Chinese-7b-Chat": "/project/model/Llama2-Chinese-7b-Chat",

3.以下为魔改,外挂数据库,链接表格模型

  • 在后端加载一个新选项:数据库查询table_chat(对应知识库查询knowledge_base_chat)
vim ./Langchain-Chatchat/server/api.py
第128def get_server_prompt_template(
        type: Literal["llm_chat", "knowledge_base_chat", "table_chat",
"search_engine_chat", "agent_chat"] = Body(
            "llm_chat", description="模板类型,可选值:llm_chat,knowledge_base_chat,table_chat,search_engine_chat,agent_chat"),
        name: str = Body("default", description="模板名称"),
    ) -> str:
        return get_prompt_template(type=type, name=name)
第147from server.chat.table_chat import table_chat
第160行
    app.post("/chat/table_chat",
             tags=["Chat"],
             summary="与数据库对话")(table_chat)

 
vim ./Langchain-Chatchat/server/chat/table_chat.py
加入  LLM项目配置\新增文件\langchain\最好的


vim ./Langchain-Chatchat/configs/prompt_config.py
加入 LLM项目配置\新增文件\langchain\prompt_config.py
  • 前端加载对应按钮:
  • 此处db_samples知识库,需要提前做好,将数据库样本(select * form A group by A.a limit 1)直接塞入db_samples向量知识库
  • 详细格式见下面表格模型的格式文件
vim ./Langchain-Chatchat/webui_pages/dialogue/dialogue.py
第141行
                        "数据库问答",

第206行
            "数据库问答": "table_chat",

第254行
        elif dialogue_mode == "数据库问答":
            with st.expander("数据库配置", True):
                kb_list = api.list_knowledge_bases()
                index = 0
                if "db_samples" in kb_list:
                    index = kb_list.index("db_samples")
                selected_kb = st.selectbox(
                    "请选择知识库:",
                    kb_list,
                    index=index,
                    on_change=on_kb_change,
                    key="selected_kb",
                )
                kb_top_k = st.number_input("匹配知识条数:", 1, 20, VECTOR_SEARCH_TOP_K)
                history_len = st.number_input("历史对话轮数:", 0, 20, 0)
                ## Bge 模型会超过1
                score_threshold = st.slider("知识匹配分数阈值:", 0.0, 2.0, float(SCORE_THRESHOLD), 0.01)

第413行
            elif dialogue_mode == "数据库问答":
                chat_box.ai_say([
                    f"正在查询知识库 `{selected_kb}` ...",
                    Markdown("...", in_expander=True, title="知识库匹配结果", state="complete"),
                ])
                text = ""
                for d in api.table_chat(prompt,
                                        knowledge_base_name=selected_kb,
                                        top_k=kb_top_k,
                                        score_threshold=score_threshold,
                                        history=history,
                                        model=llm_model,
                                        prompt_name=prompt_template_name,
                                        temperature=temperature):
                    if error_msg := check_error_msg(d):  # check whether error occured
                        st.error(error_msg)
                    elif chunk := d.get("answer"):
                        text += chunk
                        chat_box.update_msg(text, element_index=0)
                chat_box.update_msg(text, element_index=0, streaming=False)
                chat_box.update_msg("\n\n".join(d.get("docs", [])), element_index=1, streaming=False)
        
  • 前端与后端创建链接类:
vim ./Langchain-Chatchat/webui_pages/utils.py
第392def table_chat(
        self,
        query: str,
        knowledge_base_name: str,
        top_k: int = VECTOR_SEARCH_TOP_K,
        score_threshold: float = SCORE_THRESHOLD,
        history: List[Dict] = [],
        stream: bool = True,
        model: str = LLM_MODELS[0],
        temperature: float = TEMPERATURE,
        max_tokens: int = None,
        prompt_name: str = "default",
    ):
        '''
        对应api.py/chat/table_chat接口
        '''
        data = {
            "query": query,
            "knowledge_base_name": knowledge_base_name,
            "top_k": top_k,
            "score_threshold": score_threshold,
            "history": history,
            "stream": stream,
            "model_name": model,
            "temperature": temperature,
            "max_tokens": max_tokens,
            "prompt_name": prompt_name,
        }
        # print(f"received input message:")
        # pprint(data)
        response = self.post(
            "/chat/table_chat",
            json=data,
            stream=True,
        )
        return self._httpx_stream2generator(response, as_json=True)

4.新增与大改

新增:
project\Langchain-Chatchat\server\chat\table_chat.py
来自:LLM项目配置\新增文件\langchain
选最好即可

注:prompt传入参数如果对不上,
参数传多了会后端报错,前端无响应
参数传少了会前端显示:API通信失败

vim ./Langchain-Chatchat/configs/prompt_config.py
改写为:
LLM项目配置\新增文件\langchain\prompt_config.py

5.尚未魔改(项目不需要)

1. 向量知识库索引,关键词
最好为关键词索引,需要大量的标签文本进行训练神经网络(类似embedding操作)
数据:可能提问类型,与对应key_words标签

2. 查找方式
目前查找为L2欧氏距离查找,只找相似度最高
更有效的查找:MMR,最大边际相关性检索,参数能权衡相关与多样性

3. 美化前端、embedding_key.txt文件、依据查询结果写angent表格
数据库自动提取样例文件(select * form A group by A.a limit 1)
(后期)

三、数据库

来源:达摩院魔塔space-table
说明:可更换table\table_SQL\model下text2sql模型
处理优先级:换榜一> embedding_keys_words.txt 提词器文件编写 > 微调

1.继续配置环境:

位置:table_SQL
pip install -r requirements.txt


外挂后台表格模型位置:
./table/table_SQL/web/main.py

2.数据库说明:

数据库载入位置:
./table/table_SQL/web/main.py
61行函数:
def create_db():
写入自己的数据库

此外,
./table/table_SQL/data_db/SQL.jsonLLM模型)与table.json(表格模型)
写入提示数据库信息,尽量含有原信息,并对
可能提问的内容,进行
SELECT * FROM `A` jion `B` ON A.classid = B.id group by 可能提问 limite 1
信息格式参考:
./table/table_SQL/databasesLLM项目配置/数据/SQL数据拆解

知识二、表格三の启动与终止

1.启动

project目录下:
. ~/.profile
conda activate base
cd project(位置)
conda activate ./.condas/
. run_startup.sh

2.终止

终止(用于后端表格模型更新)
ctrl +C
pgrep -f 'main.py'
kill $(pgrep -f 'main.py')

四、LLM微调

来源:hf网 Open LLM Leaderboard 榜一
Open LLM Leaderboard - a Hugging Face Space by HuggingFaceH4
说明:更换更好模型优先级大于微调
处理优先级:换榜一> embedding_keys_words.txt 编写 > 微调

1.环境:独立 下载与配置:

所在位置:./fine_tunning_lora  (有.env)
pipenv shell
git clone https://github.com/FlagAlpha/Llama2-Chinese.git
(ai_deeplearn失效?)
git clone https://gitee.com/ai_deeplearn/Llama2-Chinese.git


pip install -r requirements.txt
pip install -upgrade peft
若GPU报错:
pip uninstall bitsandbytes  
pip install <https://github.com/jllllll/bitsandbytes-windows-webui/releases/download/wheels/bitsandbytes-0.41.0-py3-none-win_amd64.whl>
pip install torch torchvision langchain

2.微调文件修改:

所在位置:./fine_tunning_lora  (有.env)
pipenv shell
cd ./train/sft/
vim ./finetune_lora.sh

3.微调配置内容:

deepspeed   --num_gpus 2   finetune_clm_lora.py
deepspeed --include localhost:0,1  finetune_clm_lora.py

  1. 说明:两个参数矛盾

--save_steps 200
--eval_steps 200 2. 说明:这个是迭代微调的保存频率,太小会快速生成大量版本,建议调大


--save_total_limit 2000
3. 说明:这个是迭代微调的终止版本,与数据规模成正比


output_model=输出目录,建议 project/model/fintune/
4. 输出微调lora位置。注意,lora文件与原模型需一起使用,可以合并。不同lora可以同时与原模型一起联用


--train_files
--validation_files 5. 训练数据说明:

  • 必须要原始数据,可以参考测评网址数据
  • 微调最好为:缩写词专业词需求、回答语气格式需求
  • validation为测试文件,也是另一种迭代停止条件,尽可能与train独立。此外,该文件为loss标准,写入日志

finetune_clm_lora.py内容:
第445行

  • lora_config = LoraConfig( )
  1. 该finetune_clm_lora.py为lora参数配置文件。finetune_lora.sh为硬件参数配置文件

4.微调:

pipenv shell
cd ./train/sft/
. ./finetune_lora.sh > project/Log/lora版本.log


执行 Ctrl + Z
[n]+ Stopped xxxx 
执行 bg %n
挂载后台
执行 disown
解除程序与运行端口依赖关系(记得写好日志)

五、embedding配置提词器文件

表格模型,SQL对应提词器位置:
project\table\table_SQL\data_db\synonym.txt

LLM,外挂知识库,对应提词器位置:
project\Langchain-Chatchat\embeddings\embedding_keywords.txt
project\Langchain-Chatchat\configs\kb_config.py 中提到:

TEXT_SPLITTER_NAME = "ChineseRecursiveTextSplitter"
# Embedding模型定制词语的词表文件
EMBEDDING_KEYWORD_FILE = "embedding_keywords.txt"

1.提词器文件说明:

所在流域	所在湖泊|所在河流|流域
汕尾市	汕尾
河源市	河源

输入后者时,被自动转换为前者embedding的token向量
应用场景:
提问SQL时候,问题提出模糊不全,与SQL信息匹配不上