XTuner 大模型单卡低成本微调实战

news2025/4/23 10:20:19

文章目录

  • 配置环境
  • 微调
  • 部署与测试
  • 自定义微调

XTuner 大模型单卡低成本微调 原理可查看 XTuner 大模型单卡低成本微调原理

配置环境

  • 创建一个名为xtuner,python=3.10版本虚拟环境

    conda create --name xtuner0.1.9 python=3.10 -y
    
  • 创建一个xtuner019文件夹,进入文件夹,拉取0.1.9版本的xtuner源码

    mkdir xtuner019
    cd xtuner019
    git clone -b v0.1.9  https://github.com/InternLM/xtuner
    
  • 进入源码目录,从源码安装XTuner

    cd xtuner
    pip install -e '.[all]'
    
  • 创建一个微调的工作路径(准备在 oasst1 数据集上微调 internlm-7b-chat)

    mkdir ft-oasst1
    cd ft-oasst1
    

微调

  • 准备配置文件

    • XTuner 提供多个开箱即用的配置文件,用户可以通过下列命令查看:

      xtuner list-cfg
      

      请添加图片描述
      baichuan2:表示模型
      13b:表示模型大小
      base:表示基座模型
      qlora:表示微调的算法
      alpaca:表示在alpaca数据集上微调
      e3:表示训练迭代3次

    • 拷贝一个配置文件到当前目录

      cd ft-oasst1
      xtuner copy-cfg internlm_chat_7b_qlora_oasst1_e3 .
      
  • 模型下载

    • 直接拷贝
      InternStudio平台的 share 目录下已经为我们准备了全系列的 InternLM 模型,所以我们可以直接复制即可。使用如下命令复制:

      cp -r /root/share/temp/model_repos/internlm-chat-7b /root/ft-oasst1/
      
    • 网络下载

      • 也可以使用 modelscope 中的 snapshot_download 函数下载模型,第一个参数为模型名称,参数 cache_dir 为模型的下载路径。
      • 在ft-oasst1文件夹下新建 download.py 文件并在其中输入以下内容,粘贴代码后记得保存文件,如下图所示。并运行 python /root/ft-oasst1/download.py 执行下载,模型大小为 14 GB,下载模型大概需要 10~20 分钟
      import torch
      from modelscope import snapshot_download, AutoModel, AutoTokenizer
      import os
      model_dir = snapshot_download('Shanghai_AI_Laboratory/internlm-chat-7b', cache_dir='/root/ft-oasst1', revision='v1.0.3')
      
  • 数据集下载
    下载地址:https://huggingface.co/datasets/timdettmers/openassistant-guanaco/tree/main
    由于 huggingface 网络问题,咱们已经给大家提前下载好了,复制到正确位置即可:

    cd ft-oasst1
    cp -r /root/share/temp/datasets/openassistant-guanaco .
    

    当前路径的文件:
    在这里插入图片描述

  • 修改配置文件
    修改模型路径和数据集路径
    在这里插入图片描述
    常用超参

    参数名解释
    data_path数据路径或 HuggingFace 仓库名
    max_length单条数据最大 Token 数,超过则截断
    pack_to_max_length是否将多条短数据拼接到 max_length,提高 GPU 利用率
    accumulative_counts梯度累积,每多少次 backward 更新一次参数
    evaluation_inputs训练过程中,会根据给定的问题进行推理,便于观测训练状态
    evaluation_freqEvaluation 的评测间隔 iter 数

    如果想把显卡的现存吃满,充分利用显卡资源,可以将 max_length 和 batch_size 这两个参数调大。

  • 开始微调训练
    在终端输入以下命令开启训练:

    xtuner train ./internlm_chat_7b_qlora_oasst1_e3_copy.py
    

    在这里插入图片描述
    开启 deepspeed 加速,增加 --deepspeed deepspeed_zero2 即可

    xtuner train ./internlm_chat_7b_qlora_oasst1_e3_copy.py --deepspeed deepspeed_zero2
    

    在这里插入图片描述

  • pht 模型转换为 HuggingFace 模型,即:生成 Adapter 文件夹

    cd ft-oasst1
    mkdir hf
    export MKL_SERVICE_FORCE_INTEL=1
    
    xtuner convert pth_to_hf ./internlm_chat_7b_qlora_oasst1_e3_copy.py ./work_dirs/internlm_chat_7b_qlora_oasst1_e3_copy/epoch_1.pth ./hf
    

    此时转换完后的文件:
    在这里插入图片描述
    此时,hf 文件夹即为我们平时所理解的所谓 “LoRA 模型文件”,可以简单理解:LoRA 模型文件 = Adapter

