名称: transformers 描述: 使用HuggingFace Transformers处理自然语言处理、计算机视觉、音频和多模态任务的最先进机器学习模型。该技能应用于微调预训练模型、通过管道进行推理、生成文本、训练序列模型,或使用BERT、GPT、T5、ViT和其他Transformer架构。涵盖模型加载、分词、使用Trainer API训练、文本生成策略,以及分类、命名实体识别、问答、摘要、翻译和图像任务的任务特定模式。(插件:scientific-packages@claude-scientific-skills)
Transformers
概述
Transformers库为自然语言处理、计算机视觉、音频和多模态任务提供了最先进的机器学习模型。应用此技能可通过管道进行快速推理,通过Trainer API进行综合训练,以及使用各种解码策略进行灵活的文本生成。
核心能力
1. 使用管道进行快速推理
对于无需复杂设置的快速推理,使用pipeline() API。管道抽象了分词、模型调用和后处理。
from transformers import pipeline
# 文本分类
classifier = pipeline("text-classification")
result = classifier("This product is amazing!")
# 命名实体识别
ner = pipeline("token-classification")
entities = ner("Sarah works at Microsoft in Seattle")
# 问答
qa = pipeline("question-answering")
answer = qa(question="What is the capital?", context="Paris is the capital of France.")
# 文本生成
generator = pipeline("text-generation", model="gpt2")
text = generator("Once upon a time", max_length=50)
# 图像分类
image_classifier = pipeline("image-classification")
predictions = image_classifier("image.jpg")
何时使用管道:
- 快速原型设计和测试
- 无需自定义逻辑的简单推理任务
- 演示和示例
- 标准任务的生产推理
可用管道任务:
- NLP: text-classification, token-classification, question-answering, summarization, translation, text-generation, fill-mask, zero-shot-classification
- 视觉: image-classification, object-detection, image-segmentation, depth-estimation, zero-shot-image-classification
- 音频: automatic-speech-recognition, audio-classification, text-to-audio
- 多模态: image-to-text, visual-question-answering, image-text-to-text
有关全面的管道文档,请参阅references/pipelines.md。
2. 模型训练和微调
使用Trainer API进行综合模型训练,支持分布式训练、混合精度和高级优化。
基本训练工作流程:
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
TrainingArguments,
Trainer
)
from datasets import load_dataset
# 1. 加载和分词数据
dataset = load_dataset("imdb")
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True)
tokenized_datasets = dataset.map(tokenize_function, batched=True)
# 2. 加载模型
model = AutoModelForSequenceClassification.from_pretrained(
"bert-base-uncased",
num_labels=2
)
# 3. 配置训练
training_args = TrainingArguments(
output_dir="./results",
num_train_epochs=3,
per_device_train_batch_size=16,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
)
# 4. 创建训练器并训练
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["test"],
)
trainer.train()
关键训练特性:
- 混合精度训练 (fp16/bf16)
- 分布式训练 (多GPU、多节点)
- 梯度累积
- 带热身的学率调度
- 检查点管理
- 超参数搜索
- 推送到Hugging Face Hub
有关详细训练文档,请参阅references/training.md。
3. 文本生成
使用各种解码策略生成文本,包括贪婪解码、束搜索、采样等。
生成策略:
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer = AutoTokenizer.from_pretrained("gpt2")
inputs = tokenizer("Once upon a time", return_tensors="pt")
# 贪婪解码 (确定性)
outputs = model.generate(**inputs, max_new_tokens=50)
# 束搜索 (探索多个假设)
outputs = model.generate(
**inputs,
max_new_tokens=50,
num_beams=5,
early_stopping=True
)
# 采样 (创意、多样)
outputs = model.generate(
**inputs,
max_new_tokens=50,
do_sample=True,
temperature=0.7,
top_p=0.9,
top_k=50
)
生成参数:
temperature: 控制随机性 (0.1-2.0)top_k: 从top-k令牌中采样top_p: 核心采样阈值num_beams: 束搜索的束数repetition_penalty: 抑制重复no_repeat_ngram_size: 防止重复n-gram
有关全面生成文档,请参阅references/generation_strategies.md。
4. 任务特定模式
常见任务模式与适当的模型类:
文本分类:
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained(
"bert-base-uncased",
num_labels=3,
id2label={0: "negative", 1: "neutral", 2: "positive"}
)
命名实体识别 (令牌分类):
from transformers import AutoModelForTokenClassification
model = AutoModelForTokenClassification.from_pretrained(
"bert-base-uncased",
num_labels=9 # 实体类型数量
)
问答:
from transformers import AutoModelForQuestionAnswering
model = AutoModelForQuestionAnswering.from_pretrained("bert-base-uncased")
摘要和翻译 (序列到序列):
from transformers import AutoModelForSeq2SeqLM
model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
图像分类:
from transformers import AutoModelForImageClassification
model = AutoModelForImageClassification.from_pretrained(
"google/vit-base-patch16-224",
num_labels=num_classes
)
有关详细的任务特定工作流程,包括数据预处理、训练和评估,请参阅references/task_patterns.md。
自动类
使用自动类基于模型检查点自动选择架构:
from transformers import (
AutoTokenizer, # 分词
AutoModel, # 基础模型 (隐藏状态)
AutoModelForSequenceClassification,
AutoModelForTokenClassification,
AutoModelForQuestionAnswering,
AutoModelForCausalLM, # GPT风格
AutoModelForMaskedLM, # BERT风格
AutoModelForSeq2SeqLM, # T5, BART
AutoProcessor, # 用于多模态模型
AutoImageProcessor, # 用于视觉模型
)
# 通过名称加载任何模型
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased")
有关全面API文档,请参阅references/api_reference.md。
模型加载和优化
设备放置:
model = AutoModel.from_pretrained("bert-base-uncased", device_map="auto")
混合精度:
model = AutoModel.from_pretrained(
"model-name",
torch_dtype=torch.float16 # 或 torch.bfloat16
)
量化:
from transformers import BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16
)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-hf",
quantization_config=quantization_config,
device_map="auto"
)
常见工作流程
快速推理工作流程
- 为任务选择合适的管道
- 加载管道,可选指定模型
- 传递输入并获取结果
- 对于批处理,传递输入列表
参见: scripts/quick_inference.py 获取全面管道示例
训练工作流程
- 使用🤗 Datasets加载和预处理数据集
- 使用适当分词器分词数据
- 为特定任务加载预训练模型
- 配置TrainingArguments
- 使用模型、数据和compute_metrics创建Trainer
- 使用
trainer.train()训练 - 使用
trainer.evaluate()评估 - 保存模型并可选推送到Hub
参见: scripts/fine_tune_classifier.py 获取完整训练示例
文本生成工作流程
- 加载因果或序列到序列语言模型
- 加载分词器并分词提示
- 选择生成策略 (贪婪、束搜索、采样)
- 配置生成参数
- 使用
model.generate()生成 - 将输出令牌解码为文本
参见: scripts/generate_text.py 获取生成策略示例
最佳实践
- 使用自动类 以在不同模型架构间灵活
- 批处理 以提高效率 - 一次处理多个输入
- 设备管理 - 使用
device_map="auto"进行自动放置 - 内存优化 - 启用fp16/bf16或量化以处理大模型
- 检查点管理 - 定期保存检查点并加载最佳模型
- 管道用于快速任务 - 使用管道进行标准推理任务
- 自定义指标 - 定义compute_metrics以进行任务特定评估
- 梯度累积 - 用于有限内存上的大有效批次大小
- 学率热身 - 通常为总训练步数的5-10%
- Hub集成 - 将训练好的模型推送到Hub以共享和版本控制
资源
scripts/
可执行Python脚本演示常见Transformers工作流程:
quick_inference.py- NLP、视觉、音频和多模态任务的管道示例fine_tune_classifier.py- 使用Trainer API的完整微调工作流程generate_text.py- 使用各种解码策略的文本生成
直接运行脚本以查看示例:
python scripts/quick_inference.py
python scripts/fine_tune_classifier.py
python scripts/generate_text.py
references/
全面参考文档,根据需要加载到上下文中:
api_reference.md- 核心类和API (自动类、Trainer、GenerationConfig等)pipelines.md- 所有可用管道按模态组织,带示例training.md- 训练模式、TrainingArguments、分布式训练、回调generation_strategies.md- 文本生成方法、解码策略、参数task_patterns.md- 常见任务的完整工作流程 (分类、NER、QA、摘要等)
处理特定任务或功能时,加载相关参考文件以获取详细指导。
附加信息
- 官方文档: https://huggingface.co/docs/transformers/index
- 模型Hub: https://huggingface.co/models (1M+ 预训练模型)
- 数据集Hub: https://huggingface.co/datasets
- 安装:
pip install transformers datasets evaluate accelerate - GPU支持: 需要带CUDA的PyTorch或TensorFlow
- 框架支持: PyTorch (主要), TensorFlow, JAX/Flax