Hermes 4微调

Hermes 4微调实战:从数据准备到模型部署全流程

为什么要微调Hermes 4? Hermes 4虽然原生支持函数调用,但企业场景有特殊需求: 行业术语:医疗、法律、金融等领域专有词汇 企业API:内部系统的特定接口规范 业务流程:特定的操作顺序和判断逻辑 合规要求:输出格式和内容限制 微调能让模型"学会"这些领域知识,比prompt工程更稳定高效。 微调方法选择 方法 显存需求 训练速度 效果 适用场景 全量微调 模型大小×4 慢 最好 数据充足、资源充足 LoRA 模型大小×1.5 快 好 通用首选 QLoRA 模型大小×0.5 中 中好 显存有限 IA³ 极低 极快 中 快速实验 推荐:LoRA——性价比最高,效果接近全量微调。 数据准备 1. 数据格式 Hermes 4使用OpenAI兼容的对话格式: { "messages": [ { "role": "system", "content": "你是企业客服助手。" }, { "role": "user", "content": "订单2024001什么时候发货?" }, { "role": "assistant", "content": "", "tool_calls": [ { "id": "call_001", "type": "function", "function": { "name": "query_order", "arguments": "{\"order_id\": \"2024001\"}" } } ] }, { "role": "tool", "tool_call_id": "call_001", "content": "{\"status\": \"已付款\", \"ship_date\": \"2026-07-09\"}" }, { "role": "assistant", "content": "您的订单2024001已付款,预计7月9日发货。" } ] } 2. 数据收集策略 class TrainingDataBuilder: def __init__(self): self.samples = [] def from_logs(self, conversation_logs): """从客服对话日志提取训练样本""" for log in conversation_logs: # 筛选高质量对话 if log.resolution == "success" and log.satisfaction >= 4: sample = self.format_conversation(log) self.samples.append(sample) def from_templates(self, templates): """从模板生成多样化训练样本""" for template in templates: # 使用LLM扩展模板为多种表达方式 variations = self.expand_template(template, n=10) self.samples.extend(variations) def from_synthetic(self, scenario, n=100): """使用强模型生成合成数据""" prompt = f"为'{scenario}'场景生成{n}个多样化的客服对话样本" synthetic = strong_model.generate(prompt) self.samples.extend(self.validate(synthetic)) def build(self): """构建训练集""" # 去重 self.samples = self.deduplicate(self.samples) # 质量过滤 self.samples = self.filter_quality(self.samples) # 划分训练/验证集 return self.split(self.samples, ratio=0.95) 3. 数据质量标准 def quality_check(sample): checks = [ len(sample["messages"]) >= 3, # 至少3轮 has_system_prompt(sample), # 有系统提示 tool_calls_valid(sample), # 工具调用格式正确 response_length_reasonable(sample), # 响应长度合理 no_sensitive_info(sample), # 无敏感信息 function_args_match_schema(sample), # 参数匹配schema ] return all(checks) LoRA微调实战 1. 环境准备 # 硬件:A100 80GB 或 2x RTX 4090 # 软件: pip install torch transformers peft trl accelerate bitsandbytes 2. 训练配置 import torch from transformers import AutoModelForCausalLM, AutoTokenizer from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training from trl import SFTTrainer, SFTConfig # 加载模型 model_id = "NousResearch/Hermes-4-14B" tokenizer = AutoTokenizer.from_pretrained(model_id) # 4-bit量化加载(节省显存) model = AutoModelForCausalLM.from_pretrained( model_id, quantization_config=BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_quant_type="nf4", ), device_map="auto" ) model = prepare_model_for_kbit_training(model) # LoRA配置 lora_config = LoraConfig( r=64, # LoRA秩 lora_alpha=128, # 缩放因子 target_modules=[ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj" ], lora_dropout=0.05, task_type="CAUSAL_LM", modules_to_save=["embed_tokens", "lm_head"] # 保存嵌入层 ) model = get_peft_model(model, lora_config) 3. 训练执行 # 训练数据 train_dataset = load_dataset("json", data_files="train.jsonl") eval_dataset = load_dataset("json", data_files="eval.jsonl") # 训练配置 training_args = SFTConfig( output_dir="./hermes-4-finetuned", num_train_epochs=3, per_device_train_batch_size=4, per_device_eval_batch_size=4, gradient_accumulation_steps=4, warmup_ratio=0.03, learning_rate=2e-4, lr_scheduler_type="cosine", logging_steps=10, eval_strategy="steps", eval_steps=100, save_steps=200, bf16=True, gradient_checkpointing=True, max_seq_length=4096, ) # 训练器 trainer = SFTTrainer( model=model, args=training_args, train_dataset=train_dataset["train"], eval_dataset=eval_dataset["train"], tokenizer=tokenizer, ) # 开始训练 trainer.train() # 保存 trainer.save_model("./hermes-4-finetuned") 4. 训练监控 # 关键指标 metrics_to_watch = { "train_loss": "应持续下降", "eval_loss": "应跟随train_loss下降", "eval_loss > train_loss + 0.5": "过拟合警告", "learning_rate": "按cosine衰减", "grad_norm": "应在1-10范围内", } # 典型训练曲线(3 epochs) # Epoch 0.5: train_loss=1.8, eval_loss=1.9 # Epoch 1.0: train_loss=1.2, eval_loss=1.3 # Epoch 1.5: train_loss=0.9, eval_loss=1.1 # Epoch 2.0: train_loss=0.7, eval_loss=0.9 # Epoch 2.5: train_loss=0.5, eval_loss=0.85 # Epoch 3.0: train_loss=0.4, eval_loss=0.82 ← 最佳 评估与调优 1. 评估维度 class ModelEvaluator: def evaluate(self, model, test_set): results = {} # 函数调用准确率 results["tool_call_acc"] = self.eval_tool_calls(model, test_set) # 参数匹配率 results["param_match"] = self.eval_params(model, test_set) # 多轮对话一致性 results["multi_turn"] = self.eval_multi_turn(model, test_set) # 错误恢复能力 results["error_recovery"] = self.eval_error_handling(model, test_set) # 语气/风格一致性 results["style"] = self.eval_style(model, test_set) return results 2. 评估结果示例 维度 微调前 微调后 提升 函数调用准确率 72% 96% +24% 参数匹配率 68% 93% +25% 多轮一致性 80% 95% +15% 错误恢复 65% 88% +23% 风格一致性 70% 97% +27% 3. 常见问题与调优 问题1:过拟合 ...

