关于 transformers
Hugging Face Transformers 是用于调用和训练预训练模型的库及技能指南,覆盖语言、视觉、科学和多模态任务,并提供统一的 Pipeline 与 Auto 类 API。
主要功能
- 01预训练模型 Pipeline
- 02AutoModel 和 AutoTokenizer API
- 03分词与批量数据准备
- 04基于 Trainer 训练模型
- 05量化模型加载
适用场景
- 01进行文本分类或摘要
- 02分析蛋白质或化学序列
- 03在领域数据上微调模型
- 04处理图像和文档
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ tondevrel/ scientific-agent-skills --skill transformers安装后在 Claude Code 中输入/transformers确认已加载。
详细介绍
Hugging Face Transformers——现代 AI 模型
Transformers 提供 API 和工具,让您轻松下载和训练先进的预训练模型。研究人员可以重复使用模型,而不是从头训练,从而降低计算成本和碳足迹。
适用场景
- 自然语言处理(摘要、翻译、命名实体识别)。
- 科学序列分析(蛋白质折叠、DNA/RNA 序列建模)。
- 化学性质预测(使用 SMILES 等分子字符串)。
- 计算机视觉(视觉 Transformer——ViT、图像分类)。
- 使用基础模型进行时间序列预测。
- 在特定领域的科学文献上微调大语言模型(LLM)。
- 多模态任务(文档 AI、视觉问答)。
参考文档
官方文档:https://huggingface.co/docs/transformers/
模型中心:https://huggingface.co/models
搜索模式:pipeline、AutoModel、AutoTokenizer、Trainer、PEFT(参数高效微调)
核心原则
“Auto” 类
Hugging Face 使用“Auto”类(AutoModel、AutoTokenizer),根据模型名称或路径自动推断正确的架构。这使代码具有很强的可移植性。
分词
数据进入模型之前,必须先转换为数字 Token。Tokenizer 负责处理这一过程,包括填充、截断和特殊 Token(如 [CLS]、[SEP])。
Pipeline
使用模型最简单的方式。它将分词、模型执行和后处理封装到一次 pipe(data) 调用中。
快速参考
安装
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)
关键规则
✅ 应该做
- 使用 Auto 类——始终优先使用
AutoTokenizer.from_pretrained()和AutoModel.from_pretrained(),以保持灵活性。 - 设置设备——在 Pipeline 中明确设置
device=0(用于 CUDA)或device="mps"(用于 Mac),以确保 GPU 加速。 - 缓存模型——模型体积较大。使用
HF_HOME环境变量管理模型在磁盘上的存储位置。 - 处理截断——大多数模型都有最大序列长度(通常为 512)。在 Tokenizer 中始终使用
truncation=True。 - 使用 Datasets 库——训练时,使用
datasets库处理数据加载和流式传输,避免占满 RAM。 - 将 Tokenizer 与模型一起保存——微调时,始终将 Tokenizer 与模型一同保存,以确保一致性。
❌ 不要做
- 在循环中加载模型——加载模型需要数秒时间和数 GB RAM。只加载一次,重复使用。
- 上传私有数据——使用可能会向 API 发送数据的模型时请务必谨慎(不过 transformers 主要在本地执行)。
- 忽略填充——进行批处理时,确保设置
padding=True,使批次中的所有序列长度相同。 - 为任务选错模型——“BERT”模型用于理解,“GPT”用于生成。请使用正确的架构。
反模式(绝对不要)
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!
深入了解分词
为模型准备数据
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()
科学应用
1. 蛋白质序列分析(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
2. 化学性质预测(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}")
3. 论文命名实体识别(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)
性能与效率
1. 量化(bitsandbytes)
通过降低精度(8 位或 4 位),在消费级 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)
2. 在 GPU 上使用 pipeline
# 'device=0' targets the first CUDA device
pipe = pipeline("translation_en_to_fr", model="t5-base", device=0)
常见问题与解决方案
GPU 上“内存不足”(OOM)
# ❌ Problem: Batch size is too large for GPU RAM
# ✅ Solution:
# 1. Reduce 'per_device_train_batch_size'
# 2. Use 'gradient_accumulation_steps' to keep effective batch size
# 3. Use 'fp16=True' in TrainingArguments
模型输出是字典,而不是张量
# ❌ Problem: outputs[0] works, but is confusing
# ✅ Solution: Access by name
outputs = model(**inputs)
hidden_states = outputs.last_hidden_state
分词速度慢
# ✅ Solution: Use "Fast" tokenizers (written in Rust, usually default)
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased", use_fast=True)
Hugging Face Transformers 为科学界普及了 AI。它为全球最强大的模型提供了统一接口,让研究人员减少在工程工作上花费的时间,将更多时间用于从数据中发现洞见。
评论
支持 Markdown