大模型微调入门(Transformers + Pytorch)

server/2025/3/3 21:11:31/

目标

输入:你是谁?

输出:我们预训练的名字。

训练

为了性能好下载小参数模型,普通机器都能运行。

下载模型

python"># 方式1:使用魔搭社区SDK 下载
# down_deepseek.py
from modelscope import snapshot_download
model_dir = snapshot_download('deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B')# 方式2:git lfs 
# 需要提前安装git大文件存储 git-lfs
# 在线查看 https://www.modelscope.cn/models/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B
git lfs install
git clone https://www.modelscope.cn/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B.git

训练模型

python"># finetune_deepseek.py
from datasets import Dataset
from transformers import (AutoModelForCausalLM,AutoTokenizer,TrainingArguments,Trainer,DataCollatorForLanguageModeling
)# 加载模型和分词器
model_name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True)# 准备训练数据
train_data = [{"question": "你是谁?","answer": "我是黄登峰。"},{"question": "你的名字是什么?","answer": "黄登峰"},{"question": "你是做什么的?","answer": "我是深圳一家公司打工的牛马程序员。"},# 在这里添加更多的问答对
]test_data = [{"question": "你的名字是什么?","answer": "我的名字是黄登峰。"}
]
def format_instruction(example):"""格式化输入输出对"""return f"Human: {example['question']}\n\nAssistant: {example['answer']}"# 转换数据格式
train_formatted_data = [{"text": format_instruction(item)} for item in train_data]
test_formatted_data = [{"text": format_instruction(item)} for item in test_data]
train_dataset = Dataset.from_list(train_formatted_data)
test_dataset = Dataset.from_list(test_formatted_data)# 数据预处理函数
def preprocess_function(examples):return tokenizer(examples["text"], truncation=True, padding="max_length", max_length=512)# 对数据集进行预处理
train_tokenized_dataset = train_dataset.map(preprocess_function,batched=True,remove_columns=train_dataset.column_names
)test_tokenized_dataset = test_dataset.map(preprocess_function,batched=True,remove_columns=test_dataset.column_names
)
output_dir = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B_CUSTOM"# 训练参数设置
training_args = TrainingArguments(output_dir=output_dir,num_train_epochs=3,per_device_train_batch_size=4,save_steps=100,save_total_limit=2,learning_rate=2e-5,weight_decay=0.01,logging_dir="./logs",logging_steps=10,
)# 创建训练器
trainer = Trainer(model=model,args=training_args,train_dataset=train_tokenized_dataset,eval_dataset=test_tokenized_dataset,data_collator=DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False),
)# 开始训练
trainer.train()# 保存模型
trainer.save_model()
# 保存tokenizer
tokenizer.save_pretrained(output_dir)

模型格式

训练后的模型输出格式是Hugging Face格式,vllm 可以直接使用,ollama,llama.cpp默认是GGUF格式。

# 需要用llama.cpp仓库的convert_hf_to_gguf.py脚本来转换
git clone https://github.com/ggerganov/llama.cpp.git
pip install -r llama.cpp/requirements.txt
# 如果不量化,保留模型的效果
python llama.cpp/convert_hf_to_gguf.py ./DeepSeek-R1-Distill-Qwen-1.5B  --outtype f16 --verbose --outfile DeepSeek-R1-Distill-Qwen-1.5B.gguf
# 如果需要量化(加速并有损效果),直接执行下面脚本就可以
python llama.cpp/convert_hf_to_gguf.py ./DeepSeek-R1-Distill-Qwen-1.5B  --outtype q8_0 --verbose --outfile DeepSeek-R1-Distill-Qwen-1.5B.gguf

验证

