logo
0
0
Login

DeepSeek-R1-Distill-Qwen-7B Finetune on CNB

说明

本仓库展示了在 CNB 中,使用 unsloth华佗医疗数据集 medical-o1-reasoning-SFT 微调 DeepSeek-R1-Distill-Qwen-7B 模型的方法。

仓库镜像 .ide/Dockerfile 中已预装 pytorch、unsloth 等依赖库,可开箱即用。初次启动,需等待 3min 左右,生成自己仓库的微调环境镜像。

快速开始

  • fork 本仓库,并启动远程开发。finetune.ipynb 文件可以直接看到代码运行结果
  • 可以修改代码,点击 "Run All" 自己运行并体验。详细步骤见如下

配置 jupyter 环境

  1. 在控制台运行jupyter lab list 可展示本地 jupyter 服务运行地址。 复制服务地址

  2. 打开 finetune.ipynb 文件,将刚才的服务地址配置到 jupyter ![选择已存在的 Server](选择已存在的 Server.png) 粘贴服务地址 ![配置 Display name](配置 Display name.png) 选择内核

执行 Check 微调环境 脚本

执行脚本时,会打印当前环境的资源、依赖、模型预热情况

如果当前仓库是前三次使用,因为缓存没有在三台机器上完成准备,所以执行 check 时会下载 models 文件,大约 20min 左右。

执行三次后,该仓库的 models 就会完成缓存准备。

执行 原始模型输出 脚本

该脚本,会使用原始模型回答指定的医学问题,查看原始模型的输出

执行 微调模型 脚本

该脚本,会从 hugging face 上拉取指定数据集,并训练模型,然后使用模型微调后的模型还是回答原问题,比较差异

我希望 DIY 模型和数据集

DIY 模型

可以替换 Check 微调环境 脚本中的模型下载命令,需先清空 models 文件夹,以免还在复用缓存模型

result = subprocess.run([ "modelscope", "download", "--model", "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", "--local_dir", "./models" ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)

DIY 数据集

可以替换 模型微调 脚本中的加载数据集,以及也需要相应调整数据集的格式化,以及调整 prompt

调整获取的数据集

dataset = load_dataset("FreedomIntelligence/medical-o1-reasoning-SFT","zh", split = "train[0:2000]",trust_remote_code=True)

调整 prompt

train_prompt = """以下是描述任务的说明,并附有提供更多上下文的输入。 请写出问题的合适回复。 回答之前,请仔细分析问题并建立逐步拆解,循序渐进的思考链路,以确保回答合乎逻辑且准确。 ### 指令: 您是一位中国医学专家,你需要先分析患者的症状做出诊断,基于诊断结果给出合理的治疗方案。 请回答以下患者咨询,并给出合理且具体的治疗方案。 ### 问题: {} ### 回答: <think> {} </think> {}"""

调整数据集格式化脚本

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

调整模型训练参数

trainer = SFTTrainer( model=model, tokenizer=tokenizer, train_dataset=dataset, dataset_text_field="text", max_seq_length=2048, dataset_num_proc=2, args=TrainingArguments( per_device_train_batch_size=2, gradient_accumulation_steps=4, # Use num_train_epochs = 1, warmup_ratio for full training runs! 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=43, output_dir="outputs", report_to = "none", # Use this for WandB etc ), )

参考资料及致谢

About

DeepSeek-R1-Distill-Qwen-7B Finetune on CNB

Language
Jupyter49.6%
Markdown44.5%
Dockerfile3.1%
License2.3%
Others0.5%