手把手教学,DeepSeek-R1微调全流程拆解

news/2025/2/11 19:40:58/文章来源:https://www.cnblogs.com/shanren/p/18707513

DeepSeek 通过发布其开源推理模型 DeepSeek-R1 颠覆了 AI 格局,该模型使用创新的强化学习技术,以极低的成本提供与 OpenAI 的 o1 相当的性能。

更令人印象深刻的是,DeepSeek 已将其推理能力提炼成几个较小的模型。这篇文章,我们将使用其蒸馏版本之一引导大家完成 DeepSeek-R1 的整个微调过程。

本文章将演示了如何微调其中一个模型(使用我们自己的自定义思维链数据集),然后保存和部署微调后的模型。

图片

高级推理模型微调

DeepSeek 简介

DeepSeek-R1 是由深度求索(DeepSeek)公司开发的突破性推理模型。DeepSeek-R1 基于 DeepSeek-V3-Base(总共 671B 个参数,每次推理 37B 处于活动状态)构建,使用强化学习 (RL) 在提供最终答案之前生成思路链 (CoT)。

为了使这些功能更易于访问,DeepSeek 将其 R1 输出提炼成几个较小的模型:

  • 基于 Qwen 的蒸馏模型:1.5B、7B、14B 和 32B

  • 基于 Llama 的蒸馏模型:8B 和 70B

注意:对于 14B 模型,正确的变体是 DeepSeek-R1-Distill-Qwen-14B。

为什么 DeepSeek-R1 越来越受欢迎**

DeepSeek-R1 因其性能、可访问性和成本效益的结合而在 AI 社区中迅速受到关注。以下是它成为开发人员和研究人员首选的原因:

  • 开源可用性:完全开源,允许不受限制地使用、修改和分发。

  • 具有成本效益的培训:训练成本仅为 500 万美元,仅为大型语言模型成本的一小部分。

  • 强化学习和 CoT 推理:采用先进的强化学习技术来开发思维链推理。

  • 高效蒸馏:Distilled 模型在资源效率高的同时保持了强大的推理能力。

  • 活跃的社区和生态系统:不断增长的工具、微调模型和社区驱动型资源的生态系统。

下面是微调 DeepSeek-R1 以进行高级推理的完整过程。

01 环境设置和身份验证

a. 安装依赖项

使用具有 GPU 访问权限的首选环境。run:

!pip install unsloth
!pip install --force-reinstall --no-cache-dir --no-deps git+https://github.com/unslothai/unsloth.git

说明:这将安装 Unsloth,一个可加快微调速度(速度提高 2× 并减少 70% 内存使用量的框架)。

b. 登录Hugging Face和Weights & Biases

安全地检索 API Token:

from huggingface_hub import loginhf_token = “your_huggingface_token”
login(hf_token)

然后,初始化权重和偏差(wandb):

import wandbwb_token = “your_wandb_token”
wandb.login(key=wb_token)
run = wandb.init(project='合法 COT 数据集上的 Fine-tune-DeepSeek-R1-Distill-Qwen-14B', job_type=“training”, anonymous=“allow”
)

说明: 这些步骤可确保安全的模型下载和实验跟踪。

02 加载 Model 和 Tokenizer

使用具有 4 位量化的 Unsloth 加载蒸馏的 14B 模型,DeepSeek-R1-Distill-Qwen-14B:

from unsloth import FastLanguageModelmax_seq_length = 2048 
dtype = None 
load_in_4bit = True
model, tokenizer = FastLanguageModel.from_pretrained(model_name = “unsloth/DeepSeek-R1-Distill-Qwen-14B”,max_seq_length = max_seq_length,dtype = dtype,load_in_4bit = load_in_4bit,token = hf_token,
)

说明:为最多 2048 个 tokens 的序列配置模型,并使用 4-bit 量化来提高内存效率。

03 预微调推理

使用法律推理提示测试模型的基准性能。

定义 Prompt 并运行推理

