AI 学习笔记阅读台
16 安全 / 评估 / 部署

微调 / 评估 / 可观测

Langfuse、promptfoo 红队、LoRA/evals、失败模式

什么时候微调、LoRA 超参起点、evals 怎么做(error analysis、pass/fail 评委、pass@k)、tracing 工具。

我的理解:微调

  • 先 Prompt → 再 RAG → 最后才微调。微调管格式 / 风格 / 领域术语 / 小模型替大模型降本,不管灌新知识(那是 RAG 的事)。
  • LoRA 只训练低秩适配矩阵,存下来只是一个 adapter;QLoRA 是 4bit 上做 LoRA。Unsloth 的说法:LoRA 16bit 稍快稍准,但显存是 QLoRA 的 4 倍左右。
  • Unsloth LoRA 超参指南给的起点:普通 LoRA / QLoRA 学习率 2e-4(DPO、GRPO 这类 RL 用 5e-6);1-3 个 epoch,超过 3 个收益递减、容易过拟合;rank 推荐 16 或 32;alpha 取 r 或 2r;dropout 他们默认 0(说不太有用);target 覆盖全部主要线性层 q/k/v/o + gate/up/down,attention 和 MLP 都要。
  • TRL SFTTrainer:对话数据设 assistant_only_loss=True 只在回答部分算 loss;packing=True 把多条样本拼进一个序列提效率。
  • 不想写训练代码:LLaMA-Factory WebUI。部署推理(Ollama / vLLM / SGLang)挪到《部署:本地推理与阿里云》了。

我的理解:评估

  • 评估就是测试用例:没有 golden set,就证明不了任何一次修改是变好还是变坏。
  • Hamel Husain 的 evals FAQ 我最该记住的三条:先做 error analysis 再搭基础设施,每次大改后花 30 分钟人工看 20-50 条输出;他们项目里 60-80% 的开发时间花在 error analysis 和评估上;评委用 pass/fail 二元判断,别用 1-5 分(相邻分数主观、标注不一致)。
  • error analysis 的步骤:拿约 100 条真实 trace → open coding(自由记笔记)→ axial coding(归成失败类型并计数,最关键的一步)→ 按频次决定写哪些 eval。最好一个“benevolent dictator”领域专家来标。
  • LLM 评委(Hamel 的 critique shadowing):领域专家只回答“有没有达成目标”,pass/fail + 一段 critique;用这些 critique 做评委 prompt 的 few-shot,再拿人工标签当测试集验证评委。Eugene Yan 那篇讲评委和人工的一致性:二元 / 分类数据看 Cohen’s κ。
  • Anthropic《Demystifying evals for AI agents》的术语表:task(一个测试用例)、trial(一次尝试,要跑多次)、grader(评分逻辑,可含多个 assertion / check)、transcript(trace / trajectory,完整记录)、outcome(环境里最终状态——agent 说“订好了”不算,数据库里有订单才算)。
  • 同一篇:grader 分 code-based / model-based / human 三类;capability eval 从低通过率起步给团队爬坡,regression eval 应接近 100%;pass@k 是 k 次里至少一次成功,pass^k 是 k 次全成功——要稳定性的 agent 看 pass^k。
  • 对我的书签 RAG:先人工看 50 条问答记失败类型,再写 golden set;评委只判 pass/fail;检索单独看 recall@k。

我的理解:可观测

  • 可观测 = 把每次调用的 prompt、模型、输出、token、耗时、工具调用都记成 trace,error analysis 才有原料。
  • Langfuse:开源(MIT),OpenAI SDK 有 drop-in 包装,换一下 import 就自动记 trace;LangChain 走 callback handler。具体 import 路径 raw 里的代码块被剥掉了,用之前看官方 get-started。
  • OpenTelemetry 有 GenAI 语义约定(gen_ai.* 属性),Langfuse 的 JS 集成也是基于 OTel 的。Arize Phoenix、LangSmith 是同类工具。
  • 工作流平台 / 自研 agent 自带的 trace 和这些工具怎么接,我还没查。

代码

evalx.py —— golden set + pass/fail 评委 + recall@k(没实跑过)

python
# evalx.py —— 评估 = 测试用例:规则检查 + pass/fail 评委(带 critique)+ recall@k
import json
from llm import chat
from rag import rag

GOLDEN = [                     # 先做 error analysis,再按失败类型写用例:常见、边界、资料里没有的
    {"q": "系统支持哪些向量库?", "must": ["Milvus"]},
    {"q": "公司的年假政策是什么?", "must": ["不知道"]},   # 资料里没有 → 应拒答
]

