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

前言

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

环境准备

创建conda虚拟环境

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

创建model_scope_llm虚拟环境

切换到model_scope_llm虚拟环境

安装Python环境

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

ini 复制代码
conda install python=3.10

安装Python3.10

安装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': 'auto'}, **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文件,等待几分钟之后控制台输出问题答案(由于使用的是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=['康康', 'Kang Kang'],
    model_author=['康驰', 'KangChi'])
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文件,等待几小时之后控制台输出微调后的模型目录(由于使用的是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-20241029-100816/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': 'auto'})
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文件,等待几分钟之后控制台输出问题答案(由于使用的是CPU方式,推理时间会长一些):

开始加载微调后的模型

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

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

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

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

相关推荐
农场主John3 小时前
Accelerate_deepspeed使用
pytorch·llm·deepspeed
组合缺一4 小时前
论 AI Skills 分布式发展的必然性:从单体智能到“云端大脑”的跃迁
java·人工智能·分布式·llm·mcp·skills
小哈里5 小时前
【计算】Ray框架介绍,AI基础设施之“通用”分布式计算(跨场景,门槛低,大规模生产,单机->集群->推理一站式)
人工智能·大模型·llm·分布式计算·ray
山顶夕景20 小时前
【VLM】Visual Merit or Linguistic Crutch? 看DeepSeek-OCR
大模型·llm·ocr·多模态
玄同76520 小时前
LangChain 核心组件全解析:构建大模型应用的 “乐高积木”
人工智能·python·语言模型·langchain·llm·nlp·知识图谱
亚里随笔1 天前
相对优势估计存在偏差——揭示群体相对强化学习中的系统性偏差问题
人工智能·深度学习·机器学习·llm·agentic·rlvr
带刺的坐椅1 天前
论 AI Skills 分布式发展的必然性:从单体智能到“云端大脑”的跃迁
java·ai·llm·mcp·tool-call·skills
中杯可乐多加冰1 天前
RAG 深度实践系列(三):RAG 技术演变与核心架构的深度剖析
人工智能·深度学习·大模型·llm·知识库·rag·graphrag
Wilber的技术分享1 天前
【Transformer原理详解2】Decoder结构解析、Decoder-Only结构中的Decoder
人工智能·笔记·深度学习·llm·transformer
猿小羽2 天前
AI 2.0 时代全栈开发实战:从 Spring AI 到 MLOps 的进阶指南
ai·llm·mlops·rag·vector database·spring ai·prompt engineering