prompt_style = """Below is an instruction that describes a task, paired with an input that provides further context. 
Write a response that appropriately completes the request. 
Before answering, think carefully about the question and create a step-by-step chain of thought to ensure a logical and accurate response.### Instruction:
You are a legal expert with advanced knowledge in legal reasoning, case analysis, and interpretation of laws. 
Please answer the following legal question.
### Question:
{}
### Response:
<think>{}"""question = "A contract was signed between two parties, but one party claims they were under duress. What legal principles apply to determine the contract's validity?"
FastLanguageModel.for_inference(model)
inputs = tokenizer([prompt_style.format(question, "")], return_tensors="pt").to("cuda")
outputs = model.generate(   input_ids=inputs.input_ids,   attention_mask=inputs.attention_mask,   max_new_tokens=1200,   use_cache=True,
)
response = tokenizer.batch_decode(outputs)
print(response[0].split("### Response:")[1])

说明:生成一个响应,其中包括模型的思路链,后跟其最终答案。

04 准备训练数据

加载并格式化数据集(这里我们使用 legal chain-of-mind 数据集)。

更新提示模板

train_prompt_style = """Below is an instruction that describes a task, paired with an input that provides further context. 
Write a response that appropriately completes the request. 
Before answering, think carefully about the question and create a step-by-step chain of thought to ensure a logical and accurate response.### Instruction:
You are a legal expert with advanced knowledge in legal reasoning, case analysis, and interpretation of laws. 
Please answer the following legal question.
### Question:
{}
### Response:
<think>
{}
</think>
{}"""
EOS_TOKEN = tokenizer.eos_token

定义 formatting 函数

def formatting_prompts_func(examples):   inputs = examples["Question"]   cots = examples["Complex_CoT"]   outputs = examples["Response"]   texts = []   for input_text, cot, output_text in zip(inputs, cots, outputs):       text = train_prompt_style.format(input_text, cot, output_text) + EOS_TOKEN       texts.append(text)   return {"text": texts}

加载和映射数据集

from datasets import load_dataset
dataset = load_dataset("kienhoang123/QR-legal", "en", split="train[0:500]", trust_remote_code=True)
dataset = dataset.map(formatting_prompts_func, batched=True)
print(dataset["text"][0])####Note: This is a pseudo dataset. Please create or use an appropriate dataset for your own use case.

说明:使用问题、详细的思路和最终答案来格式化每个训练示例,并附加 EOS 令牌。

05 设置 LoRA 以进行微调

使用 LoRA (Low-Rank Adaptation) 通过仅适配关键层来有效地微调模型:

model = FastLanguageModel.get_peft_model(   model,   r=16,   target_modules=[       "q_proj",       "k_proj",       "v_proj",       "o_proj",       "gate_proj",       "up_proj",       "down_proj",   ],   lora_alpha=16,   lora_dropout=0,   bias="none",   use_gradient_checkpointing="unsloth",   random_state=3407,   use_rslora=False,   loftq_config=None,
)

说明:将 LoRA 适配器应用于关键投影层,从而减少微调期间的内存和计算要求。

06 配置和运行训练过程

从 TRL 初始化 SFTTrainer 以及相应的训练参数。

from trl import SFTTrainer
from transformers import TrainingArguments
from unsloth import is_bfloat16_supportedtrainer = SFTTrainer(   model=model,   tokenizer=tokenizer,   train_dataset=dataset,   dataset_text_field="text",   max_seq_length=max_seq_length,   dataset_num_proc=2,   args=TrainingArguments(       per_device_train_batch_size=2,       gradient_accumulation_steps=4,       warmup_steps=5,       max_steps=60,       learning_rate=2e-4,       fp16=not is_bfloat16_supported(),       bf16=is_bfloat16_supported(),       logging_steps=10,       optim="adamw_8bit",       weight_decay=0.01,       lr_scheduler_type="linear",       seed=3407,       output_dir="outputs",   ),
)

开始训练:

trainer_stats = trainer.train()

说明: 此配置使用小批量和有限的演示步骤。根据需要进行调整以进行全面微调。

07 微调后的推理

使用相同的提示结构测试微调后的模型。

question = "A contract was signed between two parties, but one party claims they were under duress. What legal principles apply to determine the contract’s validity?"FastLanguageModel.for_inference(model)
inputs = tokenizer([prompt_style.format(question, "")], return_tensors="pt").to("cuda")
outputs = model.generate(   input_ids=inputs.input_ids,   attention_mask=inputs.attention_mask,   max_new_tokens=1200,   use_cache=True,
)
response = tokenizer.batch_decode(outputs)
print(response[0].split("### Response:")[1])

说明: 输出应具有简洁的思路链和清晰的最终答案。

