基于DeepSeek-R1-Distill-Llama-8B的健康管理助手微調過程
本次創新實訓項目的主要任務是利用DEEPSEEK提供的開源模型,通過微調技術,實現一個專注于健康管理與醫療咨詢的人工智能助手。本文詳細記錄我們如何對DeepSeek-R1-Distill-Llama-8B模型進行微調,以滿足健康醫療領域應用的需求。
為什么選擇DeepSeek-R1-Distill-Llama-8B?
我們選擇DeepSeek-R1-Distill-Llama-8B模型主要基于以下原因:
- 模型規模合適:8B參數規模在GPU資源有限的條件下也能高效訓練。
- 中文理解能力強:特別適合醫療咨詢類問題,語言表述清晰且專業。
- 開放與自由:DeepSeek系列的開源特性讓我們能靈活地微調和部署。
數據集的選擇和介紹
我們使用的是FreedomIntelligence醫療推理數據集。該數據集專注于醫療推理任務,每條數據由以下三個部分組成:
- Question:醫學問題描述。
- Complex_CoT:詳細的醫學推理過程。
- Response:醫學建議或診療方案。
數據示例:
{"Question": "一個患有急性闌尾炎的病人已經發病5天,腹痛稍有減輕但仍然發熱...","Complex_CoT": "考慮病程較長,闌尾可能已形成膿腫,需要進一步處理...","Response": "建議首先進行保守治療,如有必要再考慮手術干預。"
}
LoRA 微調原理詳解
LoRA (Low-Rank Adaptation) 是一種高效的微調技術,通過凍結原模型的參數,僅通過低秩矩陣來適應新任務。具體而言,LoRA在原始權重矩陣 W 0 ∈ R d × d W_0 \in \mathbb{R}^{d \times d} W0?∈Rd×d 基礎上,增加了兩個低秩矩陣 A ∈ R r × d A \in \mathbb{R}^{r \times d} A∈Rr×d 和 B ∈ R d × r B \in \mathbb{R}^{d \times r} B∈Rd×r,實現權重微調:
Δ W = B A ( r ? d ) \Delta W = BA \quad (r \ll d) ΔW=BA(r?d)
實際更新后的權重表示為:
W = W 0 + B A W = W_0 + BA W=W0?+BA
LoRA的參數設置包括:
- r (rank):控制模型微調的容量與精度,通常取8至64。
- lora_alpha:放大系數,用于調整LoRA微調的學習強度,通常與r取相近數值。
通過LoRA,能夠極大降低訓練成本與顯存占用,僅用少量參數即可有效微調。
微調實現過程
環境配置
!pip install unsloth bitsandbytes transformers datasets trl
模型加載與量化
使用Unsloth進行高效加載(使用4-bit量化):
from unsloth import FastLanguageModelmodel, tokenizer = FastLanguageModel.from_pretrained("unsloth/DeepSeek-R1-Distill-Llama-8B",max_seq_length=2048, load_in_4bit=True
)
數據集處理
構建適合模型微調的Prompt模板:
from datasets import load_datasetEOS = tokenizer.eos_tokendef formatting_prompts_func(examples):texts = []for q, cot, ans in zip(examples["Question"], examples["Complex_CoT"], examples["Response"]):text = f"""Below is an instruction...
### Question:
{q}### Response:
<think>
{cot}
</think>
{ans}{EOS}"""texts.append(text)return {"text": texts}dataset = load_dataset("FreedomIntelligence/medical-o1-reasoning-SFT",'zh',split="train[:500]"
).map(formatting_prompts_func, batched=True)
LoRA微調參數配置
model = FastLanguageModel.get_peft_model(model,r=16, # 設定秩大小lora_alpha=16, # LoRA放縮因子target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],use_gradient_checkpointing="unsloth"
)
微調訓練
使用TRL庫的SFTTrainer進行高效訓練:
from trl import SFTTrainer
from transformers import TrainingArgumentstrainer = SFTTrainer(model=model,tokenizer=tokenizer,train_dataset=dataset,dataset_text_field="text",args=TrainingArguments(per_device_train_batch_size=2,gradient_accumulation_steps=4,max_steps=60,learning_rate=2e-4,fp16=True,output_dir="outputs",logging_steps=1)
)trainer.train()
微調后模型簡單推理驗證
FastLanguageModel.for_inference(model)question = "“最近感覺睡眠質量差,晚上容易醒來,白天精神也不好,應該如何調理?"
inputs = tokenizer([question], return_tensors="pt").to("cuda")outputs = model.generate(input_ids=inputs.input_ids,attention_mask=inputs.attention_mask,max_new_tokens=1024
)response = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(response)
通過上述過程,可以初步看到我們微調后的模型,在醫療問題回答的邏輯性和專業性上明顯優于未經微調的模型,這驗證了LoRA微調方法和我們整體微調流程的有效性。
總結
本文介紹了我們項目中如何基于DeepSeek-R1-Distill-Llama-8B模型,采用LoRA技術及醫療推理數據進行高效的微調訓練。這為后續“健康管理助手”智能體的開發和應用提供了重要的基礎。