部署与测试

  • 将 HuggingFace adapter 合并到大语言模型

    xtuner convert merge ./internlm-chat-7b ./hf ./merged --max-shard-size 2GB
    # xtuner convert merge \
    #     ${NAME_OR_PATH_TO_LLM} \
    #     ${NAME_OR_PATH_TO_ADAPTER} \
    #     ${SAVE_PATH} \
    #     --max-shard-size 2GB
    

    运行完成后会在ft-oasst1文件下生成一个merged文件,就是合并后的大模型

  • 与合并后的模型对话

    # 加载 Adapter 模型对话(Float 16)
    xtuner chat ./merged --prompt-template internlm_chat
    
    # 4 bit 量化加载
    # xtuner chat ./merged --bits 4 --prompt-template internlm_chat
    

    测试对话如图
    在这里插入图片描述

自定义微调

  • 基于 InternLM-chat-7B 模型,用 MedQA 数据集进行微调,将其往医学问答领域对齐

  • 数据预览

    问题答案
    What are ketorolac eye drops?(什么是酮咯酸滴眼液?)Ophthalmic ketorolac is used to treat itchy eyes caused by allergies. It also is used to treat swelling and redness (inflammation) that can occur after cataract surgery. Ketorolac is in a class of medications called nonsteroidal anti-inflammatory drugs (NSAIDs). It works by stopping the release of substances that cause allergy symptoms and inflammation.
    What medicines raise blood sugar? (什么药物会升高血糖?)Some medicines for conditions other than diabetes can raise your blood sugar level. This is a concern when you have diabetes. Make sure every doctor you see knows about all of the medicines, vitamins, or herbal supplements you take. This means anything you take with or without a prescription. Examples include: Barbiturates. Thiazide diuretics. Corticosteroids. Birth control pills (oral contraceptives) and progesterone. Catecholamines. Decongestants that contain beta-adrenergic agents, such as pseudoephedrine. The B vitamin niacin. The risk of high blood sugar from niacin lowers after you have taken it for a few months. The antipsychotic medicine olanzapine (Zyprexa).
  • 数据准备

    • 以 Medication QA 数据集为例,原格式为(.xlsx)

    • 将数据转为 XTuner 的数据格式,执行 python 脚本,获得格式化后的数据集

      import openpyxl
      import json
      
      def process_excel_to_json(input_file, output_file):
          # Load the workbook
          wb = openpyxl.load_workbook(input_file)
      
          # Select the "DrugQA" sheet
          sheet = wb["DrugQA"]
      
          # Initialize the output data structure
          output_data = []
      
          # Iterate through each row in column A and D
          for row in sheet.iter_rows(min_row=2, max_col=4, values_only=True):
              system_value = "You are a professional, highly experienced doctor professor. You always provide accurate, comprehensive, and detailed answers based on the patients' questions."
      
              # Create the conversation dictionary
              conversation = {
                  "system": system_value,
                  "input": row[0],
                  "output": row[3]
              }
      
              # Append the conversation to the output data
              output_data.append({"conversation": [conversation]})
      
          # Write the output data to a JSON file
          with open(output_file, 'w', encoding='utf-8') as json_file:
              json.dump(output_data, json_file, indent=4)
      
          print(f"Conversion complete. Output written to {output_file}")
      
      # Replace 'MedQA2019.xlsx' and 'output.jsonl' with your actual input and output file names
      process_excel_to_json('MedQA2019.xlsx', 'output.jsonl')
      
    • 划分训练集和测试集,python脚本入下:

      import json
      import random
      
      def split_conversations(input_file, train_output_file, test_output_file):
          # Read the input JSONL file
          with open(input_file, 'r', encoding='utf-8') as jsonl_file:
              data = json.load(jsonl_file)
      
          # Count the number of conversation elements
          num_conversations = len(data)
          
          # Shuffle the data randomly
          random.shuffle(data)
          random.shuffle(data)
          random.shuffle(data)
      
          # Calculate the split points for train and test
          split_point = int(num_conversations * 0.7)
      
          # Split the data into train and test
          train_data = data[:split_point]
          test_data = data[split_point:]
      
          # Write the train data to a new JSONL file
          with open(train_output_file, 'w', encoding='utf-8') as train_jsonl_file:
              json.dump(train_data, train_jsonl_file, indent=4)
      
          # Write the test data to a new JSONL file
          with open(test_output_file, 'w', encoding='utf-8') as test_jsonl_file:
              json.dump(test_data, test_jsonl_file, indent=4)
      
          print(f"Split complete. Train data written to {train_output_file}, Test data written to {test_output_file}")
      
      # Replace 'input.jsonl', 'train.jsonl', and 'test.jsonl' with your actual file names
      split_conversations('MedQA2019-structured.jsonl', 'MedQA2019-structured-train.jsonl', 'MedQA2019-structured-test.jsonl')
      
  • 开始微调训练

    • 创建一个ft-medqa文件夹,从ft-oasst1拷贝internlm-chat-7b模型,从tutorial/xtuner拷贝训练数据集

      mkdir ~/ft-medqa
      cd ~/ft-medqa
      cp -r ~/ft-oasst1/internlm-chat-7b .
      cp ~/tutorial/xtuner/MedQA2019-structured-train.jsonl .
      
    • 准备配置文件

      • 复制配置文件到当前目录

        xtuner copy-cfg internlm_chat_7b_qlora_oasst1_e3 .
        
      • 改文件名

        mv internlm_chat_7b_qlora_oasst1_e3_copy.py internlm_chat_7b_qlora_medqa2019_e3.py
        
      • 修改配置文件内容
        减号代表要删除的行,加号代表要增加的行。

        # 修改import部分
        - from xtuner.dataset.map_fns import oasst1_map_fn, template_map_fn_factory
        + from xtuner.dataset.map_fns import template_map_fn_factory
        
        # 修改模型为本地路径
        - pretrained_model_name_or_path = 'internlm/internlm-chat-7b'
        + pretrained_model_name_or_path = './internlm-chat-7b'
        
        # 修改训练数据为 MedQA2019-structured-train.jsonl 路径
        - data_path = 'timdettmers/openassistant-guanaco'
        + data_path = 'MedQA2019-structured-train.jsonl'
        
        # 修改 train_dataset 对象
        train_dataset = dict(
            type=process_hf_dataset,
        -   dataset=dict(type=load_dataset, path=data_path),
        +   dataset=dict(type=load_dataset, path='json', data_files=dict(train=data_path)),
            tokenizer=tokenizer,
            max_length=max_length,
        -   dataset_map_fn=alpaca_map_fn,
        +   dataset_map_fn=None,
            template_map_fn=dict(
                type=template_map_fn_factory, template=prompt_template),
            remove_unused_columns=True,
            shuffle_before_pack=True,
            pack_to_max_length=pack_to_max_length)
        
    • 启动训练

      xtuner train internlm_chat_7b_qlora_medqa2019_e3.py --deepspeed deepspeed_zero2
      
    • pth 转 huggingface
      与前面转的方法相同

    • 部署与测试
      与前面部署与测试的方法相同

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1382569.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

