关于 alterlab-transformers
alterlab-transformers 是针对 Hugging Face Transformers v5 的开发技能,适用于使用预训练模型进行推理、生成和微调的开发者。内容涵盖常见任务及 v4 代码迁移要点。
主要功能
- 01通过 pipeline 执行多任务推理
- 02加载并管理预训练模型
- 03控制文本生成与解码
- 04使用 Trainer 微调模型
- 05处理分词与聊天模板
适用场景
- 01运行文本、图像或音频推理
- 02配置模型加载与量化
- 03微调自定义标注数据集
- 04将 Transformers v4 代码迁移至 v5
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ alterlab-ieu/ alterlab-academic-skills --skill alterlab-transformers安装后在 Claude Code 中输入/alterlab-transformers确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
evals/evals.jsonreferences/generation.mdmodels.mdpipelines.mdtokenizers.mdtraining.md详细介绍
Transformers
概述
Hugging Face Transformers 可从 Hub 加载用于 NLP、视觉、音频和多模态任务的预训练检查点,通过 pipeline() 或 Auto* 类运行推理,并使用 Trainer 进行微调。此技能针对 transformers v5(≥ 5.0;截至 2026-09 的当前版本为 5.17.0)。v5 仅支持 PyTorch,且更改了多种 v4 编码习惯;重用论文、博客或模型卡中的旧代码片段前,请先查看下文的“会导致 v4 代码失效的 v5 变更”。
何时使用此技能
当用户想要执行以下操作时,使用此技能:
- 通过
pipeline()使用 Hub 检查点快速运行推理——文本分类、NER、零样本分类、使用聊天模型进行文本生成、语音识别、图像分类/检测,或使用 VLM 进行图像文本转文本。 - 加载模型及其分词器/处理器,并明确指定
dtype、device_map、attention 后端或 4/8 位量化。 - 控制
model.generate()中的解码方式(贪心搜索、采样、束搜索、流式传输、聊天模板)。 - 使用
Trainer在自定义标注数据集上微调编码器或解码器,也可选择通过peft使用 LoRA。 - 将 v4 时代的代码(
torch_dtype=、load_in_8bit=、已移除的 pipelines、TF/Flax 模型)迁移到 v5。
不适用的情况
| 场景 | 请改用 |
|---|---|
| 对表格特征进行传统机器学习(随机森林、预处理工作流、CV 网格搜索) | alterlab-scikit-learn |
| 使用 LightningModule 设计自定义 PyTorch 架构的训练循环、多 GPU 策略和检查点 | alterlab-pytorch-lightning |
| 将主题模型、嵌入或文本分类器用于社会科学测量设计(效度、BERTopic、词典) | alterlab-text-as-data |
| 蛋白质语言模型(ESM3 / ESM C 嵌入、蛋白质设计) | alterlab-esm |
| 使用预训练基础模型进行零样本时间序列预测 | alterlab-timesfm |
安装
uv pip install "transformers>=5" torch accelerate datasets
- 视觉:添加
pillow和torchvision(默认的图像处理器后端;仅 timm 支持的模型需要timm)。 - 音频:添加
librosa soundfile。 - LoRA / 量化:
peft、bitsandbytes(CUDA)。评估指标:evaluate或直接使用 scikit-learn 指标。
身份验证
受限或私有模型需要 Hub 令牌。可以登录一次:
from huggingface_hub import login
login() # or run `hf auth login` in a shell (huggingface-cli is deprecated)
也可以导出 Hub 客户端读取的变量:
export HF_TOKEN="your_token_here"
令牌:https://huggingface.co/settings/tokens。需要显式传递令牌时,请使用 token=(而非已移除的 use_auth_token=)。
快速入门
from transformers import pipeline
# Text generation with a small open chat model (CPU-friendly; add device_map="auto" on GPU)
generator = pipeline("text-generation", model="Qwen/Qwen3-0.6B")
messages = [{"role": "user", "content": "Explain p-hacking in two sentences."}]
out = generator(
messages,
max_new_tokens=128,
tokenizer_encode_kwargs={"enable_thinking": False}, # Qwen3 chat-template switch; omit for other models
)
print(out[0]["generated_text"][-1]["content"])
# Text classification — pin the checkpoint; task defaults change between releases
classifier = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
classifier(["This movie was excellent!", "Terrible pacing."])
# Zero-shot classification
zero_shot = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
zero_shot("The grant covers two postdoc salaries.", candidate_labels=["funding", "teaching", "ethics"])
使用 max_new_tokens(要生成的令牌数量),而不是 max_length(提示词 + 输出;在文本生成 pipeline 中,它还会影响分词器截断)。v5 不再提供专用的摘要、翻译和问答 pipelines——像上面那样向聊天模型提供提示词即可。
会破坏 v4 代码的 v5 变更
| v4 惯用写法 | v5 替代方案 |
|---|---|
torch_dtype=torch.float16 | dtype=torch.float16(torch_dtype 仅会发出警告)。默认值现在是 dtype="auto"——使用检查点的 dtype,通常为 bf16——而不是 float32 |
TFAutoModel… / FlaxAutoModel…、framework="tf"、return_tensors="tf" | 已移除;仅支持 PyTorch(return_tensors 接受 "pt"、"np"、"mlx") |
load_in_8bit=True / load_in_4bit=True | quantization_config=BitsAndBytesConfig(...) |
pipeline("summarization" / "translation_xx_to_yy" / "text2text-generation" / "question-answering") | 已移除——使用聊天模型和指令提示词调用 pipeline("text-generation") |
pipeline("image-to-text" / "visual-question-answering") | 搭配 VLM 使用 pipeline("image-text-to-text"),例如 Qwen/Qwen3-VL-2B-Instruct |
AutoModelForVision2Seq、AutoModelWithLMHead | AutoModelForImageTextToText;AutoModelForCausalLM / AutoModelForMaskedLM / AutoModelForSeq2SeqLM |
apply_chat_template(..., tokenize=True) 返回 ID 张量 | 返回 BatchEncoding(input_ids、attention_mask)→ model.generate(**inputs) |
慢速与快速分词器、use_fast= | 每个模型在 🤗 tokenizers 后端上只有一个分词器;AutoTokenizer 会忽略 use_fast |
batch_decode、encode_plus、additional_special_tokens | decode 可处理批次,tokenizer(...)、extra_special_tokens(为保持向后兼容,旧名称仍可用) |
penalty_alpha(对比搜索)、force_words_ids / constraints、分组束搜索、DoLa | 已迁移至 Hub 上的 custom_generate 仓库——例如 custom_generate="transformers-community/contrastive-search", trust_remote_code=True |
TrainingArguments(logging_dir=..., warmup_ratio=...) | 两者都已移除:设置 TENSORBOARD_LOGGING_DIR 环境变量;使用 warmup_steps=0.1(小于 1 的浮点数表示比例) |
Trainer(tokenizer=...) | Trainer(processing_class=...);report_to 现在默认值为 "none" |
save_pretrained(safe_serialization=False)、use_auth_token= | 始终使用 safetensors;使用 token= |
TRANSFORMERS_CACHE、low_cpu_mem_usage=True | HF_HOME / HF_HUB_CACHE;始终启用低内存加载(该标志会被忽略) |
来源:官方 v5 迁移指南,并对照 5.17.0 版本发布内容核验。
核心功能
1. 用于快速推理的管道
一次调用即可完成文本分类、NER、零样本分类、填充掩码、文本生成、ASR、音频分类、图像分类/分割、目标检测、深度估计和图文到文本任务的分词、前向传播及后处理。适用于原型开发和无需自定义预处理的批量推理。参见 references/pipelines.md。
2. 模型加载与管理
使用 from_pretrained 加载模型,支持 dtype、device_map、attn_implementation(默认使用 SDPA)和 quantization_config;还提供保存、上传至 Hub 和 ONNX 导出选项。参见 references/models.md。
3. 文本生成
generate() 支持贪心搜索、采样(temperature/top-k/top-p)和束搜索;支持聊天模板、流式传输和静态缓存。参见 references/generation.md。
4. 训练与微调
Trainer + TrainingArguments 支持混合精度、梯度累积/检查点、回调、超参数搜索,以及通过 peft 使用 LoRA。参见 references/training.md。
5. 分词
支持填充、截断、特殊词元、偏移量和聊天模板。参见 references/tokenizers.md。
常见模式
模式 1:简单推理
pipe = pipeline("task-name", model="org/model-id")
output = pipe(input_data)
模式 2:显式指定模型和分词器(聊天模型)
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "Qwen/Qwen3-0.6B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="auto", device_map="auto")
messages = [{"role": "user", "content": "State the central limit theorem in one sentence."}]
inputs = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt",
enable_thinking=False, # Qwen3-specific template variable
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=128)
new_tokens = outputs[0, inputs["input_ids"].shape[1]:]
print(tokenizer.decode(new_tokens, skip_special_tokens=True))
模式 3:微调分类器
from datasets import load_dataset
from transformers import (AutoModelForSequenceClassification, AutoTokenizer,
DataCollatorWithPadding, Trainer, TrainingArguments)
model_id = "google-bert/bert-base-uncased" # or answerdotai/ModernBERT-base
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSequenceClassification.from_pretrained(model_id, num_labels=5)
ds = load_dataset("Yelp/yelp_review_full")
ds = ds.map(lambda b: tokenizer(b["text"], truncation=True), batched=True)
args = TrainingArguments(
output_dir="./results",
num_train_epochs=3,
per_device_train_batch_size=16,
eval_strategy="epoch",
warmup_steps=0.1, # ratio of total steps
report_to="tensorboard", # default is "none" in v5
)
trainer = Trainer(
model=model,
args=args,
train_dataset=ds["train"],
eval_dataset=ds["test"],
processing_class=tokenizer,
data_collator=DataCollatorWithPadding(tokenizer),
)
trainer.train()
实用说明
- 在研究代码中固定模型 ID(最好也固定
revision=):管道默认值和 Hub 仓库会发生变化,导致结果在不知不觉中改变。 - 如果论文中出现生成文本或微调指标,请报告确切的检查点、transformers 版本、解码参数和随机种子(
transformers.set_seed)。 - 重新分发权重或输出之前,请检查模型卡中的许可证和访问限制条款。
参考文档
references/pipelines.md— 支持的 v5 任务、参数、批处理和已移除的管道references/models.md— 加载、dtype/device/attention/quantization、保存和导出references/generation.md— 解码策略、聊天模板、流式传输和缓存references/training.md—Trainer工作流、TrainingArguments、PEFT 和调优references/tokenizers.md— 分词、特殊 token 和聊天模板
属于 AlterLab Academic Skills 套件的一部分。