用 Transformers 跑通分词、推理与微调
用可重现的 CPU 模型检查三类架构、任务输出、Trainer 和 LoRA,分开记录生产条件。
学完这一章,你能够
- 用可重现的 CPU 模型检查三类架构、任务输出、Trainer 和 LoRA,分开记录生产条件。
先区分库、模型文件和任务
Transformers 提供模型架构、预处理和训练推理接口。Hub 管理模型及数据集版本。Datasets 负责读取与变换数据,Tokenizers 构造词表和预处理,Evaluate 管理指标,Accelerate 协助设备与分布式运行,PEFT 管理适配器。部署时分别核对数据、模型和代码许可及版本。
文本任务包括分类、填空、实体识别、抽取式问答、续写、翻译和摘要。视觉任务可能是分类、检测、分割、深度估计、视频分类和关键点。通用图像生成还可使用扩散框架。音频任务要区分语音识别、音频分类和语音合成。图文问答、图像描述、文档问答、零样本分类分别有自己的模型及结果约定。
编码器、因果解码器和双组件模型
编码器用双向上下文建立隐藏表示,BERT 系列可加分类、实体或问答头。因果解码器逐个预测后续词元,GPT 类模型的前缀输出只依赖当前及之前的输入。编码器加解码器则先表示完整输入,再由解码器通过交叉注意力生成目标序列。
本站使用小型 BERT、GPT-2 和 T5 架构,权重在本机初始化。BERT 输出张量可用于遮罩池化和分类,GPT-2 的生成结果包含提示和新增词元,T5 结果从解码起始词元开始。业务质量取决于权重、任务与测试集,不能由张量形状推断。
固定版本后做离线实验
将依赖装到独立环境。本站实际版本是 Transformers 5.0.0、PyTorch 2.10.0、Tokenizers 0.22.2、PEFT 0.18.0 和 Accelerate 1.12.0。Python 环境和 CPU/GPU 支持应按选定版本核对。旧版资料中的 TensorFlow 和 Flax 安装路径要匹配当时的发行版。
在导入前设置 HF_HOME,按需单独设置 HF_HUB_CACHE。HF_HUB_OFFLINE=1 使 Hub 调用只用缓存,from_pretrained 也可指定 local_files_only=True 与已核对的本地目录。旧的 TRANSFORMERS_CACHE、TRANSFORMERS_OFFLINE 与第三方端点写法要按对应旧版本查阅。使用本地固定路径可明确实际加载的是哪套权重。
Pipeline 和手动推理如何对应
任务管道通常把预处理、模型前向和后处理串起来。分类输出标签和分数,填空返回候选替换,实体识别返回分组和字符位置,抽取式问答返回原上下文中的区间。零样本分类可将候选标签转成自然语言推断假设,要求模型具备相应训练能力。
本站分类管道与手动 softmax 的标签和分数相符,填空返回 3 项。实体位置、问答片段、零样本候选、批量分类和生成在独立样本中核对。文本生成设置 do_sample=False 时走确定性解码,采样温度和 top_p 需要启用采样。对话模板需匹配模型的角色和起始标记,解码时按输入长度切掉提示。
Transformers 5.0.0 的任务注册表保留文本生成和语音识别,旧的 translation、summarization 管道入口在本版本不可直接用。翻译或摘要可用任务匹配的编码器-解码器模型、分词器和 generate,再按各自的语料评估。ASR 要明确采样率、分段、重叠及时间戳单位,本机 CTC 样本与 Whisper 的分段方式须分别核验。
观察分词、截断和遮罩
BPE 以学习到的合并规则拆分子词,WordPiece 使用词表匹配子词并可标记词内后缀,SentencePiece 是实现框架,可训练 Unigram 或 BPE。先核对规范化、切分和词表,再添加特定任务的边界标记。词元 ID 是词表索引,attention_mask 表示模型需要区分的输入位置。
本机将 BRIGHT 和 sailing port 分成不同长度的输入。对齐后第一行 ID 为 2、5、3、0、0,遮罩末两项是 0。打开实例切换到截断,输入保留 bright port 与起止标记。下图来自实际浏览器,显示填充及遮罩。