python"># test_model.py
from transformers import AutoModelForCausalLM, AutoTokenizer
import torchdef generate_response(prompt, model, tokenizer, max_length=512):# 将输入格式化为训练时的格式formatted_prompt = f"Human: {prompt}\n\nAssistant:"# 对输入进行编码inputs = tokenizer(formatted_prompt, return_tensors="pt", padding=True, truncation=True)# 生成回答with torch.no_grad():outputs = model.generate(inputs.input_ids,max_length=max_length,num_return_sequences=1,temperature=0.7,do_sample=True,pad_token_id=tokenizer.pad_token_id,eos_token_id=tokenizer.eos_token_id,)# 解码输出response = tokenizer.decode(outputs[0], skip_special_tokens=True)# 提取Assistant的回答部分response = response.split("Assistant:")[-1].strip()return responsedef main():# 加载微调后的模型和分词器model_path = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B_CUSTOM"tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True)# 准备测试问题test_questions = ["你是谁?","你的名字是什么?","你是做什么的?",]# 测试模型回答print("开始测试模型回答:")print("-" * 50)for question in test_questions:print(f"问题: {question}")response = generate_response(question, model, tokenizer)print(f"回答: {response}")print("-" * 50)if __name__ == "__main__":main()


http://www.ppmy.cn/server/172164.html

相关文章

smolagents学习笔记系列(番外一)使用DeepSeek API Key + CodeAgent

这篇文章是在 smolagents 官方教程结束后的番外篇,实现了如何使用 DeepSeek API Key CodeAgent 执行你的提示词。 之所以写这篇文章是因为 smolagents 没有提供 DeepSeek 的模型接口,尽管可以通过 HfApiModel 这个类来指定使用与 DeepSeek 相关的模型&…

【前端知识】Vue2.x与3.x之间的区别以及升级过程需要关注的地方

文章目录 Vue 2.x 与 Vue 3.x**Vue 2.x 与 Vue 3.x 的区别详细说明****1. 核心特性与性能****2. API 变化****3. 新增特性****4. 工具链与生态系统** **从 Vue 2 升级到 Vue 3 的注意事项****1. 检查依赖库兼容性****2. 修改代码以适配 Vue 3 的 API****3. 处理废弃功能****4. …

C++ ++++++++++

初始C 注释 变量 常量 关键字 标识符命名规则 数据类型 C规定在创建一个变量或者常量时,必须要指定出相应的数据类型,否则无法给变量分配内存 整型 sizeof关键字 浮点型(实型) 有效位数保留七位,带小数点。 这个是保…

CSS 系列之:基础知识

块级元素和内联元素 块级元素行内元素块级元素是指在页面上以块的形式显示的元素内联元素&#xff08;又称行内元素&#xff09;以行的形式显示它们会独占一行&#xff0c;并且默认情况下会占满其父元素的宽度不独占一行<div>、<p>、<h1>至<h6>、<…

16. LangChain实战项目2——易速鲜花内部问答系统

需求简介 易束鲜花企业内部知识库如下&#xff1a; 本实战项目设计一个内部问答系统&#xff0c;基于这些内部知识&#xff0c;回答内部员工的提问。 在前面课程的基础上&#xff0c;需要安装的依赖包如下&#xff1a; pip install docx2txt pip install qdrant-client pip i…

进阶--jvm

目录 jvm部分 jvm的作用 jvm内部构造 垃圾回收部分 类加载系统 类加载过程 类在哪些情况下被加载 类在以下两种情况下,是不会被加载的 运行时数据区 程序计数器 本地方法栈 堆 堆空间区域划分 为什么分区(代) 对象创建存储过程: JVM调优 方法区 方法区的垃圾…

Github 仓库 git clone 速度过慢解决方案

很多时候想从 GitHub 上 clone 一个仓库&#xff0c;都会遇到速度慢的问题&#xff0c;而且经常连接失败&#xff0c;这里给出有效解决方案。 一、背景 应该是很多小伙伴碰到过的问题&#xff1a;想从 GitHub 上面 clone 项目&#xff0c;很多情况下会慢的离谱&#xff0c;等…

专业工具,提供多种磁盘分区方案

随着时间的推移&#xff0c;电脑的磁盘空间往往会越来越紧张&#xff0c;许多人都经历过磁盘空间不足的困扰。虽然通过清理垃圾文件可以获得一定的改善&#xff0c;但随着文件和软件的增多&#xff0c;磁盘空间仍然可能显得捉襟见肘。在这种情况下&#xff0c;将其他磁盘的闲置…