论文分类打榜赛Baseline:ms-swift微调InternLM实践

article/2025/6/7 22:58:33

本文来自社区投稿,作者尖米、张富才。

书生大模型实战营第5期已正式启动,本期实战营新增「论文分类打榜赛」,以帮助学员更好地掌握大模型技能。

本文将手把手带领大家如何用 ms-swiftt 微调 InternLM 模型,轻松上手论文自动分类任务。从环境配置、数据准备,到 LoRA 微调和推理部署,完整教程不藏私。即使你是模型微调新手,也能快速参与打榜实践!

InternLM开源链接:

https://github.com/InternLM/InternLM

在线体验链接:

https://chat.intern-ai.org.cn/\

1.环境配置

登录 InternStudio 平台,创建开发机(https://studio.intern-ai.org.cn/console/instance)。

  • 镜像选择: Cuda12.2-conda
  • GPU 资源选择:50% A100

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

conda 管理环境安装:

#安装 ms-swift
conda create -n ms-swift python=3.10 -y
conda activate ms-swift
pip install ms-swift -U

注意:后续所有的操作都需要再 ms-swift 的虚拟环境中执行,在进入新终端时需要先执行 conda activate ms-swift

创建目录 paper 文件,组织形式如下图:

在这里插入图片描述

2.准备训练数据

这里已经为大家准备了处理好的 arxiv 数据集和采集得到的数据。

下载链接:https://www.modelscope.cn/datasets/JimmyMa99/smartflow-arxiv-dataset/files

conda activate ms-swift
pip install modelscope
modelscope download --dataset JimmyMa99/smartflow-arxiv-dataset --local_dir ./datasets/train

3.模型训练

LoRA 预训练

预训练目的是让模型先学点论文元数据,类比基础知识。好比我们学习数学,刚开始学点加减乘除,而不是一上来就学习多元函数变微分求导

代码

#!/bin/bash# 创建日志目录
LOG_DIR="logs"
mkdir -p $LOG_DIR  # 确保日志目录存在,如果不存在则创建# 获取当前时间戳,用于生成唯一的日志文件名
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
LOG_FILE="$LOG_DIR/internlm3-8b_lora_sft_${TIMESTAMP}.log"  # 设置日志文件路径# 设置CUDA环境变量
export NPROC_PER_NODE=1  # 设置每个节点使用的进程数为1
export OMP_NUM_THREADS=1  # 限制OpenMP线程数为1,避免过多线程竞争
export CUDA_VISIBLE_DEVICES=0  # 指定使用的GPU编号为0# 使用nohup命令在后台运行训练任务,即使终端关闭也能继续运行
nohup swift sft \--model /root/share/new_models/internlm3/internlm3-8b-instruct \  # 指定基础模型路径--train_type lora \  # 使用LoRA训练方法--dataset '/root/paper/data/swift_formatted_pretrain_data.jsonl' \  # 指定训练数据集--torch_dtype bfloat16 \  # 使用bfloat16精度以节省显存--num_train_epochs 1 \  # 设置训练轮数为2--per_device_train_batch_size 2 \  # 每个设备的训练批次大小为4--learning_rate 5e-5 \  # 学习率设置为5e-5--warmup_ratio 0.1 \  # 预热阶段占总训练步数的10%--split_dataset_ratio 0 \  # 不拆分数据集--report_to wandb \  # 将训练日志报告到Weights & Biases平台--lora_rank 8 \  # LoRA的秩设置为8--lora_alpha 32 \  # LoRA的alpha参数设置为32--use_chat_template false \  # 不使用聊天模板--target_modules all-linear \  # 对所有线性层应用LoRA--gradient_accumulation_steps 2 \  # 梯度累积步数为2,用于增大有效批次大小--save_steps 2000 \  # 每2000步保存一次模型--save_total_limit 5 \  # 最多保存5个检查点--gradient_checkpointing_kwargs '{"use_reentrant": false}' \  # 梯度检查点设置,禁用重入--logging_steps 5 \  # 每5步记录一次日志--max_length 2048 \  # 最大序列长度设为2048--output_dir ./swift_output/InternLM3-8B-Lora \  # 输出目录--dataloader_num_workers 256 \  # 数据加载器使用256个工作线程--model_author JimmyMa99 \  # 模型作者信息--model_name InternLM3-8B-Lora \  # 模型名称> "$LOG_FILE" 2>&1 &  # 将标准输出和错误输出重定向到日志文件,并在后台运行# 打印进程ID和日志文件位置,便于用户跟踪
echo "Training started with PID $!"  # 显示后台进程的PID
echo "Log file: $LOG_FILE"  # 显示日志文件位置# 提示用户如何实时查看日志
echo "To view logs in real-time, use:"
echo "tail -f $LOG_FILE"

启动

bash internlm3-8b-lora.sh

合并权重

LoRA 训练方法是只训练了一部分权重,那么接下来就需要将原模型剩下的权重合并在一起,成一个新的模型。

swift export --adapters /root/paper/config/swift_output/InternLM3-8B-Lora/v1-20250510-224052/checkpoint-144 --merge_lora true

Lora 监督微调

代码

#!/bin/bash# 创建日志目录
LOG_DIR="logs"
mkdir -p $LOG_DIR# 获取当前时间戳
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
LOG_FILE="$LOG_DIR/internlm3-8b_lora_sft_${TIMESTAMP}.log"# 设置CUDA设备
export NPROC_PER_NODE=1
export OMP_NUM_THREADS=1
export CUDA_VISIBLE_DEVICES=0nohup swift sft \--model /root/paper/config/swift_output/InternLM3-8B-Lora/v1-20250510-224052/checkpoint-144-merged \--train_type lora \--dataset '/root/paper/data/swift_formatted_sft_train_data.jsonl' \--torch_dtype bfloat16 \--num_train_epochs 3 \--per_device_train_batch_size 8 \--learning_rate 5e-5 \--warmup_ratio 0.1 \--split_dataset_ratio 0 \--lora_rank 16 \--lora_alpha 64 \--lora_dropout 0.1 \--weight_decay 0.01 \--target_modules all-linear \--gradient_accumulation_steps 4 \--save_steps 1000 \--save_total_limit 5 \--gradient_checkpointing_kwargs '{"use_reentrant": false}' \--logging_steps 5 \--max_length 4096 \--output_dir ./swift_output/InternLM3-8B-Lora-SFT \--dataloader_num_workers 256 \--model_author zhangfucai \--model_name InternLM3-8B-Lora-SFT \> "$LOG_FILE" 2>&1 &# 打印进程ID和日志文件位置
echo "Training started with PID $!"
echo "Log file: $LOG_FILE"# 显示查看日志的命令
echo "To view logs in real-time, use:"
echo "tail -f $LOG_FILE"

启动

bash internlm3-8b-sft-lora.sh

合并权重

同理,需要合并权重。

swift export --adapters /root/paper/config/swift_output/InternLM3-8B-Lora-SFT/v3-20250510-231854/checkpoint-21 --merge_lora true

4.模型推理

代码

from transformers import AutoModelForCausalLM, AutoTokenizer
import time# 加载模型和分词器
# model_path = "/root/share/new_models/internlm3/internlm3-8b-instruct"
model_path = "/root/paper/config/swift_output/InternLM3-8B-Lora/v1-20250510-224052/checkpoint-144-merged"
# model_path = "/root/paper/config/swift_output/InternLM3-8B-Lora-SFT/v3-20250510-231854/checkpoint-21-merged"
print(f"加载模型:{model_path}")start_time = time.time()tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True, torch_dtype="auto", device_map="auto"
)def classify_paper(title, authors, abstract, additional_info=""):# 构建输入,包含多选选项prompt = f"Based on the title '{title}', authors '{authors}', and abstract '{abstract}', please determine the scientific category of this paper. {additional_info}\n\nA. astro-ph\nB. cond-mat.mes-hall\nC. cond-mat.mtrl-sci\nD. cs.CL\nE. cs.CV\nF. cs.LG\nG. gr-qc\nH. hep-ph\nI. hep-th\nJ. quant-ph"# 设置系统信息messages = [{"role": "system", "content": "你是个优秀的论文分类师"},{"role": "user", "content": prompt},]# 应用聊天模板input_text = tokenizer.apply_chat_template(messages, tokenize=False)# 生成回答inputs = tokenizer(input_text, return_tensors="pt").to(model.device)outputs = model.generate(**inputs,max_new_tokens=10,  # 减少生成长度,只需要简短答案temperature=0.1,  # 降低温度提高确定性top_p=0.95,repetition_penalty=1.0,)# 解码输出response = tokenizer.decode(outputs[0][inputs.input_ids.shape[1] :], skip_special_tokens=True).strip()# 如果回答中包含选项标识符,只返回该标识符for option in ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]:if option in response:return option# 如果回答不包含选项,返回完整回答return response# 示例使用
if __name__ == "__main__":title = "Outilex, plate-forme logicielle de traitement de textes 'ecrits"authors = "Olivier Blanc (IGM-LabInfo), Matthieu Constant (IGM-LabInfo), Eric Laporte (IGM-LabInfo)"abstract = "The Outilex software platform, which will be made available to research, development and industry, comprises software components implementing all the fundamental operations of written text processing: processing without lexicons, exploitation of lexicons and grammars, language resource management. All data are structured in XML formats, and also in more compact formats, either readable or binary, whenever necessary; the required format converters are included in the platform; the grammar formats allow for combining statistical approaches with resource-based approaches. Manually constructed lexicons for French and English, originating from the LADL, and of substantial coverage, will be distributed with the platform under LGPL-LR license."result = classify_paper(title, authors, abstract)print(result)# 计算并打印总耗时end_time = time.time()total_time = end_time - start_timeprint(f"程序总耗时:{total_time:.2f}秒")