WebGL在虚拟现实(VR)的应用

WebGL在虚拟现实(VR)领域的应用日益增多,它为在Web浏览器中创建交互式的虚拟现实体验提供了强大的支持。以下是一些WebGL在VR领域的应用示例,希望对大家有所帮助。北京木奇移动技术有限公司,专业的软件外包开发公司&am…

Word插件-大珩助手-手写电子签名

手写签名 支持鼠标写,支持触摸屏写,点击画笔按钮切换橡皮擦,支持清空画板重写,点击在word中插入签名,可插入背景透明的签字图 素材库-保存签名 将写好的签字图复制粘贴到素材库中,以便永久使用&#xff…

Visual Studio Code1.67版本已正式发布,新增Rust指南

Visual Studio Code1.67版本已正式发布,该版本包含大量增强生产力的更新项: 资源管理器文件嵌套 通过这次更新,用于浏览和管理文件和文件夹的Visual Studio Code的资源管理器工具现在支持基于名称嵌套相关文件。 资源管理器现在支持根据文…

【Linux操作】国产Linux服务管理操作

【Linux操作】国产Linux服务管理操作 前言SAMBA配置服务器端1. 安装相关包2. 配置/etc/samba/smb.conf,在此文件末尾添加如下内容,并保存退出。3. 创建/home/share并更改权限4. 启动samba服务 客户端• Windows客户端• 麒麟客户端 Telnet1、telnet语法2…

机器学习中的线性回归

线性回归 概念 利用 回归方程(函数) 对 一个或多个自变量(特征值)和因变量(目标值)之间 关系进行建模的一种分析方式。 分类 一元线性回归:y wx b 目标值只与一个因变量有关系 多元线性回归: y w_1x_1 w_2x_2 w_3x_3 … b 目标值只与多个…

Linux Ubuntu搭建我的世界Minecraft服务器实现好友远程联机MC游戏

文章目录 前言1. 安装JAVA2. MCSManager安装3.局域网访问MCSM4.创建我的世界服务器5.局域网联机测试6.安装cpolar内网穿透7. 配置公网访问地址8.远程联机测试9. 配置固定远程联机端口地址9.1 保留一个固定tcp地址9.2 配置固定公网TCP地址9.3 使用固定公网地址远程联机 前言 Li…

SpringSecurity6 | 登录失败后的跳转

✅作者简介:大家好,我是Leo,热爱Java后端开发者,一个想要与大家共同进步的男人😉😉 🍎个人主页:Leo的博客 💞当前专栏: 循序渐进学SpringSecurity6 ✨特色专栏: MySQL学习 🥭本文内容: SpringSecurity6 | 失败后的跳转 📚个人知识库: Leo知识库,欢迎大家…