08 保存和发布微调模型

本地保存

new_model_local = "DeepSeek-R1-Legal-COT"
model.save_pretrained(new_model_local)
tokenizer.save_pretrained(new_model_local)
model.save_pretrained_merged(new_model_local, tokenizer, save_method="merged_16bit")

推送到 Hugging Face Hub

new_model_online = "yourusername/DeepSeek-R1-Legal-COT"
model.push_to_hub(new_model_online)
tokenizer.push_to_hub(new_model_online)
model.push_to_hub_merged(new_model_online, tokenizer, save_method="merged_16bit")

说明:替换为 您的实际存储库名称。合并版本集成了 LoRA 适配器,以便于部署。

"yourusername/DeepSeek-R1-Legal-COT"

09 在 Ollama 中使用微调模型

要将微调模型 DeepSeek-R1-Legal-COT 与 Ollama 结合使用,请执行以下步骤:

准备模型文件

  • 确保您的微调模型以 SafeTensors 格式保存。

  • 将模型文件组织到系统上的目录中。

创建 Modelfile

  • 在包含模型文件的目录中,创建一个名为 (不带任何扩展名) 的文件。Modelfile

  • 将以下行添加到 :Modelfile

FROM /path/to/base/model
ADAPTER .
  • 替换为您在微调过程中使用的基础模型的路径。/path/to/base/model

  • 该行表示适配器 (您的微调模型) 位于当前目录中。ADAPTER .

使用 Ollama 构建模型

  • 打开终端并导航到包含。Modelfile

  • 执行以下命令,在 Ollama 中创建模型。

ollama create deepseek-r1-legal-cot
  • 此命令将构建模型并使其可在 Ollama 中使用。

运行模型

成功创建模型后,你可以使用以下方法与模型进行交互:

ollama run deepseek-r1-legal-cot

此命令允许您输入提示并接收来自微调模型的响应。

10 其他注意事项

  • 型号兼容性:确保中指定的基本模型与微调期间使用的基本模型匹配,以避免出现兼容性问题。Modelfile

  • 量化:如果您希望优化模型的性能,请考虑在步骤中对其进行量化。例如:ollama create

ollama create --quantize q4_K_M deepseek-r1-legal-cot
  • 此命令对模型进行量化,以减少内存使用并可能提高推理速度。

有关将模型和适配器导入 Ollama 的详细信息,请参阅官方 Ollama 文档。

https://github.com/ollama/ollama/blob/main/docs/import.md

11 其他提示和建议

  • 硬件设置:使用至少具有 24–32GB VRAM 的 GPU。

  • 数据预处理:确保您的数据集包含字段 、 和 ."Question""Complex_CoT""Response"

  • 超参数优化:根据数据集大小调整 和 epochs。max_steps

  • 监控训练:使用 wandb 控制面板跟踪损失和指标。

  • LoRA 洞察:LoRA 仅调整关键投影层,从而减少内存使用。

  • 部署:如果需要,将模型转换为 GGUF 等格式以进行本地部署。

Last but not least

DeepSeek-R1 代表了以推理为中心的 AI 的新时代。通过将高效的强化学习与监督式微调和蒸馏相结合,DeepSeek 生成的模型可与专有系统相媲美,同时具有开源性和成本效益。本指南将引导您完成每个步骤,从设置环境和加载模型,到数据准备和基于 LoRA 的微调,再到推理和部署。

对于 14B 蒸馏模型,请记住,正确的名称是 DeepSeek-R1-Distill-Qwen-14B。借助这些详细说明,我们现在可以微调和部署高性能推理模型,即使在适度的硬件上也是如此,从而为创新的 AI 应用程序铺平道路。


内容参考:

1. DeepSeek-R1 模型和蒸馏:

https://huggingface.co/deepseek-ai

2. Unsloth:加快和优化 LLM 微调:

https://github.com/unslothai/unsloth

3. DeepSeek-R1 for Madical DataSet 的微调示例:

https://www.datacamp.com/tutorial/fine-tuning-deepseek-r1-reasoning-model


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/881619.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【警惕!土地红线不容触碰】揭秘土地犯罪那些事儿

