用途
Transformers 是 Hugging Face 推出的机器学习库,面向 PyTorch、TensorFlow 和 JAX,提供数千个预训练模型,覆盖自然语言处理、科学序列分析、化学性质预测、计算机视觉、时间序列预测、大语言模型微调以及多模态任务。其目标是让研究人员复用模型而非从头训练,从而降低计算成本与碳排放。
主要能力
- 预训练模型下载、推理与训练的统一 API。
- Auto 类(AutoModel、AutoTokenizer)可根据模型名称或路径自动推断正确架构,提高代码可移植性。
- Tokenizer 负责将数据转换为数值 token,支持 padding、truncation 及特殊 token(如 [CLS]、[SEP])。
- pipeline 将 tokenization、模型执行和后处理封装为单次 pipe(data) 调用,是最简单的使用方式。
- Trainer API 提供简化的训练循环,配合 TrainingArguments 配置训练参数。
- 支持 PEFT(参数高效微调)以及 bitsandbytes 量化,可在消费级 GPU 上运行大模型(8-bit 或 4-bit)。
- 支持 GPU 加速,可在 pipeline 中设置 device=0(CUDA)或 device="mps"(Mac)。
- 支持“Fast” tokenizer(Rust 编写,通常为默认选项),提升 tokenization 速度。
使用方式
安装命令:
pip install transformers datasets tokenizers
# Requires a backend (PyTorch or JAX)
pip install torch
常用导入:
from transformers import pipeline, AutoModel, AutoTokenizer, TrainingArguments, Trainer
import torch
基础使用模式(预训练 pipeline):
from transformers import pipeline
# 1. Initialize a pipeline (automatically downloads model)
classifier = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
# 2. Run inference
results = classifier("The molecular structure of this compound is fascinating.")
print(results)
批量编码示例:
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
texts = ["Science is cool.", "Quantum physics is hard."]
# Batch encoding
inputs = tokenizer(
texts,
padding=True,
truncation=True,
max_length=128,
return_tensors="pt" # Returns PyTorch tensors
)
print(inputs['input_ids'].shape) # (batch_size, seq_len)
Trainer API 示例:
from transformers import TrainingArguments, Trainer
training_args = TrainingArguments(
output_dir="./results",
num_train_epochs=3,
per_device_train_batch_size=16,
evaluation_strategy="epoch",
logging_dir="./logs",
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_train,
eval_dataset=tokenized_val,
)
# trainer.train()
科学应用示例:
- 蛋白质序列分析(ESM):
# ESM-2 is a powerful protein language model
tokenizer = AutoTokenizer.from_pretrained("facebook/esm2_t6_8M_UR50D")
model = AutoModel.from_pretrained("facebook/esm2_t6_8M_UR50D")
protein_seq = "MAPLRKTYLLG"
inputs = tokenizer(protein_seq, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
# The 'last_hidden_state' represents a "feature vector" for each amino acid
embeddings = outputs.last_hidden_state
- 化学性质预测(SMILES):
# Using a model trained on molecular strings
pipe = pipeline("text-classification", model="seyonec/ChemBERTa-zinc-base-v1")
smiles = "CC(=O)Oc1ccccc1C(=O)O" # Aspirin
result = pipe(smiles)
print(f"Prediction: {result}")
- 论文命名实体识别(NER):
# Extracting genes, proteins, or chemicals from text
ner_pipe = pipeline("ner", model="dslim/bert-base-NER")
text = "The expression of the BRCA1 gene was observed in the sample."
entities = ner_pipe(text)
量化与 GPU 使用:
from transformers import BitsAndBytesConfig
# Load model in 4-bit precision
quant_config = BitsAndBytesConfig(load_in_4bit=True)
model = AutoModel.from_pretrained("model_name", quantization_config=quant_config)
# 'device=0' targets the first CUDA device
pipe = pipeline("translation_en_to_fr", model="t5-base", device=0)
关键规则
建议(DO):
- 始终优先使用 AutoTokenizer.from_pretrained() 和 AutoModel.from_pretrained() 以获得灵活性。
- 在 pipeline 中显式设置 device=0(CUDA)或 device="mps"(Mac)以确保 GPU 加速。
- 模型较大,使用 HF_HOME 环境变量管理模型在磁盘上的存储位置。
- 大多数模型有最大序列长度(通常 512),在 tokenizer 中始终使用 truncation=True。
- 训练时使用 datasets 库处理数据加载和流式传输,避免占满内存。
- 微调时始终将 tokenizer 与模型一起保存,确保一致性。
避免(DON'T):
- 不要在循环中加载模型;加载模型需要数秒和数 GB 内存,应加载一次并重复使用。
- 谨慎上传私有数据(transformers 主要为本地执行)。
- 批处理时确保 padding=True,使批次内所有序列长度一致。
- 不要为任务使用错误的模型:BERT 用于理解,GPT 用于生成。
反模式(NEVER):
from transformers import AutoModel, AutoTokenizer
# ❌ BAD: Re-initializing the model inside a function called frequently
def get_prediction(text):
model = AutoModel.from_pretrained("bert-base-uncased") # ❌ SLOW & RAM HEAVY
return model(text)
# ✅ GOOD: Load once globally or in a class
model = AutoModel.from_pretrained("bert-base-uncased")
def get_prediction(text):
return model(text)
# ❌ BAD: Manual string splitting for "tokens"
# tokens = text.split(" ") # ❌ Not compatible with model vocabulary
# ✅ GOOD: Use the model's specific tokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
inputs = tokenizer(text, return_tensors="pt")
# ❌ BAD: Forgetting to move model to GPU
# model = AutoModel.from_pretrained("...")
# output = model(inputs.to("cuda")) # ❌ Error: Model is on CPU!
适用场景
- 自然语言处理:摘要、翻译、命名实体识别。
- 科学序列分析:蛋白质折叠、DNA/RNA 序列建模。
- 化学性质预测:使用 SMILES 等分子字符串。
- 计算机视觉:Vision Transformers(ViT)、图像分类。
- 时间序列预测:使用基础模型。
- 大语言模型微调:面向特定领域科学文献。
- 多模态任务:文档 AI、视觉问答。
常见问题与限制
GPU 内存不足(OOM):
- 降低 per_device_train_batch_size。
- 使用 gradient_accumulation_steps 保持有效批次大小。
- 在 TrainingArguments 中使用 fp16=True。
模型输出为字典而非张量:建议按名称访问,如 outputs.last_hidden_state。
Tokenization 缓慢:使用“Fast” tokenizer(通常为默认),可显式设置 use_fast=True。
参考文档:
- 官方文档:https://huggingface.co/docs/transformers/
- 模型库:https://huggingface.co/models
- 搜索模式:pipeline, AutoModel, AutoTokenizer, Trainer, PEFT (Parameter-Efficient Fine-Tuning)
其他平台、收费、价格或具体效果信息暂未提供。