微调前后推理对比

观察下图,发现监督微调后的模型符合预期。

在这里插入图片描述

在这里插入图片描述

5.模型评测(可选)

在提交模型后,后台会自动评测,所以这部分是可选的。但不放心的小伙伴,可以先自己评测一下看看效果,自己评测的结果和最终结果差距不会很大。下面展示如何使用 OpenCompass 进行测评。

环境配置

git clone https://github.moeyy.xyz/https://github.com/open-compass/opencompass opencompass
cd opencompass
conda create -n opencompass python=3.10 -y
conda activate opencompass 
pip install -e .pip install sentencepiece

代码

评测代码(数据/root/datasets/train/newformat_sft_test_data.csv是 A 榜测试数据)

 # To run this example, you need to do the following steps:
# 1. Install latest opencompass
# 2. Start a local server with Qwen2.5-72B-Instruct as LLMJudge server (i.e. using vLLM or LMDeploy)
# 3. Change the judge_cfg openai_api_base to your corresponindg local server address
# 4. Start this evaluation by running 'opencompass eval_internlm3_math500_thinking.py' 
# from opencompass.models import VLLMwithChatTemplate, OpenAISDK
from mmengine.config import read_base
from opencompass.models import HuggingFaceCausalLMmodels = [dict(type=HuggingFaceCausalLM,path='/root/paper/config/swift_output/InternLM3-8B-Lora-SFT/v3-20250510-231854/checkpoint-21-merged',tokenizer_path='/root/paper/config/swift_output/InternLM3-8B-Lora-SFT/v3-20250510-231854/checkpoint-21-merged',tokenizer_kwargs=dict(padding_side='left', truncation_side='left'),model_kwargs=dict(device_map='auto'),max_seq_len=32768,max_out_len=16384,batch_size=4,run_cfg=dict(num_gpus=1),)
]datasets = [{"path": "/root/datasets/train/newformat_sft_test_data.csv", "data_type": "mcq", "infer_method": "gen"},
]

