【LLM模型】【自我认知微调】实践基于【ModelScope】的【ms-swift】框架【GPU】方式

前言

本文是基于ModelScope的ms-swift框架使用GPU的方式进行的LLM模型的自我认知微调实践

环境准备

创建conda虚拟环境

lua 复制代码
conda create -n model_scope_llm_gpu
conda activate model_scope_llm_gpu

创建model_scope_llm_gpu虚拟环境

切换到model_scope_llm_gpu虚拟环境

安装Python环境

本次实践Python版本依旧采用3.10版本

ini 复制代码
conda install python=3.10

安装Python3.10

安装pytorch-cuda环境

ini 复制代码
conda install pytorch==2.5.0 torchvision==0.20.0 torchaudio==2.5.0 pytorch-cuda=12.1 -c pytorch -c nvidia

pytorch-cuda安装开始

pytorch-cuda安装成功

安装ms-swift环境

arduino 复制代码
pip install 'ms-swift[llm]' -U

也可使用国内镜像,安装速度更快

arduino 复制代码
pip install 'ms-swift[llm]' -U -i https://pypi.tuna.tsinghua.edu.cn/simple

ms-swift安装开始

ms-swift安装成功

IDE准备

使用PyCharm IDE工具创建一个自己的项目目录:

选择File->New Project

选择已经创建好的虚拟环境

点击Create创建成功后会默认生成一个main.py的文件,等待右下角环境加载完成后,run运行一下main.py文件,成功打印Hi, PyCharm内容说明创建成功:

main.py文件

加载虚拟环境

main.py运行成功

LLM模型微调前推理

在新建的项目中创建一个inference_before.py文件,写入以下代码:

python 复制代码
import os

os.environ['CUDA_VISIBLE_DEVICES'] = '0'

from swift.llm import (
    get_model_tokenizer, get_template, inference, ModelType,
    get_default_template_type, inference_stream
)
from swift.utils import seed_everything
import torch

model_type = ModelType.glm4_9b_chat
template_type = get_default_template_type(model_type)
print(f'template_type: {template_type}')


kwargs = {}
model_id_or_path = None
model, tokenizer = get_model_tokenizer(model_type, torch.float16, model_id_or_path=model_id_or_path,
                                       model_kwargs={'device_map': 'cuda:0'}, **kwargs)
# 修改max_new_tokens
model.generation_config.max_new_tokens = 128

template = get_template(template_type, tokenizer)
seed_everything(42)

query = '你是谁?'
response, history = inference(model, template, query)
print(f'response: {response}')
print(f'history: {history}')

项目名称右键->NEW->Python File

inference_before.py文件创建成功

写入代码

运行写好的inference_before.py文件,等待三十几秒之后控制台输出问题答案(GPU方式要比CPU方式快很多):

加载本地glm模型

成功输出问题答案

LLM模型自我认知微调

在项目中创建一个inference_train.py文件,写入以下代码:

python 复制代码
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'

from swift.llm import DatasetName, ModelType, SftArguments, sft_main

sft_args = SftArguments(
    model_type=ModelType.glm4_9b_chat,
    dataset=[f'{DatasetName.alpaca_zh}#500', f'{DatasetName.alpaca_en}#500',
             f'{DatasetName.self_cognition}#500'],
    max_length=1024,
    learning_rate=1e-4,
    output_dir='output',
    lora_target_modules=['ALL'],
    model_name=['张三', 'Zhang San'],
    model_author=['李四', 'LiSi'],
    device_map_config='0')
output = sft_main(sft_args)
best_model_checkpoint = output['best_model_checkpoint']
print(f'best_model_checkpoint: {best_model_checkpoint}')

项目名称右键->NEW->Python File

inference_train.py文件创建成功

写入代码

运行写好的inference_train.py文件,等待四十几分钟之后控制台输出微调后的模型目录(GPU方式要比CPU方式快的多的多):

开始自我认知微调训练

完成自我认知微调训练

LLM模型微调后推理

在项目中创建一个inference_after.py文件,写入以下代码:

python 复制代码
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'

from swift.llm import (
    get_model_tokenizer, get_template, inference, ModelType, get_default_template_type,
)
from swift.utils import seed_everything
from swift.tuners import Swift

seed_everything(42)

ckpt_dir = 'output/glm4-9b-chat/v0-20241030-141255/checkpoint-93' #填写自己微调后的模型目录
model_type = ModelType.glm4_9b_chat
template_type = get_default_template_type(model_type)
model_id_or_path = None
model, tokenizer = get_model_tokenizer(model_type, model_id_or_path=model_id_or_path, model_kwargs={'device_map': 'cuda:0'})
model.generation_config.max_new_tokens = 128

model = Swift.from_pretrained(model, ckpt_dir, inference_mode=True)
template = get_template(template_type, tokenizer)

query = '你是谁?'
response, history = inference(model, template, query)
print(f'response: {response}')
print(f'history: {history}')

项目名称右键->NEW->Python File

inference_after.py文件创建成功

写入代码并修改模型目录

运行写好的inference_after.py文件,等待二十几秒之后控制台输出问题答案(GPU方式要比CPU方式快很多):

开始加载微调后的模型

成功输出微调后的问题答案

本次实践采用的是智普清言的glm4-9b-chat模型,也可以换成通义千问等其他的开源LLM模型。

注意:初次使用模型会先下载模型到本地,时间会长一点。

至此基于ModelScope的ms-swift框架使用GPU的方式进行的LLM模型的自我认知微调实践圆满完成。

相关推荐
deepseek235 小时前
硬预算帽默认值拆解:AWS 九月上线支出上限、GCP 七月跟进,Agent 时代按量付费必须默认断供
人工智能·llm·云计算·agent·aws
lucas_AI7 小时前
别等上下文爆了才压缩:AutoCompact 教编码智能体主动「断舍离」
llm·agent
用户3134672143547 小时前
Agent相关 - agent_scratchpad 到底该放哪?一个隐蔽的顺序坑
langchain·llm·agent
浮生望9 小时前
大模型结构化输出怎么选:从 JSON.parse、OutputParser 到 Zod
llm
AINative软件工程9 小时前
LLM Prompt Registry 工程实践:集中管理 Prompt,让模型调用不再散落在代码各处
后端·python·llm
XLYcmy19 小时前
Dify 本地部署、Ollama 与 Xinference 集成:踩坑与最佳实践指南
llm·agent·dify·rag·ollama·rerank·harness
吃饱了得干活1 天前
Agent 的架构、多智能体与落地:从 Demo 到生产系统
llm·agent
CoderJia程序员甲1 天前
GitHub 热榜项目 - 周榜(2026-10-03)
ai·大模型·llm·github·ai教程
bullkingluo1 天前
从零到一搭建企业级智能问答系统:Ch12 · 结构化输出与工具调用
人工智能·架构·llm
桃西西呀1 天前
LangChain 之五:智能体与工具
人工智能·langchain·llm