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

前言

本文是基于ModelScopems-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模型。

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

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

相关推荐
袭明_2 小时前
AI大模型 之 词袋模型(Bag-of-words)
llm
阿牛大牛中4 小时前
大模型tokenizer重构流程
语言模型·llm·tokenizer·千问
xidianjiapei0018 小时前
构建大语言模型应用:简介(第一部分)
人工智能·语言模型·自然语言处理·llm·rag
小杨4041 天前
LLM大语言模型二(应用篇)
人工智能·llm
小小小怪兽1 天前
如何快速搭建一个RAG(Retrieval-Augmented Generation)🤖
人工智能·llm
boydfd1 天前
万字长文详解Text-to-SQL
llm·text-to-sql
小馒头学python1 天前
腾讯云HAI1元体验:DeepSeek-R1模型助力个人博客快速搭建
llm·云计算·腾讯云·hai要玩ai
憨憨睡不醒啊1 天前
DeepSearcher 解读——探秘 DeepSearch 和 DeepResearcher 的魅力🤓🤓🤓
开源·llm
Baihai_IDP1 天前
为什么大模型在 OCR 任务上表现不佳?
人工智能·llm·aigc