Transformers
Hugging Face 的预训练模型工具库,用于文本分类、生成等任务。本页使用 PyTorch 后端。
安装与导入
python -m pip install transformers torch
首次加载模型通常需要联网下载权重。下面分类示例使用英文模型;处理中文时需要换成对应语言、任务的模型。
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
MODEL_ID = "distilbert/distilbert-base-uncased-finetuned-sst-2-english"
各小节共用以上导入和模型名;保存、批处理小节接前面的手动推理示例。
常用用法
Pipeline:快速完成一个任务
classifier = pipeline("text-classification", model=MODEL_ID, device=-1)
results = classifier(["The example is useful.", "This is disappointing."])
for item in results:
print(item["label"], round(item["score"], 3))
pipeline 封装预处理、模型推理和后处理。本例固定使用 CPU;任务名、模型和输入格式要相匹配。见Pipeline 教程。
分词:文本变成张量
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
batch = tokenizer(
["A short note.", "A slightly longer learning note."],
padding=True,
truncation=True,
max_length=128,
return_tensors="pt",
)
print(batch["input_ids"].shape)
print(batch["attention_mask"].shape)
padding 补齐长度,truncation 截断超长文本,attention_mask 标记有效 token;详见补齐与截断。
手动推理:控制输入与输出
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID).to(device)
inputs = tokenizer("This explanation is clear.", return_tensors="pt").to(device)
model.eval()
with torch.inference_mode():
logits = model(**inputs).logits
probabilities = logits.softmax(dim=-1)
label_id = probabilities.argmax(dim=-1).item()
print(model.config.id2label[label_id])
AutoModelForSequenceClassification 带分类头;AutoModel 通常只返回基础模型的特征,不能直接替代分类模型。
文本生成与聊天输入
生成任务换用独立的指令模型,不使用上面的分类权重。
generator = pipeline(
"text-generation",
model="HuggingFaceTB/SmolLM2-135M-Instruct",
device=-1,
)
messages = [{"role": "user", "content": "Explain a Python list in one sentence."}]
output = generator(messages, max_new_tokens=48, do_sample=False)
print(output[0]["generated_text"][-1]["content"])
这里由 pipeline 应用模型的聊天模板。max_new_tokens 限制新生成的长度;小模型适合跑通流程,回答质量有限。见聊天模板。
保存到本地与再次加载
接手动分类推理示例:
model.save_pretrained("./sentiment-model")
tokenizer.save_pretrained("./sentiment-model")
local_tokenizer = AutoTokenizer.from_pretrained("./sentiment-model", local_files_only=True)
local_model = AutoModelForSequenceClassification.from_pretrained(
"./sentiment-model", local_files_only=True,
)
模型和 tokenizer 一起保存,避免只复制权重却丢失词表或配置。见模型加载与保存接口。
进阶与不常用用法
批量推理
接前面的 model、tokenizer 和 device,一次处理多条文本:
texts = ["A helpful guide.", "The result is confusing.", "A clear example."]
batch_size = 2
model.eval()
with torch.inference_mode():
for start in range(0, len(texts), batch_size):
batch = tokenizer(
texts[start:start + batch_size], padding=True,
truncation=True, max_length=128, return_tensors="pt",
).to(device)
ids = model(**batch).logits.argmax(dim=-1).cpu().tolist()
print([model.config.id2label[i] for i in ids])
文本长度接近时一起分批,可减少 padding;batch 并非越大越好。
自动分配模型设备
安装 accelerate 后,可让加载器根据可用内存分配权重:
python -m pip install accelerate
distributed_model = AutoModelForSequenceClassification.from_pretrained(
MODEL_ID, device_map="auto",
)
print(distributed_model.hf_device_map)
device_map="auto" 面向推理加载,不是分布式训练配置;通常不要再对这个模型整体调用 .to(...)。见大模型推理。
易错点
- 模型、tokenizer 尽量来自同一仓库和修订版本。
- 分类模型不能直接拿来续写文本,生成任务需要相应的生成模型。
- padding 不等于 truncation;批处理时两者通常都要考虑。
- API 随版本演进,记录
transformers.__version__和模型修订版本更方便复现。