一、具体训练步骤
1. 环境准备
- 安装依赖库:
这些库均为开源工具,Hugging Face Transformers 和 PEFT 均免费使用145。pip install transformers peft datasets accelerate bitsandbytes
2. 加载模型与分词器
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained(
"deepseek-ai/deepseek-llm-7b-chat", # 模型名称或本地路径
torch_dtype=torch.bfloat16, # 半精度节省显存
device_map="auto" # 自动分配多卡
)
tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-llm-7b-chat")
说明:DeepSeek 模型需从 Hugging Face 下载,支持本地或在线加载13。
3. 数据处理与格式化
- 数据集格式:推荐单轮对话或多轮对话格式(JSON/CSV)
{"conversation": [{"human": "问题", "assistant": "回答"}]} # 单轮对话示例
- 数据预处理:
截断和填充保证序列长度一致13。def tokenize_function(examples): return tokenizer(examples["text"], padding="max_length", truncation=True, max_length=512) encoded_dataset = dataset.map(tokenize_function, batched=True)
4. 配置 PEFT(以 LoRA 为例)
from peft import LoraConfig, get_peft_model
lora_config = LoraConfig(
r=8, # 秩(推荐值 8-32)
lora_alpha=32, # 缩放系数
target_modules=["q_proj", "v_proj"], # 目标注意力层
lora_dropout=0.1,
task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters() # 示例输出:0.54% 参数可训练
5. 设置训练参数
from transformers import TrainingArguments
training_args = TrainingArguments(
output_dir="./output", # 输出路径
per_device_train_batch_size=4, # 批次大小(3090 建议 4)
gradient_accumulation_steps=8, # 梯度累积(显存不足时增大)
num_train_epochs=3,
learning_rate=2e-5, # 学习率
fp16=True, # 混合精度训练
logging_steps=10,
save_strategy="steps"
)
6. 启动训练
from transformers import Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=encoded_dataset,
tokenizer=tokenizer
)
trainer.train() # 开始微调
7. 模型保存与部署
model.save_pretrained("./output/lora_weights") # 保存 LoRA 权重
tokenizer.save_pretrained("./output")
# 合并权重(推理时可选)
model = model.merge_and_unload()
二、训练成本
-
技术方案免费:
- Hugging Face Transformers、PEFT 及相关库均为开源工具,无使用费用。
- DeepSeek 模型开源,可免费下载和微调。
-
硬件成本:
- 显存需求:DeepSeek-7B 微调需至少 15GB 显存(如单卡 3090/4090)。
- 云平台租用:若本地无 GPU,可租用云服务器(如每小时 1.7 元/小时的 4090 实例)。
-
数据成本:
- 公开数据集(如 EmoLLM)可免费使用3,私有数据标注可能需额外费用。
三、优化技巧
-
显存不足解决方案:
- 4-bit 量化:通过
bitsandbytes
启用量化训练,显存需求可降至 8GB 以下:model = AutoModelForCausalLM.from_pretrained(..., load_in_4bit=True)
- 梯度检查点:牺牲 20% 训练速度换取显存优化:
model.gradient_checkpointing_enable()
- 4-bit 量化:通过
-
分布式训练:
- 使用
accelerate
或deepspeed
加速多卡训练:accelerate launch --num_processes=4 train.py
- 使用
四、完整流程示例
以情感化回复微调为例:
- 数据:使用 EmoLLM 单轮对话数据集。
- 训练:注入 LoRA 至 Q/V 注意力层,训练 3 轮。
- 效果:模型回复更自然,减少“套路化”表达。