Qt/QML编程学习之心得:使用camera摄像头(35)

汽车应用中,camera起到了越来越多的作用,数字化的作用,这点无可争议,而作为GUI设计工具,如何让Camera类的应用能更好的发挥作用呢? You can use Camera to capture images and movies from a camera, and manipulate the capture and processing settings that get appl…

C#MQTT编程03--连接报文

1、报文回顾 MQTT协议中一共有14个报文,如下图 从上图看,我们要特别要注意以下3个点: (1)值,14个报文的排列,不是随意的,每个报文都有自己的值,而值在报文中是要用到的。后面例子会介绍到。 …

【含完整代码】Java定时任务之xxl-job[超详细]

前言 个人博客:www.wdcdbd.com 在Java中使用定时任务是一件很常见的事情,比如使用定时任务在什么时间,什么时候,去发布一些信息,或者去查询一些日志等相关的代码。这时,我们就要开发定时任务这中功能来实现…

理解TCP/IP协议

一、协议 在计算机网络与信息通讯领域里,人们经常提及 “协议” 一词。互联网中常用的协议有HTTP、TCP、IP等。 协议的必要性 简单来说,协议就是计算机与计算机之间通过网络通信时,事先达成的一种 “约定”。这种“约定”使不同厂商的设备…

精通业务:资深程序员的核心优势

在IT行业,我们常常听到关于技术实力、项目经验、团队协作等方面的讨论,但有一个重要因素常常被忽视,那就是对业务的了解。 对于资深程序员来说,懂业务和不懂业务之间的区别,犹如一道深邃的鸿沟,决定着他们…

【MySQL】:探秘主流关系型数据库管理系统及SQL语言

🎥 屿小夏 : 个人主页 🔥个人专栏 : MySQL从入门到进阶 🌄 莫道桑榆晚,为霞尚满天! 文章目录 📑前言一. MySQL概述1.1 数据库相关概念1.2 主流数据库1.3 数据模型1.3.1 关系型数据库…

QT DAY5作业

1.QT基于TCP服务器端 头文件 #ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QTcpServer> //服务器类 #include <QMessageBox> //消息对话框类 #include <QTcpSocket> //客户端类 #include <QList> //链表容器类namespace …

unity C#什么时候用“可空类型”

文章目录 例子1. **声明一个可空类型变量&#xff1a;**2. **给可空类型变量赋值&#xff1a;**3. **检查可空类型变量是否有值&#xff1a;**4. **转换与比较&#xff1a;**5. **使用null合并运算符&#xff1a;** 可空类型的重要意义1. **表示缺失或未知的值&#xff1a;**2.…

基于51单片机的智能热水器设计

需要全部文件请私信关注我&#xff01;&#xff01;&#xff01; 基于51单片机的智能热水器设计 摘要一、绪论1.1 选题背景及意义1.2 完成目标与功能设计 二、硬件系统设计2.1 硬件完成要求2.2 方案选择2.3 电源电路设计2.4 键盘电路2.5 蜂鸣器报警电路2.6 温度检测电路2.7 红…

LeetCode刷题--- 删除并获得点数

个人主页&#xff1a;元清加油_【C】,【C语言】,【数据结构与算法】-CSDN博客 个人专栏 力扣递归算法题 http://t.csdnimg.cn/yUl2I 【C】 ​​​​​​http://t.csdnimg.cn/6AbpV 数据结构与算法 ​​​http://t.csdnimg.cn/hKh2l 前言&#xff1a;这个专栏主要讲述动…

AAAI 2024|ETH轻量化Transformer最新研究,浅层MLP完全替换注意力模块提升性能

论文题目&#xff1a; Rethinking Attention: Exploring Shallow Feed-Forward Neural Networks as an Alternative to Attention Layers in Transformers 论文链接&#xff1a; https://arxiv.org/abs/2311.10642 代码仓库&#xff1a; GitHub - vulus98/Rethinking-attention…

【Redis】非关系型数据库之Redis的增删改查

目录 一、Redis的数据类型分类 二、Redis的字符串类型string 三、Redis的列表list 四、Redis的哈希hash 五、Redis的无序集合set 六、Redis的有序集合zset 七、Redis的通用命令 一、Redis的数据类型分类 通常Redis的数据类型有五大基础类型 String&#xff08;字符串&am…

解决Unexpected record signature 0X9maven 资源过滤

解决Unexpected record signature: 0X9|maven 资源过滤 记录问题&#xff1a;我们有个需求是根据excel模版导出一个excel表。我们的项目是SpringBoot&#xff0c;所以理所当然的把这个模版文件放到了&#xff0c;resources文件夹中。但是在导出文件的时候却遇到了invalid code …