在快速发展的现代社会,土地作为宝贵的自然资源,其管理和保护显得尤为重要。然而,一些不法行为却不断侵蚀着这份宝贵资源,严重威胁到生态环境和国家利益。今天,我们就来深入探讨一下土地犯罪的种类,特别是聚焦一个常见且危害极大的罪行——非法占用耕地罪。土地犯罪的多种…

拒绝繁忙!免费使用 deepseek-r1:671B 参数满血模型

相信大家都已经有体验过deepseek-r1的强大推理能力,由于其网页版本免费使用的原因,用户量激增、同时据传还遭受了大量的网络攻击,这使得过程不是很流程,经常收到类似下图的问题:同时,API服务也已经暂停充值,之前的余额用完之后暂时也就不用调用了为了更流畅的使用对话或…

【未来风向】2025年10款顶尖项目管理软件,哪个最适合你的需求?

在当今快节奏的工作环境中,项目管理软件已成为团队协作和项目成功交付的关键工具。随着技术的不断发展,2025年市场上涌现出了众多功能强大、特色各异的项目管理软件。本文将为你详细介绍10款顶尖的项目管理软件,并分析它们各自的特点,帮助你找到最适合自己需求的那一款。一…

第四轮easy~hard

题目1代码 #include<bits/stdc++.h>#define endl \nusing namespace std;#define int long longint power(int a,int b,int p) {int tar=1;while(b){if(b&1)tar=(tar*a)%p;a=(1ll*a*a)%p;b>>=1;}return tar; }int read(int p) {int tar=0;string s;cin>>…

XMind2025电脑版最新免安装绿色解锁版

前言 XMind 2024中文版(就是XMind思维导图2024)是一款特别受欢迎的用来激发新想法和创造力的软件。在国内,很多人都在用它,因为它功能特别强大,不仅能帮助我们整理和管理思路,还能用来做商务展示,跟其他办公软件一起配合使用也很方便。这款软件用了一个国际上很先进的软…

Ollama+DeepSeek+AnythingLLM构建自己的大模型

环境:OS:windows 10###################################ollama的安装与配置######################################## 1.介质下载下载地址:https://ollama.com/download选择相应的操作系统版本下载,我这里下载的是windows版本。2.下载后点击运行安装OllamaSetup.exe双击运行,…

一款体积小巧、便捷、简单实用的windows任务栏透明美化工具

前言 如果你正在寻找一个能让Windows 10任务栏变得透明或者模糊的小工具,那么TranslucentTB正式版绝对是你的好帮手。它很小巧,用起来也很方便,而且功能很多。你可以通过它轻松地把任务栏变成透明的,或者给它加上一点模糊效果,这样你的桌面看起来就会更加整洁和美观。而且…

告警事件如何与 CMDB 打通附加更多元信息

告警事件产生之后,会带有一些 labels、annotations、description 等信息,有时这些信息不够规整需要二次处理,有时这些信息不够丰富需要附加更多信息,才方便 SRE 等 OnCall 人员快速定位、解决问题。具体应该如何做?本文会分享一些思路,希望对大家有所帮助。 需求场景举例…

deepseek基础篇--本地部署

官网:https://www.deepseek.com/ API文档:https://api-docs.deepseek.com/zh-cn/guides/reasoning_model 开放平台:https://platform.deepseek.com/usage 一、本地部署 本地安装Deepseek R1 Ollama本地安装Deepseek R1 模型 Ollama官网:https://ollama.com/ 打开官网,然后…

tabbar配置

tabbar在app.json中进行配置"tabBar": {"color": "#000000","selectedColor": "#000000","backgroundColor": "#000000","list": [{"pagePath": "pages/index/index",&q…

开放api接口平台:appid、appkey、appsecret 原创

转自:https://blog.51cto.com/u_14014612/5677760 开放api接口平台:appid、appkey、appsecret 原创 小波同学 2022-09-15 00:42:29 博主文章分类:日记本 文章标签 时间戳 客户端 数据 开放平台 开放api接口 文章分类 Java 后端开发 阅读数4314一、什么是appid、appkey、…

Pico 4 Enterprise(pico4企业版)玩转vrchat

下载PICOConnect-Oversea-release-signed.apk,使用数据线连接pico4e和电脑,直接将安装包上传到pico存储路径的安装包文件夹 到pico企业注册企业账号然后创建一个组织,组织随便起一个就行电话不用填 pico端打开设置,找到设备详情,连续点击8次版本号打开开发者选项,点开设置…