2026-07-08 · 4 min · 675 words · 硅基 AGI 探索者
Hermes 4架构

Nous Hermes 4架构解析:开源函数调用模型的新标杆

Nous Hermes 4 简介 Nous Hermes系列是Nous Research开发的开源大模型家族,以出色的函数调用能力和指令遵循闻名。2026年,Hermes 4成为开源Agent开发的热门选择。 核心定位 开源免费:Apache 2.0许可 函数调用原生支持:不需要额外微调 多尺寸覆盖:7B/14B/70B/405B 模型无关:可本地部署,数据不出域 版本演进 版本 发布时间 基座模型 核心改进 Hermes 2 2024 Q3 Llama 3 基础函数调用 Hermes 3 2025 Q1 Llama 3.1 多轮函数调用 Hermes 4 2026 Q1 Llama 4 结构化输出+Agent能力 架构深度解析 模型架构 Hermes 4基于Llama 4架构,关键改进在训练数据和后训练流程: Llama 4 基座模型 ↓ 监督微调(SFT) - 100万+函数调用样本 - 50万+多轮对话样本 - 20万+结构化输出样本 ↓ 偏好优化(DPO) - 函数调用准确性偏好 - 指令遵循偏好 - 安全偏好 ↓ Constitutional AI - 安全约束 - 诚实性约束 - 帮助性约束 ↓ Hermes 4 最终模型 函数调用架构 Hermes 4的函数调用不是简单的prompt工程,而是训练阶段内化的能力: ...

2026-07-08 · 3 min · 528 words · 硅基 AGI 探索者
鲁ICP备2026018361号