运行

#在opencompass目录下
python run.py internlm3-oc_eval.py --debug

结果

在这里插入图片描述

6.提交模型

前置条件

在魔搭平台创建模型仓库,并获取 hub_model_id,如下图:

在这里插入图片描述

在【账号设置】里获取hub_token,如下图:

在这里插入图片描述

下载 git

apt-get install git-lfs
git lfs install

提交模型至魔搭平台

swift export \--model /root/paper/config/swift_output/InternLM3-8B-Lora-SFT/v3-20250510-231854/checkpoint-21-merged\--push_to_hub true \--hub_model_id 'zhangfc12345678/zfc-camp5' #替换成自己的 \--hub_token '03fb4fxx' \ #替换成自己的--use_hf false

将上传至魔搭的模型提交至比赛评测平台

填写下方表单即可完成提交

https://aicarrier.feishu.cn/share/base/form/shrcn0JkjbZKMeMPw04uHCWc5Pg

将上传至魔搭的模型提交至比赛评测平台

填写下方表单即可完成提交

https://aicarrier.feishu.cn/share/base/form/shrcn0JkjbZKMeMPw04uHCWc5Pg

7.参赛奖励

在以下时间点,排行榜位列前 10 的选手将获得相应奖励:

  • 6 月 3 日 20:00,前 10 名获得 InternStudio 平台 2000 算力点
  • 6 月 10 日 20:00,前 10 名获得 InternStudio 平台 1688 算力点
  • 6 月 17 日 20:00,前 10 名获得 InternStudio 平台 999 算力点
  • 6 月 24 日 20:00,前 10 名获得 InternStudio 平台 666 算力点
  • 6 月 30 日 20:00,前 10 名额外获得 官方证书
    注:算力有效期仅第五期实战营内有效

