Chapter 07

推理与测试

训练完得验货。用 for_inference 开启 2x 推理加速,调好生成参数,流式输出,并对比微调前后。

7.1 开启推理模式

训练态和推理态的最优内核不同。Unsloth 提供 for_inference 切换到原生 2x 加速的推理路径:

from unsloth import FastLanguageModel

FastLanguageModel.for_inference(model)   # 启用 2x 快速推理

messages = [{"role": "user", "content": "用一句话解释什么是微调"}]
inputs = tokenizer.apply_chat_template(
    messages,
    tokenize = True,
    add_generation_prompt = True,   # 关键:让模型接着生成回答
    return_tensors = "pt",
).to("cuda")

out = model.generate(input_ids=inputs, max_new_tokens=128,
                     temperature=0.7, top_p=0.9)
print(tokenizer.decode(out[0], skip_special_tokens=True))

7.2 生成参数名词解释

max_new_tokens
最多生成多少新 token。控制回答长度,设太小会被截断。
temperature(温度)
随机性。越高越发散有创意、越低越确定保守。事实问答用 0.1-0.3,创作用 0.7-1.0。
top_p(核采样)
只在累计概率前 p 的候选里采样。常用 0.9,与 temperature 配合控制多样性。
top_k
只在概率最高的 k 个候选里采样。与 top_p 二选一或同用。
do_sample
是否随机采样。False 则贪心/beam 搜索,输出确定;True 才让 temperature/top_p 生效。
repetition_penalty(重复惩罚)
>1 时惩罚已出现的 token,缓解复读。常用 1.1 左右。
add_generation_prompt
推理时设 True,在提示末尾加上 assistant 起始标记,让模型知道该轮到它说话。
skip_special_tokens
解码时是否隐藏 <|im_start|> 等特殊 token,展示给用户时设 True

7.3 流式输出(streaming)

像 ChatGPT 那样逐字吐出,用 TextStreamer

from transformers import TextStreamer

streamer = TextStreamer(tokenizer, skip_prompt=True,
                        skip_special_tokens=True)

_ = model.generate(
    input_ids = inputs,
    streamer = streamer,       # 边生成边打印
    max_new_tokens = 256,
    temperature = 0.7,
    top_p = 0.9,
)

7.4 对比微调前后

验证微调是否真的有用,最直接的方式是拿同一个问题,分别用基础模型和微调后模型回答对比。写个小工具函数:

def ask(model, question, max_new_tokens=200):
    FastLanguageModel.for_inference(model)
    msgs = [{"role": "user", "content": question}]
    ids = tokenizer.apply_chat_template(
        msgs, tokenize=True, add_generation_prompt=True,
        return_tensors="pt").to("cuda")
    out = model.generate(input_ids=ids, max_new_tokens=max_new_tokens,
                         temperature=0.3, do_sample=True)
    return tokenizer.decode(out[0][ids.shape[-1]:], skip_special_tokens=True)

q = "我的订单还没发货,怎么办?"
print("微调后:", ask(model, q))
# 微调后应更贴合你的客服话术与业务口径
评测别只靠"感觉"

准备一份固定的测试问题集(20-50 条),微调前后各跑一遍并肩对比,甚至用更强的模型打分。这样才能量化"到底变好了没",而不是被个别好例子迷惑。

推理效果差的排查

① 推理用的 chat template 是否和训练时一致;② 是否忘了 add_generation_prompt=True;③ temperature 是否过高导致胡言乱语;④ 训练是否欠拟合(loss 没降下来)。

7.5 小结与下一步