JUDGE = """你是评分员。问题:{q}
参考要点:{must}
模型回答:{a}
只判断一件事:回答是否达到了要求(正确、有出处、资料里没有时会拒答)。
先写一句 critique 说明理由,再给结论。只输出 JSON:{{"critique": str, "pass": bool}}"""

def run_eval():
    passed = 0
    for case in GOLDEN:
        a = rag.ask(case["q"])
        rule_ok = all(m in a for m in case["must"])
        judged = json.loads(chat([{"role": "user", "content": JUDGE.format(a=a, **case)}],
                                 response_format={"type": "json_object"}, temperature=0))
        ok = rule_ok and judged["pass"]
        passed += ok
        print(f"{'PASS' if ok else 'FAIL'} rule={rule_ok} judge={judged['pass']} {case['q']} | {judged['critique']}")
    print(f"通过率 {passed}/{len(GOLDEN)}")

def recall_at_k(cases: list[dict], k: int = 4) -> float:
    hits = sum(any(c["gold_chunk"] in r for r in rag.retrieve(c["q"], k)) for c in cases)
    return hits / len(cases)

passk.py —— pass@k 与 pass^k(没实跑过)

python
# passk.py —— 同一任务跑 n 次,算 pass@k(至少一次成功)和 pass^k(k 次全成功)
from math import comb

def pass_at_k(n: int, c: int, k: int) -> float:
    """n 次试验里 c 次成功,随机抽 k 次至少一次成功的概率(无偏估计)"""
    if n - c < k:
        return 1.0
    return 1 - comb(n - c, k) / comb(n, k)

def pass_hat_k(n: int, c: int, k: int) -> float:
    """随机抽 k 次全部成功的概率"""
    return comb(c, k) / comb(n, k) if c >= k else 0.0

# 例:书签 agent 同一任务跑 10 次成功 7 次
print(pass_at_k(10, 7, 3), pass_hat_k(10, 7, 3))

抽取 + 校验 + 重试(没实跑过)

python
# 抽取的通用套路:JSON 模式 + pydantic 校验 + 把报错喂回去重试
import json
from pydantic import BaseModel, ValidationError
from llm import client, MODEL

class Invoice(BaseModel):
    vendor: str
    invoice_no: str
    date: str          # YYYY-MM-DD
    total: float
    currency: str = "CNY"

PROMPT = "从发票文本中抽取字段,只输出 JSON,字段:" + json.dumps(Invoice.model_json_schema()["properties"], ensure_ascii=False)

def extract(text: str, retries: int = 2) -> Invoice:
    msgs = [{"role": "system", "content": PROMPT}, {"role": "user", "content": text[:20000]}]
    for _ in range(retries + 1):
        out = client.chat.completions.create(model=MODEL, messages=msgs, temperature=0,
                response_format={"type": "json_object"}).choices[0].message.content
        try:
            return Invoice.model_validate_json(out)       # 永远校验
        except ValidationError as e:
            msgs += [{"role": "assistant", "content": out},
                     {"role": "user", "content": f"校验失败:{e},请修正后重新输出 JSON"}]
    raise ValueError("抽取失败,转人工")

lora.py —— TRL + PEFT 骨架(只过了语法检查;这次按 Unsloth 指南改了超参和 target,改完的版本也没实跑过)

python
# pip install "transformers>=4.45" peft trl datasets accelerate —— 要 GPU,先拿 0.5B 练手
# 超参按 Unsloth LoRA 指南的起点:LR 2e-4,1-3 epoch,r 16,alpha = r 或 2r,dropout 0,覆盖全部主要线性层
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer

# data.jsonl 每行:{"messages": [{"role":"user","content":"..."},{"role":"assistant","content":"..."}]}
ds = load_dataset("json", data_files="data.jsonl", split="train")

peft_config = LoraConfig(
    r=16, lora_alpha=32, lora_dropout=0.0,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    task_type="CAUSAL_LM",
)
args = SFTConfig(output_dir="qwen-lora", num_train_epochs=2,
                 per_device_train_batch_size=2, gradient_accumulation_steps=8,
                 learning_rate=2e-4, logging_steps=10, bf16=True,
                 assistant_only_loss=True)        # TRL 文档:对话数据只在 assistant 部分算 loss
trainer = SFTTrainer(model="Qwen/Qwen2.5-0.5B-Instruct", train_dataset=ds,
                     args=args, peft_config=peft_config)
trainer.train()
trainer.save_model("qwen-lora")    # 只存 adapter
# 不想写代码:LLaMA-Factory WebUI