5 月 29 日榜单部分截图
在这里插入图片描述

访问下方链接可查看全部榜单内容
https://aicarrier.feishu.cn/share/base/dashboard/shrcnqpXY6Uy9FodNF3It75GSNe

本文主要介绍了如何使用 ms-swift 对 InternLM 进行微调,并应用于论文分类任务,涵盖了从环境配置、数据准备到模型训练、推理与评测的完整流程,希望对大家参加赛事有所帮助。


http://www.hkcw.cn/article/xQgfAKayod.shtml

相关文章

v4l2常见操作-查看当前摄像头信息,帧率,控制参数,分辨率,支持格式,抓图实践等

一:查看当前有哪些摄像头 grep /sys/class/video4linux/video*/name 例如以下为USB插入式camera 二:查看当前摄像头支持的分辨率 v4l2-ctl -d /dev/video14 --get-fmt-video 例如以下摄像头支持的video捕获分辨率为3840*2160 三:查看当前…

MaxCompute开发UDF和UDTF案例

文章目录 一、Java开发UDF1、创建Maven项目2、创建UDF类3、打包上传资源4、创建函数MyUDF5、SQL验证 二、Java开发UDTF1、创建Maven项目2、创建UDTF类3、打包上传更新资源4、创建函数MyUDTF5、SQL验证 三、常见问题1、发布函数报错 一、Java开发UDF 1、创建Maven项目 创建Mav…

ROS2学习(17)------ROS 2 Gazebo 三维物理仿真平台简介及举例使用

操作系统:ubuntu22.04 IDE:Visual Studio Code 编程语言:C11 ROS版本:2 ROS 2 Gazebo 三维物理仿真平台简介 Gazebo 是一个强大的三维机器人仿真环境,它能够模拟复杂的机器人系统和环境。结合 ROS 2,你可以使用 Gaze…

定时通知群内值班人功能

from app.external.zhiban import default_zhiban_api_client import requests import json from datetime import datetimedef send_daily_reminder():# app_map [# {"name": "平台-存储云平台服务号", "type": "app"},# {&…

现代密码学 | 椭圆曲线密码学—附py代码

Elliptic Curve Cryptography 椭圆曲线密码学(ECC)是一种基于有限域上椭圆曲线数学特性的公钥加密技术。其核心原理涉及椭圆曲线的代数性质、离散对数问题以及有限域上的运算。 椭圆曲线密码学是多种数字签名算法的基础,例如椭圆曲线数字签…

04 APP 自动化- Appium toast 元素定位列表滑动

文章目录 一、toast 元素的定位二、滑屏操作 一、toast 元素的定位 toast 元素就是简易的消息提示框,toast 显示窗口显示的时间有限,一般3秒左右 # -*- codingutf-8 -*- from time import sleep from appium import webdriver from appium.options.an…

C++ -- 继承

继承 1. 继承的概念及定义1.1 概念1.2 继承定义 1.2.1 格式1.2.2 继承基类成员访问方式的变化2. 基类和派生类对象赋值转换3. 继承中的作用域4. 派生类的默认成员函数5. 继承与友元6. 继承与静态成员7. 菱形继承7.1 单继承7.2 多继承7.3 菱形继承7.4 虚拟继承virtual 1. 继承的…

K8S上使用helm部署 Prometheus + Grafana

一、使用 Helm 安装 Prometheus 1. 配置源 地址:prometheus 27.19.0 prometheus/prometheus-community # 添加repo $ helm repo add prometheus-community https://prometheus-community.github.io/helm-charts "prometheus-community" has been added…

