ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Transformers 快速上手指南:加载预训练模型、Pipeline 推理与 Trainer 微调实战

2026/9/10 21:21:19 拓冰建站 浏览量
Transformers 快速上手指南:加载预训练模型、Pipeline 推理与 Trainer 微调实战 Transformers 快速上手指南加载预训练模型、Pipeline 推理与 Trainer 微调实战【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers导读本文是 docs/source/en/quicktour.md 的完整中文实战指南面向第一次接触 Transformers 的开发者。它把 Transformers 的对外接口收敛到「3 个模型基类 2 套 API」先用 AutoClass 从 Hub 加载预训练模型与预处理器再用Pipeline一条命令完成推理、用Trainer一个循环完成微调与评测。读完本文你将能独立完成环境搭建、模型加载、文本生成/图像分割/语音识别三类推理任务以及完整的「数据预处理 → 动态批处理 → 训练 → 推送 Hub」微调闭环并了解每一步背后的仓库源码依据。一、环境搭建与登录Transformers 是模型定义与使用框架其核心依赖是 PyTorch。官方推荐的第一步是访问 Hugging Face Hub一个用于发现、托管和协作模型/数据集/Spaces 的平台注册账号并创建 User Access Token以便下载受权限保护的模型与数据集。登录方式二选一在 Notebook 中使用交互式登录运行时按提示粘贴 tokenfrom huggingface_hub import notebook_login notebook_login()在命令行中登录需先确保安装了带 CLI 组件的huggingface_hub包hf auth login安装依赖先安装 PyTorch再安装最新版 Transformers 及生态配套库若在 Notebook 中安装则去掉行首的!!pip install torch!pip install -U transformers datasets evaluate accelerate timm各库在本文后续环节中的作用如下datasets提供数据集加载与.map()批量预处理evaluate用于评测指标accelerate用于自动检测/分配计算设备Accelerator与device_mapauto背后依赖它timm为视觉模型提供更多主干网络支持。对应依赖关系可查看仓库顶层 setup.py。二、Agent skills让编码 Agent 替你写训练脚本可选如果你使用 Claude Code、Codex 等带插件体系的编码 Agent可以从huggingface/skills安装Hugging Face Skills让 Agent 基于技能库而非手写脚本完成模型微调。以 Claude Code 为例/plugin marketplace add huggingface/skills /plugin install hf-clihuggingface/skillsCodex 则先添加 marketplace再在/plugins中安装技能codex plugin marketplace add huggingface/skills安装后在给 Agent 的指令中引用对应技能即可例如Use the HF Trainer skill to fine-tune RT-DETRv2 on Lekim89/sportsmot for basketball player tracking.本仓库中对应的端到端参考脚本位于 examples/pytorch如image-classification、object-detection等目录是理解微调全流程的补充材料。三、三大基类与 AutoClass 加载预训练模型3.1 三大基类Config、Model、Processor每一个预训练模型都继承自三个基类这也是理解 Transformers 抽象的第一张地图类作用PreTrainedConfig一个描述模型属性的文件/对象例如注意力头数量、词表大小、层数等超参数PreTrainedModel由配置文件定义的模型架构。预训练模型只输出原始 hidden states若要完成具体任务需要套上对应的任务头例如LlamaModel纯主干与LlamaForCausalLM带因果语言建模头Preprocessor把原始输入文本、图像、音频、多模态转换为模型能接收的数值张量例如PreTrainedTokenizer文本 → 张量、ImageProcessingMixin像素 → 张量其中核心三类的基类定义分别位于 src/transformers/configuration_utils.py、src/transformers/modeling_utils.py 与 src/transformers/tokenization_utils_base.py。3.2 为什么推荐 AutoClass手动逐个匹配模型架构非常繁琐因此仓库提供了 AutoClass 体系实现位于 src/transformers/models/auto核心工厂逻辑在 auto_factory.py。只需传入 Hub 上的模型名或本地权重目录路径AutoClass 就会根据config.json自动推断正确的架构类、并兼容 PyTorch 等框架例如AutoModel/AutoModelForCausalLM/AutoModelForSequenceClassification等模型类AutoTokenizer、AutoImageProcessor、AutoFeatureExtractor、AutoProcessor等预处理类。在 modeling_auto.py 中可以看到从MODEL_FOR_CAUSAL_LM_MAPPING_NAMES到MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES等一整套「架构名 → 任务模型类」的映射表AutoClass 正是依据这些映射在from_pretrained内部完成自动分发的。更完整的 AutoClass 文档见 docs/source/en/model_doc/auto.md。3.3 用 from_pretrained 加载模型与分词器推荐用AutoModelForCausalLM与AutoTokenizer分别加载模型和分词器仓库文档给出的示例模型为meta-llama/Llama-2-7b-hffrom transformers import AutoModelForCausalLM, AutoTokenizer model AutoModelForCausalLM.from_pretrained(meta-llama/Llama-2-7b-hf, dtypeauto, device_mapauto) tokenizer AutoTokenizer.from_pretrained(meta-llama/Llama-2-7b-hf)from_pretrained是 Transformers 中最常用的入口其完整签名与参数语义见 src/transformers/modeling_utils.py。加载时建议配置两个关键参数以保证最优加载device_mapauto让 Accelerate 自动把模型各层分配到当前最快的设备上先 GPU 后 CPU甚至支持将部分权重 offload 到 CPU/磁盘以最大化可用显存dtypeauto按权重实际存储的精度直接初始化模型避免「先以 fp32 加载再转精度」导致的二次加载开销。默认情况下 PyTorch 会以torch.float32加载权重。from_pretrained的pretrained_model_name_or_path既可以是 Hub 上的模型 ID也可以是本地目录该目录应包含通过save_pretrained保存的config.json与权重文件。除上述两个参数外源码还支持revision指定分支/tag/commit、use_safetensors、attn_implementationeager/sdpa/flash_attention_2 等、quantization_config、cache_dir等一系列高级选项需要时可直接查阅其 docstring。3.4 分词并运行一次推理用分词器把文本转成 PyTorch 张量再to(model.device)移动到模型所在设备model_inputs tokenizer([The secret to baking a good cake is ], return_tensorspt).to(model.device)推理时把张量传给model.generate()定义于GenerationMixin再用tokenizer.batch_decode把生成的 token id 解码回文本generated_ids model.generate(**model_inputs, max_length30) 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,到这一步模型便已具备推理或继续训练的能力。若想直接微调可以跳到下文 Trainer 部分。四、Pipeline一条命令完成多模态推理Pipeline类是推理最便捷的入口把「预处理 → 模型前向 → 后处理」整条链路封装成一个可调用对象支持文本生成、图像分割、自动语音识别、文档问答等大量任务。仓库中完整的受支持任务列表定义在 src/transformers/pipelines/init.pySUPPORTED_TASKSAPI 参考见 docs/source/en/main_classes/pipelines.md。创建Pipeline时只需指定任务名默认它会自动下载并缓存该任务对应的默认预训练模型也可以通过model参数指定具体模型。配合accelerate.Accelerator可以自动探测当前可用的推理设备from transformers import pipeline from accelerate import Accelerator device Accelerator().device4.1 文本生成pipe pipeline(text-generation, modelmeta-llama/Llama-2-7b-hf, devicedevice) pipe(The secret to baking a good cake is , max_length50) # [{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 weve created the best buttercream frosting reci}]4.2 图像分割pipeline pipeline(image-segmentation, modelfacebook/detr-resnet-50-panoptic, devicedevice)输入可以是图像 URL 或本地路径segments pipeline(https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png) segments[0][label] # bird segments[1][label] # bird4.3 自动语音识别pipeline pipeline(automatic-speech-recognition, modelopenai/whisper-large-v3, devicedevice) 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.}从源码实现看pipeline()函数会基于SUPPORTED_TASKS构建PIPELINE_REGISTRY PipelineRegistry(...)见 src/transformers/pipelines/init.py任务名在这里完成校验并分发到对应的具体 Pipeline 子类传给pipe(...)的max_length等额外关键字会被透传给内部的生成/前向逻辑。五、Trainer完整的训练与评测循环5.1 概览Trainer核心实现在 src/transformers/trainer.py为 PyTorch 模型提供开箱即用的完整训练与评测循环屏蔽了手写训练循环的大量样板代码梯度累积、学习率调度、日志、断点保存、多卡/分布式协调等。你只需提供四样东西模型、数据集、预处理器和一个把数据拼成 batch 的 data collator。对应 API 参考见 docs/source/en/main_classes/trainer.md。TrainingArguments类用于定制训练过程提供 batch size、学习率、混合精度、torch.compile等大量超参选项定义见 src/transformers/training_args.py例如learning_rate默认5e-5、per_device_train_batch_size默认8、num_train_epochs默认3.0、fp16/bf16与torch_compile开关等。你也可以直接用默认参数先跑出一个 baseline。5.2 第一步加载模型、分词器与数据集以 IMDb 影评情感分类二分类为示例加载序列分类模型与对应分词器并用datasets加载rotten_tomatoes数据集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(rotten_tomatoes)5.3 第二步编写预处理函数并对全数据集做批量映射def tokenize_dataset(dataset): return tokenizer(dataset[text]) dataset dataset.map(tokenize_dataset, batchedTrue)datasets.Dataset.map(..., batchedTrue)会把整批文本一次性送入分词器比逐条调用高效得多。5.4 第三步加载 DataCollator 以构建批数据不同样本长度不同需要 padding 到相同长度才能组成 batch。DataCollatorWithPadding会自动完成动态 paddingfrom transformers import DataCollatorWithPadding data_collator DataCollatorWithPadding(tokenizertokenizer)更完整的 collator 介绍见 docs/source/en/main_classes/data_collator.md。5.5 第四步配置 TrainingArgumentsoutput_dir指定训练产物模型权重、配置、训练状态的输出目录是唯一必填参数from transformers import TrainingArguments training_args TrainingArguments( output_dirdistilbert-rotten-tomatoes, learning_rate2e-5, per_device_train_batch_size8, per_device_eval_batch_size8, num_train_epochs2, push_to_hubTrue, )其中push_to_hubTrue会在训练结束后把模型自动推送到你的 Hub 账户需要已完成文首的登录。5.6 第五步组装 Trainer 并开始训练将模型、训练参数、训练/评测集、预处理器与 data collator 全部交给Trainer调用.train()即可启动from transformers import Trainer trainer Trainer( modelmodel, argstraining_args, train_datasetdataset[train], eval_datasetdataset[test], processing_classtokenizer, data_collatordata_collator, ) trainer.train()注意当前版本Trainer.__init__中承接预处理器/分词器的是processing_class参数取代旧版tokenizer/feature_extractor等参数的统一命名。该循环内部会自动完成模型置于训练模式、batch 组装、前向反向、优化器更新、评测与日志记录等工作。训练完成后用Trainer.push_to_hub()一键把模型与分词器分享到 Hubtrainer.push_to_hub()至此你就完成了用 Transformers 训练的第一个模型。本仓库中与本节流程对应的可运行完整示例见 examples/pytorch/text-classificationPyTorch 版微调脚本可作为真实数据集上落地时的参照。六、后续深入方向掌握本文三大流程后可以按兴趣继续探索基类深入阅读PreTrainedConfig/PreTrainedModel/Processor 文档理解如何创建、定制模型处理音频/图像/多模态输入并分享模型推理深入 Pipeline、大模型对话与 Agents以及针对具体硬件与框架的推理优化训练深入学习 Trainer 与分布式训练、面向特定硬件的训练优化如 examples/pytorch 与 docs/source/en/main_classes/deepspeed.md量化用更少的 bit 表示权重以降低显存/存储占用并加速推理参考 docs/source/en/main_classes/quantization.md任务配方如果希望找到「某一具体任务的端到端训练 推理」配方参考 examples 目录下按任务组织的完整示例。【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考