# 快速入门

Transformers 旨在快速且易于使用，让每个人都能开始学习或构建基于 transformer 的模型。

面向用户的抽象层数量被限制为仅三个用于实例化模型的类，以及两个用于推理或训练的 API。本快速入门将向您介绍 Transformers 的核心功能，并展示如何：

- 加载预训练模型
- 使用 [Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline) 运行推理
- 使用 [Trainer](/docs/transformers/v5.23.0/zh/main_classes/trainer#transformers.Trainer) 微调模型

## 设置

首先，我们建议创建一个 Hugging Face [账户](https://hf.co/join)。通过账户，您可以在 Hugging Face [Hub](https://hf.co/docs/hub/index) 上托管和访问受版本控制的模型、数据集以及 [Spaces](https://hf.co/spaces)。Hub 是一个用于探索和构建的协作平台。

创建一个 [User Access Token](https://hf.co/docs/hub/security-tokens#user-access-tokens) 并登录您的账户。

在提示登录时，将您的 User Access Token 粘贴到 [notebook_login](https://huggingface.co/docs/huggingface_hub/v2.4.0/en/package_reference/authentication#huggingface_hub.notebook_login) 中。

```py
from huggingface_hub import notebook_login

notebook_login()
```

请确保已安装 [huggingface_hub[cli]](https://huggingface.co/docs/huggingface_hub/guides/cli#getting-started) 包，并运行以下命令。在提示登录时，请粘贴您的 User Access Token。

```bash
hf auth login
```

安装 PyTorch。

```bash
# remove ! if installing from the CLI
!pip install torch
```

然后，安装最新版本的 Transformers 以及 Hugging Face 生态系统中的一些附加库，用于访问数据集和视觉模型、评估训练以及针对大模型优化训练。

```bash
# remove ! if installing from the CLI
!pip install -U transformers datasets evaluate accelerate timm
```

## Agent 技能

[Hugging Face Skills](https://github.com/huggingface/skills) 教你的编码代理如何使用 Transformers。你无需自己编写训练脚本，只需让代理微调一个视觉模型，并让该技能引导它完成操作。

```sh
/plugin marketplace add huggingface/skills
/plugin install hf-cli@huggingface/skills
```

```sh
codex plugin marketplace add huggingface/skills
```

然后在 Codex 中运行 `/plugins`，并从 `huggingface/skills` 仓库中安装一个 skill。

有关 Cursor 和 Gemini 等更多受支持的平台，请参阅 [安装](https://github.com/huggingface/skills#installation) 指南。

安装技能后，请将其包含在你对编码代理的指令中。

```md
Use the HF Trainer skill to fine-tune RT-DETRv2 on [Lekim89/sportsmot](https://huggingface.co/datasets/Lekim89/sportsmot) for basketball player tracking.
```

## 预训练模型

每个预训练模型都继承自三个基类。

| **类** | **描述** |
|---|---|
| [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) | 指定模型属性的文件，例如注意力头数或词汇表大小。 |
| [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel) | 由配置文件中的模型属性所定义的模型（或架构）。预训练模型仅返回原始隐藏状态。针对特定任务，请使用相应的模型头将原始隐藏状态转换为有意义的结果（例如，[LlamaModel](/docs/transformers/v5.23.0/zh/model_doc/llama2#transformers.LlamaModel) 与 [LlamaForCausalLM](/docs/transformers/v5.23.0/zh/model_doc/llama2#transformers.LlamaForCausalLM)）。 |
| 预处理器 | 用于将原始输入（文本、图像、音频、多模态）转换为模型数值输入的一类。例如，[PreTrainedTokenizer](/docs/transformers/v5.23.0/zh/main_classes/tokenizer#transformers.PythonBackend) 将文本转换为张量，[ImageProcessingMixin](/docs/transformers/v5.23.0/zh/internal/image_processing_utils#transformers.ImageProcessingMixin) 将像素转换为张量。 |

我们建议使用 [AutoClass](./model_doc/auto) API 来加载模型和预处理器，因为它会根据预训练权重和配置文件的名称或路径，自动推断出适用于每个任务和机器学习框架的相应架构。

使用 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 从 Hub 加载权重和配置文件到模型和预处理器类中。

加载模型时，请配置以下参数，以确保模型以最优方式加载。

- `device_map="auto"` 会自动将模型权重优先分配到速度最快的设备上。
- `dtype="auto"` 会直接以权重存储的数据类型来初始化模型权重，这有助于避免两次加载权重（PyTorch 默认以 `torch.float32` 加载权重）。

```py
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype="auto", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
```

使用分词器对文本进行分词，并返回 PyTorch 张量。在运行推理之前，将分词后的输入移动到与模型相同的设备上，以便模型能够处理它们。

```py
model_inputs = tokenizer(["The secret to baking a good cake is "], return_tensors="pt").to(model.device)
```

模型现已准备好进行推理或训练。

对于推理，将标记化后的输入传递给 [generate()](/docs/transformers/v5.23.0/zh/main_classes/text_generation#transformers.GenerationMixin.generate) 以生成文本。使用 [batch_decode()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.batch_decode) 将 token id 解码回文本。

```py
generated_ids = model.generate(**model_inputs, max_length=30)
tokenizer.batch_decode(generated_ids)[0]
'<s> The secret to baking a good cake is 100% in the preparation. There are so many recipes out there,'
```

> [!TIP]
> 请跳至 [Trainer](#trainer) 部分，了解如何微调模型。

## Pipeline

[Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline) 类是使用预训练模型进行推理的最便捷方式。它支持多种任务，例如文本生成、图像分割、自动语音识别、文档问答等。

> [!TIP]
> 有关可用任务的完整列表，请参阅 [Pipeline](./main_classes/pipelines) API 参考。

创建一个 [Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline) 对象并选择任务。默认情况下，[Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline) 会下载并缓存给定任务的默认预训练模型。将模型名称传递给 `model` 参数以选择特定模型。

使用 `Accelerator` 自动检测可用于推理的加速器。

```py
from transformers import pipeline
from accelerate import Accelerator

device = Accelerator().device

pipe = pipeline("text-generation", model="meta-llama/Llama-2-7b-hf", device=device)
```

使用一些初始文本提示 [Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline) 以生成更多文本。

```py
pipe("The secret to baking a good cake is ", max_length=50)
[{'generated_text': 'The secret to baking a good cake is 100% in the batter. The secret to a great cake is the icing.\nThis is why we’ve created the best buttercream frosting reci'}]
```

使用 `Accelerator` 自动检测可用于推理的加速器。

```py
from transformers import pipeline
from accelerate import Accelerator

device = Accelerator().device

pipeline = pipeline("image-segmentation", model="facebook/detr-resnet-50-panoptic", device=device)
```

将图像（图像的 URL 或本地路径）传递给 [Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline)。

   

```py
segments = pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
segments[0]["label"]
'bird'
segments[1]["label"]
'bird'
```

使用 `Accelerator` 自动检测可用于推理的加速器。

```py
from transformers import pipeline
from accelerate import Accelerator

device = Accelerator().device

pipeline = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3", device=device)
```

将音频文件传递给 [Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline)。

```py
pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
{'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'}
```

## Trainer

[Trainer](/docs/transformers/v5.23.0/zh/main_classes/trainer#transformers.Trainer) 是 PyTorch 模型的完整训练与评估循环。它抽象了手动编写训练循环时通常涉及的大量样板代码，因此您可以更快地开始训练，并将精力集中在训练设计决策上。您只需要一个模型、一个数据集、一个预处理器和一个数据整理器（data collator），即可从数据集中构建数据批次。

使用 [TrainingArguments](/docs/transformers/v5.23.0/zh/main_classes/trainer#transformers.TrainingArguments) 类来自定义训练过程。它提供了许多用于训练、评估等方面的选项。您可以尝试不同的训练超参数和功能，例如 batch size、learning rate、mixed precision、torch.compile 等，以满足您的训练需求。您也可以使用默认的训练参数来快速生成一个基线。

加载用于训练的模型、分词器和数据集。

```py
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from datasets import load_dataset

model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
dataset = load_dataset("cornell-movie-review-data/rotten_tomatoes")
```

创建一个函数，用于对文本进行分词并将其转换为 PyTorch 张量。使用 [map](https://huggingface.co/docs/datasets/v5.2.0/en/package_reference/main_classes#datasets.Dataset.map) 方法将此函数应用于整个数据集。

```py
def tokenize_dataset(dataset):
    return tokenizer(dataset["text"])
dataset = dataset.map(tokenize_dataset, batched=True)
```

加载数据整理器（data collator）以创建数据批次，并将分词器（tokenizer）传递给它。

```py
from transformers import DataCollatorWithPadding

data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
```

接下来，使用训练功能和超参数来设置 [TrainingArguments](/docs/transformers/v5.23.0/zh/main_classes/trainer#transformers.TrainingArguments)。

```py
from transformers import TrainingArguments

training_args = TrainingArguments(
    output_dir="distilbert-rotten-tomatoes",
    learning_rate=2e-5,
    per_device_train_batch_size=8,
    per_device_eval_batch_size=8,
    num_train_epochs=2,
    push_to_hub=True,
)
```

最后，将这些独立的组件全部传入 [Trainer](/docs/transformers/v5.23.0/zh/main_classes/trainer#transformers.Trainer)，并调用 [train()](/docs/transformers/v5.23.0/zh/main_classes/trainer#transformers.Trainer.train) 即可开始训练。

```py
from transformers import Trainer

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=dataset["train"],
    eval_dataset=dataset["test"],
    processing_class=tokenizer,
    data_collator=data_collator,
)

trainer.train()
```

使用 [push_to_hub()](/docs/transformers/v5.23.0/zh/main_classes/trainer#transformers.Trainer.push_to_hub) 将您的模型和分词器共享到 Hub。

```py
trainer.push_to_hub()
```

恭喜，你刚刚使用 Transformers 训练了你的第一个模型！

## 后续步骤

现在，您对 Transformers 及其功能有了更深入的了解，是时候继续探索并学习您最感兴趣的内容了。

- **基类**：深入了解配置、模型和处理器类。这将帮助你理解如何创建和自定义模型、预处理不同类型的输入（音频、图像、多模态），以及如何共享你的模型。
- **推理**：进一步探索 [Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline)，了解 LLM 的推理与对话、智能体，以及如何结合你的机器学习框架和硬件来优化推理。
- **训练**：深入了解 [Trainer](/docs/transformers/v5.23.0/zh/main_classes/trainer#transformers.Trainer)，以及分布式训练和在特定硬件上优化训练的方法。
- **量化**：通过量化减少内存和存储需求，并使用更少的位来表示权重以加快推理速度。
- **资源**：正在寻找针对特定任务训练和推理模型的端到端教程？请查看任务教程！