湖北理元理律师事务所:系统性债务化解中的法律技术革新

一、打破债务困局的核心:精准责任切割 传统债务处理常陷入"全额偿还"或"逃废债"的二元对立。法律视角下的解决方案在于: 通过法定程序分离三类债务: 无效债务:年利率超LPR四倍部分(《民法典》第…

Android Studio 向模拟器手机添加照片、视频、音乐

Android Studio 向模拟器手机添加照片、视频、音乐(其实都是一样的,只是添加到不同的文件夹),例如我们在很多程序中功能例如:选择头像,跳转到手机相册选择头像,此时相册为空,即模拟器没有图片资…

vscode使用“EIDE”和“Cortex-Debug”插件利用st-link插件实现程序烧写以及调试工作

第一步:安装vscode插件“EIDE”EIDE和“Cortex-Debug”。 第二步:配置EIDE 2.1安装“实用工具”: 2.2 EIDE插件配置:根据安装的keil C51 keil MDK IAR的相关路径设置 第三步:配置Cortex-Debug插件 点击settings.jso…

详解开漏输出和推挽输出

开漏输出和推挽输出 以上是 GPIO 配置为输出时的内部示意图,我们要关注的其实就是这两个 MOS 管的开关状态,可以组合出四种状态: 两个 MOS 管都关闭时,输出处于一个浮空状态,此时他对其他点的电阻是无穷大的&#xff…

问界M9五座零重力座椅版实车亮相 智慧出行新体验

5月31日,2025粤港澳大湾区国际汽车博览会正式开幕,问界携全系车型亮相,并举办了“问界M9大五座零重力座椅版交付仪式暨品牌挚友发布会”。赛力斯汽车总裁何利扬向五位车主交付了问界M9 2025款大五座零重力座椅版的钥匙,并宣布演员白敬亭成为问界品牌挚友及问界M8车主。何利…

【Linux】线程互斥

📝前言: 这篇文章我们来讲讲Linux——线程互斥 🎬个人简介:努力学习ing 📋个人专栏:Linux 🎀CSDN主页 愚润求学 🌄其他专栏:C学习笔记,C语言入门基础&#xf…

「OC」初识runloop

「OC」初识runloop 简介 iOS中的RunLoop(运行循环)是事件处理的核心机制,负责管理线程的生命周期、事件调度及资源优化。其核心作用是通过循环处理输入事件、定时器任务和观察者回调,保持线程活跃且高效运行。 runloop的作用 R…

python学习打卡day43

DAY 43 复习日 作业: kaggle找到一个图像数据集,用cnn网络进行训练并且用grad-cam做可视化 浙大疏锦行 数据集使用猫狗数据集,训练集中包含猫图像4000张、狗图像4005张。测试集包含猫图像1012张,狗图像1013张。以下是数据集的下…

【AI学习从零至壹】基于深度学习的⽂本分类任务

基于深度学习的⽂本分类任务 文本分类任务的实现思路⽂本预处理文本分词Jieba分词文本分词器SentencePiece训练步骤⽂本结构化转换 语料转换为训练样本 文本分类任务的实现思路 ⽂本分类就是⼀个将⽂本分配到预定义类别的⼀个过程 整体流程包括: ⽂本语料的获取和…

sourcetree中的mercurial有什么用

1、安装SourceTree的过程中,有一个选项就是mercurial,,一直没搞明白他是干什么用的,直到今天 2、ai登场 3、总结 此软件无用,不需要安装

【Linux】linux基础指令

目录 管理用户相关useraddpaaswduserdelLinux中的用户文件结构 ls-aLinux目录中的.和..是什么? -l-d-FLinux指令使用多个选项 pwdcd绝对路径与相对路径 touchmkdir-p rmdir-p rm-r-i-f mancpmvecho输出重定向和追加重定向 cat-b-n-s moreless-N-i headtail管道文件搭…

Linux中shell介绍

一、脚本实践 脚本示例1 -- 直接编辑并创建一个文件 vim bak.sh-- 写入下面这句话 # 获取ip地址信息 ifconfig ens33 | grep -w inet | awk {print $2} | xargs echo "IP: "-- 运行bak文件 bash bak.sh或者-- 添加可执行权限 chmod ax bak.sh./bak.sh或者source ba…