digest.py —— 书签日报(没实跑过)

python
# digest.py —— 阿里云上 cron 跑;crontab:0 8 * * * cd /opt/digest && .venv/bin/python digest.py
import json, os, datetime, requests
from llm import chat

def fetch_new_bookmarks() -> list[dict]:
    # X API v2:GET /2/users/:id/bookmarks,需要 OAuth 2.0 用户令牌(bookmark.read)
    r = requests.get(f"https://api.x.com/2/users/{os.environ['X_USER_ID']}/bookmarks",
                     headers={"Authorization": f"Bearer {os.environ['X_USER_TOKEN']}"},
                     params={"max_results": 50, "tweet.fields": "created_at,author_id"}, timeout=30)
    r.raise_for_status()
    seen = set(json.load(open("seen.json"))) if os.path.exists("seen.json") else set()
    new = [t for t in r.json().get("data", []) if t["id"] not in seen]
    json.dump(sorted(seen | {t["id"] for t in new}), open("seen.json", "w"))   # 去重
    return new

def summarize(tweets: list[dict]) -> str:
    items = "\n".join(f"- [{t['id']}] {t['text']}" for t in tweets)
    return chat([{"role": "system", "content": "你是我的技术情报助理。"},
                 {"role": "user", "content": f"按主题分组总结这些书签,每组 2-3 句,保留 [id]:\n{items}"}])

def push(text: str):   # 飞书群机器人 webhook,URL 放环境变量
    requests.post(os.environ["FEISHU_WEBHOOK"], json={"msg_type": "text", "content": {"text": text}}, timeout=10)

if __name__ == "__main__":
    tweets = fetch_new_bookmarks()
    if tweets:
        push(f"{datetime.date.today()} 书签日报\n\n" + summarize(tweets))

决策规则

问题 先试 再考虑
知识过时 / 要引用来源 RAG + 更好切分 微调(知识会再过时)
格式/语气/工具调用习惯 少样本 + 结构化输出 小数据 LoRA(干净>量大)
不知道哪里坏 人工看 50 条做 error analysis 上评估平台/通用指标
要回归 20+ golden set + pass/fail 1–5 分量表(难校准)
非确定任务 pass@k / pass^k 多次采样 单次分数当真理
线上漂移 tracing(Langfuse/LangSmith)+ 抽样人工 只看 dashboard 漂亮曲线
LoRA 起点(Unsloth 指南) LR 2e-4;r=8/16;alpha≈r 或 2r;dropout 常 0 盲调满参;QLoRA 省显存

失败模式

现象 常见原因 我怎么处置
微调后更胡 噪声数据 / epoch 过多 砍数据保质量;早停;对照基线
评委和人对不上 量表模糊、评委未校准 改 pass/fail;先算一致率再自动化
指标好看产品烂 通用指标不对题 回 error analysis;按失败模式写用例
trace 看不懂 没记 messages/tool 原文 按 GenAI OTel 语义约定打全
cron 静默挂 无告警/无限速 失败告警;并发上限+退避

踩坑 / 注意

  • ❌ 坑:用微调解决知识问题——知识会过时,用 RAG。
  • ❌ 坑:训练数据质量差——100 条干净数据胜过 1 万条噪声。
  • ❌ 坑:epoch 开太多——模型背训练集,新任务反而变差。
  • ❌ 坑:一上来就搭评估平台、用通用指标——先人工看数据做 error analysis(Hamel 原话的意思:平台会引导你用通用指标,那往往适得其反)。
  • ❌ 坑:只信 LLM 评委——先用人工标签验证它,再配规则检查和人工抽查。
  • ❌ 坑:cron 任务没有失败告警;批量调用不限速——加并发上限和指数退避。
  • ❌ 注意:OpenObserve 是 AGPL-3.0,公司里用之前先确认许可证;“存储成本降 140 倍”是发帖人的说法。

Langfuse / promptfoo(raw-deep 07,没实跑过)

  • Langfuse tracing:pip 后用 get_client();span/generation 套住请求;或 from langfuse.openai import openai 自动埋点(Get started / tracing example)。自建看 Self-host Docker;对齐 OTel GenAI 语义约定方便以后换后端。
  • promptfoo 红队三步(官方 Red teaming):promptfoo redteam init → promptfoo redteam run(= generate + eval)→ promptfoo redteam report。配置里 Targets / Plugins / Strategies / Purpose;CI 可用 –tag key=value。
  • 红队测的是《安全》页的注入面;日常回归仍用 golden set + pass/fail,别用红队代替产品评估。
  • Ragas:Context Precision / Recall / Faithfulness —— 有检索 golden 后再接;指标定义见 raw-deep 02/07。