AutoTokenizer 读取本地分词配置,AutoModel 选择基础模型,AutoModelForSequenceClassification 或 AutoModelForCausalLM 选相应任务头。基础模型的隐藏向量与分类 logits 含义不同。本站用遮罩做均值池化,批处理的首个结果与单条输入对齐。语义检索还要选择经过任务训练的模型。
用独立验证集训练和保存
准备训练和验证数据,先清理标签、去重并分组切分,训练批次按长度动态填充。使用 Trainer 前固定 seed、学习率、有效批量、梯度累积、预热、权重衰减与评估节奏。最佳检查点的评估与保存策略要对齐。避免把测试集用于选参。
本站用 4 条训练样本、2 条独立验证样本,在 CPU 上实际训练并检查最佳检查点。分类指标算例中,2 个真阳性和 1 个漏报得到准确率 2/3,F1 为 0.8。训练后用 safetensors 保存、从本地重载,核对同一输入的 logits。
Hub 发布需要账号授权、模型卡、依赖与许可。先核对仓库可见性和上传范围,凭据保存在安全位置。本站的实验目录和权重只在运行时临时生成。
把 LoRA、量化和加速分开比较
LoRA 以低秩更新适配某些层,基础矩阵保持冻结。秩、缩放和目标层要配合模型结构。本站给 BERT 的 query 和 value 加秩 2 适配器,实际反传后验证基础参数未动,并用原模型与独立适配器重建相同输出。
QLoRA 在量化的基础模型上训练适配器,位数、计算精度、量化后端与设备要共同匹配。NF4、双重量化、GPTQ、AWQ、半精度、FlashAttention、torch.compile、ONNX/TensorRT 和不同推理引擎分别选用并计时。吞吐、峰值内存、首词元耗时和任务质量都依赖硬件及负载。
排查显存不足时先量批量、长度和峰值占用。找不到模型时核对本地文件、权限、模型标识与版本。类别数变化意味着分类头需要重新初始化并训练。设备混用先定位实际张量位置。损失异常先检查标签、数值精度和学习率。分词较慢时分开测 Python 端、词表实现和批处理。
可按离线推理、带评估的微调、适配器与多模态、生产压测四步练习。后续部署、分布式训练、量化、对齐与发布各自保留一组可复查结果。
逐项运行小型本地模型
"""Run small original Transformer fixtures with no model downloads."""
from importlib.metadata import version
import os
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
os.environ["TRANSFORMERS_VERBOSITY"] = "error"
from tokenizers import Tokenizer
from tokenizers.decoders import WordPiece as WordPieceDecoder
from tokenizers.models import WordLevel, WordPiece
from tokenizers.normalizers import BertNormalizer
from tokenizers.pre_tokenizers import BertPreTokenizer, WhitespaceSplit
from tokenizers.processors import TemplateProcessing
import torch
from transformers import (
AutoModel, AutoModelForSequenceClassification, AutoTokenizer, BertConfig, BertForMaskedLM,
BertForSequenceClassification, GPT2Config, GPT2LMHeadModel, PreTrainedTokenizerFast,
T5Config, T5ForConditionalGeneration, pipeline,
)
from lab_tools import run_exercise
WORDS = ["[PAD]","[UNK]","[CLS]","[SEP]","[MASK]","bright","port","dark","ship","sail","##ing","and","water"]
VOCAB = {token:index for index,token in enumerate(WORDS)}
def encoder_tokenizer():
backend=Tokenizer(WordPiece(VOCAB,unk_token="[UNK]"))
backend.normalizer=BertNormalizer(lowercase=True)
backend.pre_tokenizer=BertPreTokenizer()
backend.post_processor=TemplateProcessing(single="[CLS] $A [SEP]",
pair="[CLS] $A [SEP] $B:1 [SEP]:1",special_tokens=[("[CLS]",2),("[SEP]",3)])
backend.decoder=WordPieceDecoder()
return PreTrainedTokenizerFast(tokenizer_object=backend,pad_token="[PAD]",unk_token="[UNK]",
cls_token="[CLS]",sep_token="[SEP]",mask_token="[MASK]",model_max_length=16)
def decoder_tokenizer():
backend=Tokenizer(WordLevel(VOCAB,unk_token="[UNK]"))
backend.pre_tokenizer=WhitespaceSplit()
template="{% for turn in messages %}{{ turn['content'] }} {% endfor %}{% if add_generation_prompt %}ship{% endif %}"
return PreTrainedTokenizerFast(tokenizer_object=backend,pad_token="[PAD]",unk_token="[UNK]",
model_max_length=16,chat_template=template)
def classifier_config():
return BertConfig(vocab_size=len(WORDS),hidden_size=16,num_hidden_layers=1,num_attention_heads=2,
intermediate_size=24,max_position_embeddings=24,pad_token_id=0,
id2label={0:"CALM",1:"ALERT"},label2id={"CALM":0,"ALERT":1})
def masked_mean(hidden,attention_mask):
weights=attention_mask.unsqueeze(-1)
return (hidden*weights).sum(1)/weights.sum(1).clamp(min=1)
def exercise(checks, workspace):
torch.set_num_threads(1)
torch.manual_seed(43)
expect=checks.expect
names=["transformers","torch","tokenizers","huggingface-hub"]
expect("hf_versions",names,"Inspect the installed offline CPU runtime",
["5.0.0","2.10.0","0.22.2","1.33.0"],[version(name) for name in names])
tokenizer=encoder_tokenizer()
batch=tokenizer(["BRIGHT","sailing port"],padding=True,return_tensors="pt")
expect("hf_tokenizer_batch",["BRIGHT","sailing port"],"Normalize, split WordPiece, add boundaries and mask padding",
[[[2,5,3,0,0],[2,9,10,6,3]],[[1,1,1,0,0],[1,1,1,1,1]]],
[batch.input_ids.tolist(),batch.attention_mask.tolist()])
shortened=tokenizer("bright port dark ship sailing",truncation=True,max_length=4,return_tensors="pt")
expect("hf_tokenizer_truncate","bright port dark ship sailing","Truncate to four tokens including boundaries and decode",
[[2,5,6,3],"bright port"],[shortened.input_ids[0].tolist(),tokenizer.decode(shortened.input_ids[0],skip_special_tokens=True)])
local=workspace/"classifier"
original=BertForSequenceClassification(classifier_config()).eval()
original.save_pretrained(local)
tokenizer.save_pretrained(local)
tok=AutoTokenizer.from_pretrained(local,local_files_only=True,trust_remote_code=False)
model=AutoModelForSequenceClassification.from_pretrained(local,local_files_only=True,trust_remote_code=False).eval()
base=AutoModel.from_pretrained(local,local_files_only=True,trust_remote_code=False).eval()
expect("hf_auto_local","local classifier","Save and reload tokenizer, task head and encoder base",
["BertForSequenceClassification","BertModel",True],
[type(model).__name__,type(base).__name__,tok("bright").input_ids==tokenizer("bright").input_ids])
with torch.inference_mode():
logits=model(**batch).logits
hidden=base(**batch).last_hidden_state
one=tok("bright",return_tensors="pt")
solo=masked_mean(base(**one).last_hidden_state,one.attention_mask)[0]
pooled=masked_mean(hidden,batch.attention_mask)
reference=model(**tok("bright port",return_tensors="pt")).logits.softmax(dim=-1)[0]
expect("hf_manual_and_pool","fixed input and pad masks","Compare output shape, normalized probabilities and masked mean against single input",
[[2,2],[2,5,16],[2,16],True,True],
[list(logits.shape),list(hidden.shape),list(pooled.shape),
torch.allclose(pooled[0],solo,atol=1e-6),torch.allclose(logits.softmax(dim=-1).sum(-1),torch.ones(2))])
classifier=pipeline("text-classification",model=model,tokenizer=tok,device=-1)
output=classifier("bright port")[0]
chosen=int(reference.argmax())
expect("hf_classifier_pipeline","bright port","Compare real Pipeline label and score against manual logits",
[model.config.id2label[chosen],True],[output["label"],abs(output["score"]-float(reference[chosen]))<1e-6])
fill=pipeline("fill-mask",model=BertForMaskedLM(classifier_config()).eval(),tokenizer=tok,device=-1,top_k=3)
guesses=fill("bright [MASK]")
expect("hf_fill_mask","bright [MASK]","Run the masked-LM head and inspect candidate scores and replacement",
[3,True,True],[len(guesses),all(0<=row["score"]<=1 for row in guesses),all("[MASK]" not in row["sequence"] for row in guesses)])
causal_tokenizer=decoder_tokenizer()
gpt=GPT2LMHeadModel(GPT2Config(vocab_size=len(WORDS),n_positions=24,n_embd=16,n_layer=1,n_head=2,
pad_token_id=0,bos_token_id=2,eos_token_id=None)).eval()
prompt=causal_tokenizer.apply_chat_template([{"role":"user","content":"bright port"}],
tokenize=False,add_generation_prompt=True)
inputs=causal_tokenizer(prompt,return_tensors="pt")
with torch.inference_mode():
result=gpt.generate(**inputs,max_new_tokens=3,do_sample=False)
start=inputs.input_ids.shape[1]
expect("hf_causal_generate","bright port","Render a fixed chat template, run greedy generation and slice off the prompt",
["bright port ship",[1,6],True,3],
[prompt,list(result.shape),torch.equal(result[:,:start],inputs.input_ids),len(result[0,start:])])
t5=T5ForConditionalGeneration(T5Config(vocab_size=len(WORDS),d_model=16,d_kv=8,d_ff=32,
num_layers=1,num_decoder_layers=1,num_heads=2,decoder_start_token_id=0,pad_token_id=0,eos_token_id=None)).eval()
t5_input=tok("bright port",return_tensors="pt")
with torch.inference_mode():
t5_result=t5.generate(input_ids=t5_input.input_ids,attention_mask=t5_input.attention_mask,
max_new_tokens=2,do_sample=False)
expect("hf_seq2seq","bright port","Run the separate encoder and decoder, check decoder-start plus two generated tokens",
[[1,3],0],[list(t5_result.shape),int(t5_result[0,0])])
if __name__ == "__main__":
run_exercise(exercise)
- 同一批输入能从词元 ID 和遮罩追踪到 logits。因果模型保留提示前缀,训练和适配器可重载验证。
所需环境:CPython 3.12.14,Transformers 5.0.0、Torch 2.10.0、PEFT 0.18.0、Accelerate 1.12.0,离线 CPU。
当前源码 SHA256:fe210f6af5c3963534442b8a4a3489139a54dccc4ef50ca93087e33777b16bbe
运行本地实例
ZIP 内含三个独立程序、固定依赖清单与分词交互页。
所需环境:CPython 3.12.14,Transformers 5.0.0、Torch 2.10.0、PEFT 0.18.0、Accelerate 1.12.0,离线 CPU。
ZIP SHA256:97563107c4fdafea5089eb4c497891f18143efdf18da96173d2c04ca9133c37c
常见错误与边界
- 先检查加载的具体模型头和版本。
- 避免用随机初始化模型衡量实际翻译、摘要或识别质量。
练习与解答
运行 CPU 练习并切换分词观察页的两个状态。
展开参考解答
填充时遮罩尾部出现两个 0,截断后保留起止标记和两个普通词元。