快速上手

本章用 Pipeline 在本机跑通第一次推理。Pipeline 会自动下载 Tokenizer 与权重并缓存。示例全部 ungated


情感分类(推荐第一段代码)

distilbert/distilbert-base-uncased-finetuned-sst-2-english 是 SST-2 上微调过的 DistilBERT,也是官方文档常用的分类示例:

from transformers import pipeline

clf = pipeline(
    "text-classification",
    model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
)
print(clf("This movie was a delight from start to finish."))
print(clf("I would not recommend this film to anyone."))

典型输出:

[{'label': 'POSITIVE', 'score': 0.99...}]
[{'label': 'NEGATIVE', 'score': 0.99...}]

发生了什么:

  1. from_pretrained 拉取 config.json、词表、model.safetensors
  2. 文本被 Tokenizer 变成 input_ids / attention_mask
  3. 模型输出 logits,Pipeline 做 softmax 并映射标签

要自己微调同一架构,请用底座 distilbert/distilbert-base-uncased + rotten_tomatoes,见 微调训练


文本生成(小模型)

CPU 友好的续写用 DistilGPT2;需要指令对话或中文时换 Qwen:

from transformers import pipeline

gen = pipeline(
    "text-generation",
    model="distilbert/distilgpt2",
    max_new_tokens=40,
)
print(gen("In a distant future, robots and humans")[0]["generated_text"])

指令模型(体积约 0.5B,有 GPU 更顺畅):

chat = pipeline(
    "text-generation",
    model="Qwen/Qwen2.5-0.5B-Instruct",
    device_map="auto",
    dtype="auto",
    max_new_tokens=64,
)
print(chat("用一句话解释什么是注意力机制。")[0]["generated_text"])

国内读者还可在 Hub 搜索 QwenDeepSeek 的 Instruct 检查点,同样注意是否门控与显存。


显式设备

有 NVIDIA GPU 时,Pipeline 可指定 device=0。跨设备自动分流用底层 API:

from transformers import AutoModelForCausalLM, AutoTokenizer

tok = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
model = AutoModelForCausalLM.from_pretrained(
    "distilbert/distilgpt2",
    device_map="auto",
    dtype="auto",
)

只想聊天、不想管权重格式时,用本站 Ollama;要把生成参数摸清楚,继续读 文本生成


第一次下载要等多久?

DistilBERT / DistilGPT2 大约几十到一百多 MB,Whisper-tiny 约 150MB,Qwen2.5-0.5B 约 1GB。进度条走完后,文件在 HF_HOME 缓存里,再跑同一脚本几乎是秒开。


第一个任务清单

  1. 建 venv,安装 torchtransformers datasets evaluate accelerate
  2. 运行上面的分类 Pipeline
  3. 再跑 DistilGPT2 生成,观察 max_new_tokens
  4. (可选)hf auth login,为上传做准备
  5. 打开 Hub 扫一眼模型卡

下一步

评论