langfuse_span.py —— 最小观测骨架(没实跑过;API 摘自 Langfuse tracing example)

python

待试

  • [ ] 书签问答先人工看 50 条输出,做 open / axial coding,再写 20 条 golden set 跑基线
  • [ ] 评委从 1-5 分改成 pass/fail,拿 20 条人工标签算一下和评委的一致率
  • [ ] 书签 agent 同一任务跑 10 次,算 pass@3 和 pass^3
  • [ ] 本地起一个 Langfuse,把 llm.py 的调用接进去
  • [ ] 200 条“推文 → 结构化标签”数据 LoRA 微调 0.5B,和 API 抽取效果比

收藏

更多收藏

  • 评估工具:Ragas https://raw.githubusercontent.com/explodinggradients/ragas/main/README.md ;promptfoo https://raw.githubusercontent.com/promptfoo/promptfoo/main/README.md ;Arize Phoenix https://raw.githubusercontent.com/Arize-ai/phoenix/main/README.md ;Langfuse README https://raw.githubusercontent.com/langfuse/langfuse/main/README.md ;Langfuse overview https://langfuse.com/docs/observability/overview ;LangSmith evaluation concepts https://docs.langchain.com/langsmith/evaluation-concepts ;LangSmith observability quickstart https://docs.langchain.com/langsmith/observability-quickstart
  • @HamelHusain:https://x.com/HamelHusain/status/1904235864722755639 、先 error analysis 再写 evals https://x.com/HamelHusain/status/1928590683067265473 、FAQ https://x.com/HamelHusain/status/1938296705902117052 、https://x.com/HamelHusain/status/1956371273858314397 、验证评委 https://x.com/HamelHusain/status/2010782094256222323 、和 @sh_reya 讲自动化 evals https://x.com/HamelHusain/status/2074242605634949306 、https://x.com/HamelHusain/status/2099929381850468675 、Decision Models https://x.com/HamelHusain/status/2112588257104216294
  • 评委 / evals 其他:@omarsar0 https://x.com/omarsar0/status/2070942495832470001 、https://x.com/omarsar0/status/2071595490454434214 ;@aparnadhinak agent-as-a-judge https://x.com/aparnadhinak/status/2075688574960488558 ;@hwchase17 最好的 evals 都是定制数据集 https://x.com/hwchase17/status/1992642075150434548 ;@lennysan https://x.com/lennysan/status/1909636749103599729 、https://x.com/lennysan/status/1910124776104091676 ;@svpino https://x.com/svpino/status/1895833171134201881 、AgentOps https://x.com/svpino/status/1997305280271659227 ;@langfuse 全部功能 MIT 开源 https://x.com/langfuse/status/1930263974718673378
  • 微调:@sairahul1 小模型微调全流程 https://x.com/sairahul1/status/2100882424343265527 、https://x.com/sairahul1/status/2100919437146906699 ;@UnslothAI NVIDIA 的入门指南 https://x.com/UnslothAI/status/2003098731852488864 ;@akshay_pachaar https://x.com/akshay_pachaar/status/1898713056882127083 、https://x.com/akshay_pachaar/status/1979919605570408553 、Training-Free GRPO https://x.com/akshay_pachaar/status/2023463131901816918 、https://x.com/akshay_pachaar/status/2029212227438518406 、https://x.com/akshay_pachaar/status/2075579659878854709 、https://x.com/akshay_pachaar/status/1997946287556321359 、Gemma 库 https://x.com/akshay_pachaar/status/1903426646939718142 ;@_avichawla LLaMA-Factory https://x.com/_avichawla/status/1926164620324069843 、12 种技巧 https://x.com/_avichawla/status/2090732012005200135 ;@_philschmid FunctionGemma on TPU https://x.com/_philschmid/status/2020878523259293964 ;@GitHub_Daily https://x.com/GitHub_Daily/status/1942433460792054184 、https://x.com/GitHub_Daily/status/1966079270796800119
  • 旧草稿里的链接(raw 里没有):@rasbt 评估四类 https://x.com/rasbt/status/1974838408670261401 ;@wsl8297 cgft-llm https://x.com/wsl8297/status/2046876975235764716 、https://github.com/echonoshy/cgft-llm ;@AndrewYNg SGLang 短课 https://x.com/AndrewYNg/status/2042289428702642588 ;Unsloth 仓库 https://github.com/unslothai/unsloth