实战案例

三个由浅入深的例子:现成情感 Pipeline、无检索的小聊天、Trainer / LoRA 微调提纲。模型均为 ungated


案例 1:情感分析 Pipeline

目标: 对英文短评打正负向,适合接入评论审核原型。

from transformers import pipeline

sentiment = pipeline(
    "text-classification",
    model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
)

reviews = [
    "The pacing is perfect and the cast shines.",
    "I left the theater disappointed and tired.",
]
for text, pred in zip(reviews, sentiment(reviews)):
    print(f"{pred['label']:8} {pred['score']:.3f}  {text}")

验证: 换几句明显褒贬的话,确认 POSITIVE / NEGATIVE 与分数。中文评论请换 Qwen 分类检查点或自己用中文数据微调 DistilBERT 中文版(本例是英文 SST-2)。


案例 2:无 RAG 的小聊天(generate

目标: 多轮对话,不接向量库。有 GPU 用 Qwen;纯 CPU 可把 model_id 换成 distilbert/distilgpt2 并改为普通续写(无 chat template)。

from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "Qwen/Qwen2.5-0.5B-Instruct"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, device_map="auto", dtype="auto"
)
history = [{"role": "system", "content": "You are a brief, friendly tutor."}]

def ask(user: str) -> str:
    history.append({"role": "user", "content": user})
    prompt = tok.apply_chat_template(
        history, add_generation_prompt=True, return_tensors="pt"
    ).to(model.device)
    out = model.generate(
        prompt,
        max_new_tokens=96,
        do_sample=True,
        temperature=0.7,
        top_p=0.9,
    )
    text = tok.decode(out[0][prompt.shape[-1]:], skip_special_tokens=True)
    history.append({"role": "assistant", "content": text})
    return text

print(ask("什么是 Tokenizer?一句话。"))
print(ask("它和模型权重是什么关系?"))

这是无 RAG 聊天:知识只来自权重,会幻觉。要接文档请走本站 LangChain 或自建检索;只要稳定本地聊,用 Ollama 更省事。


案例 3:微调提纲(Trainer 或 LoRA)

路径 A — 分类(可在 CPU 上缩小数据):微调训练distilbert/distilbert-base-uncased + rotten_tomatoes 调用 trainer.train(),再 pipeline("text-classification", model=保存目录)

路径 B — 因果 LM + LoRA(建议 GPU):

  1. pip install peft
  2. 准备若干 {"messages": [...]} 或纯文本语料,mapinput_ids / labels
  3. LoraConfig(task_type=TaskType.CAUSAL_LM, r=8, target_modules=["q_proj", "v_proj"])
  4. get_peft_model 后交给 Trainerper_device_train_batch_size=1,必要时梯度累积
  5. push_to_hub 适配器,模型卡写明底座是 Qwen/Qwen2.5-0.5B-Instruct

显存: 全参微调 0.5B 都可能吃紧;7B 全参需要专业卡。OOM 时先降 batch、开 LoRA,而不是盲目换 Llama。


反模式

反模式改进
示例里用未授权的 Llama换 DistilBERT / DistilGPT2 / Qwen 0.5B
不设 max_new_tokens生成章已说明,必须显式写
Token 写进笔记本hf auth login 或 CI 的 HF_TOKEN
无 GPU 却训 7B用 Pipeline、Ollama,或很小的 Trainer 子集
不读模型卡就商用先看许可与局限

下一步

评论