Transformers详解

发布时间:2026/10/11 15:18:36
Transformers详解
Transformers详解一、加载模型from_pretrained() 说明from_pretrained() 方法会加载 safetensors 文件格式中存储的权重前提是这些权重可用该方法接受来自 Hugging Face Hub 或本地目录的权重 examples: from transformers import AutoModelForCausalLM model AutoModelForCausalLM.from_pretrained(meta-llama/Llama-2-7b-hf, device_mapauto)1.1 模型和配置​ 所有模型都包含一个 configuration.py 文件其中定义了隐藏层数、词汇表大小、激活函数等特定属性。你还会找到一个 modeling.py 文件用于定义各层的结构以及每层内部执行的数学运算。modeling.py 文件会根据 configuration.py 中的模型参数来构建模型。此时你已经拥有了一个随机权重的模型需要进行训练以输出有意义的结果。​ 模型架构指的是模型的结构而检查点指的是特定架构下的模型权重。例如BERT 是一种架构而 google-bert/bert-base-uncased 则是一个检查点。你将看到“模型”一词与“架构”和“检查点”可以互换使用。此外模型架构对应于model_type架构类型代表模型特点Encoder-onlyBERT双向注意力适合理解任务Decoder-onlyGPT、LLaMA因果注意力适合生成Encoder-DecoderT5、BART编码器解码器适合翻译、摘要其中在hugging face代码里这些架构对应不同的类BERT架构BertModel、BertForSequenceClassificationGPT-2架构GPT2Model、GPT2LMHeadModelT5 架构 T5Model、T5ForConditionalGenerationLLaMA 架构LlamaModel、LlamaForCausalLM可以加载模型分为两类1.一种输出隐藏状态的简化模型例如 AutoModel 或 LlamaModel。2.带有特定头部的模型例如 AutoModelForCausalLM 或 LlamaForCausalLM用于执行特定任务。from transformers import AutoModel model AutoModel.from_pretrained(bert-base-chinese) 执行过程 1. 下载或读取 bert-base-chinese/config.json 2. 看到 model_type: bert 3. AutoConfig 查表bert - BertConfig 4. 用 BertConfig 读取配置 5. AutoModel 查表BertConfig - BertModel 6. 实例化 BertModel 7. 加载权重 8. 返回一个 BertModel 对象 AutoClass自动选择正确的模型类 工作原理自动匹配正确的模型架构 常用的AutoClass有AutoTokenizer、AutoModel、AutoModelForSeqClass、AutoModelForCausalLM1.2 模型类1. AutoModel类 AutoModel 类是一种便捷的方式用于加载架构而无需知道具体的模型类名因为有多种模型可供选择。它会根据配置文件自动选择正确的模型类。你只需了解要使用的任务和检查点即可。只要特定任务支持相应的架构即可轻松切换模型或任务。 examples: from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoModelForQuestionAnswering # use the same API for 3 different tasks model AutoModelForCausalLM.from_pretrained(meta-llama/Llama-2-7b-hf) model AutoModelForSequenceClassification.from_pretrained(meta-llama/Llama-2-7b-hf) model AutoModelForQuestionAnswering.from_pretrained(meta-llama/Llama-2-7b-hf) 2.model-specific类 AutoModel类是基于特定模型类构建的。所有支持特定任务的模型类都会映射到其对应的AutoModelFor任务类。如果你已经知道要使用哪个模型类就可以直接使用其特定的模型类。 from transformers import LlamaModel, LlamaForCausalLM model LlamaForCausalLM.from_pretrained(meta-llama/Llama-2-7b-hf)二、预处理器1.1 Tokenizer[分词器]用途分词器将文本转换为张量这些张量是模型的输入。它对文本进行标准化和分割应用分词算法添加特殊标记并将输出的ID解码回文本。1.加载分词器 可以使用 AutoTokenizer 类或特定模型的分词器类加载分词器。 AutoTokenizer.from_pretrained() 会读取模型配置解析出正确的分词器类并返回其实例。你无需事先知道分词器的类。大多数分词器都会被解析为 TokenizersBackend 的子类后者是来自 Tokenizers 库的一个基于 Rust 的高性能分词器。 from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained(google/gemma-2-2b) 2.编码与解码 TokenizersBackend.call() 方法将文本或一组文本编码为 input_ids、attention_mask 及其他模型输入并控制填充、截断和特殊标记的插入。 from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained(google/gemma-2-2b) tokenizer(Sphinx of black quartz, judge my vow., return_tensorspt) { input_ids: tensor([[ 2, 235277, 82913, 576, 2656, 30407, 235269, 11490, 970, 29871, 235265]]), attention_mask: tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) } TokenizersBackend.encode() 的功能类似但仅返回 input_ids。 TokenizersBackend.decode() 将单个序列或一批分词后的 input_ids 转换回文本。 TokenizersBackend.decode() 会保留精确的分词间距。将 clean_up_tokenization_spaces 设置为 True 可移除标点前的空格将 skip_special_tokens 设置为 True 可去除输出中的特殊标记。 特殊标记用于标识序列中的结构边界例如序列开始位置或填充位置。每个模型都有其自身的特殊标记集合。分词器在调用时会添加这些标记。使用 extra_special_tokens 参数注册额外的命名特殊令牌。多模态模型会将这些令牌用作图像、视频或音频的占位符。 from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained( google/gemma-3-4b-pt, extra_special_tokens{image_token: image} ) 3.批量处理 批量处理会在单次调用中对多个序列进行分词。由于其基于 Rust 的后端能够跨线程并行化处理任务因此 TokenizersBackend 能更快地处理大批次数据。 from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained(google/gemma-2-2b) tokenizer( [ Sphinx of black quartz, judge my vow., Pack my box with five dozen liquor jugs., How vexingly quick daft zebras jump! ], return_tensorspt ) 批量处理要求所有序列具有相同的长度。填充和截断是处理不同长度序列的策略。 填充操作会添加特殊标记使较短的序列与批次中最长的序列匹配。注意力掩码将填充位置标记为0以便模型忽略这些位置。设置 paddingTrue 可以将序列填充到最长长度或传入 max_length 参数将序列填充至固定大小。 from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained(google/gemma-2-2b) tokenizer( [ Sphinx of black quartz, judge my vow., Pack my box with five dozen liquor jugs., How vexingly quick daft zebras jump! ], return_tensorspt, paddingTrue, ) { input_ids: tensor([ [ 2, 235277, 82913, 576, 2656, 30407, 235269, 11490, 970, 29871, 235265], [ 0, 2, 6519, 970, 3741, 675, 4105, 25955, 42184, 225789, 235265], [ 0, 2, 2299, 73378, 17844, 4320, 224463, 4949, 48977, 9902, 235341] ]), attention_mask: tensor([ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ]) } 截断片段令牌使序列长度不超过最大长度。设置 truncationTrue 并指定 max_length 即可启用该功能。 填充和截断协同工作。短序列会获得填充标记而长序列则会丢失尾部标记。它们共同生成一个压缩的矩形张量。 from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained(google/gemma-2-2b) tokenizer( [ Sphinx of black quartz, judge my vow., Pack my box with five dozen liquor jugs., How vexingly quick daft zebras jump! ], return_tensorspt, paddingTrue, truncationTrue, max_length5 ) { input_ids: tensor([ [ 2, 235277, 82913, 576, 2656], [ 2, 6519, 970, 3741, 675], [ 2, 2299, 73378, 17844, 4320] ]), attention_mask: tensor([ [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1] ]) }三、管道Pipeline是一个简单而强大的推理 API可轻松用于各种机器学习任务支持 Hugging Face Hub 中的任意模型Transformers 有两个管道类一个通用的 Pipeline以及许多针对特定任务的独立管道例如 TextGenerationPipeline。通过在 Pipeline 的任务参数中设置任务标识符来加载这些独立管道。每个管道的任务标识符可在其 API 文档中找到。每个任务都默认配置为使用预训练模型和预处理器但如果您想使用不同的模型可以通过修改模型参数来覆盖此设置。examples: 要使用 Gemma 2 的 TextGenerationPipeline请设置 tasktext-generation 和 modelgoogle/gemma-2-2b from transformers import pipeline pipeline pipeline(tasktext-generation, modelgoogle/gemma-2-2b) pipeline(the secret to baking a really good cake is ) [{generated_text: the secret to baking a really good cake is 1. the right ingredients 2. the}]Pipeline 可与多种模态下的机器学习任务兼容。只需将合适的输入传递给 Pipeline其余部分将由它自动处理。ASR: from transformers import pipeline pipeline pipeline(taskautomatic-speech-recognition, modelopenai/whisper-large-v3) pipeline(https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac) {text: I have a dream that one day this nation will rise up and live out the true meaning of its creed.} image classification: from transformers import pipeline pipeline pipeline(taskimage-classification, modelgoogle/vit-base-patch16-224) pipeline(imageshttps://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg) [{label: lynx, catamount, score: 0.43350091576576233}, {label: cougar, puma, catamount, mountain lion, painter, panther, Felis concolor, score: 0.034796204417943954}, {label: snow leopard, ounce, Panthera uncia, score: 0.03240183740854263}, {label: Egyptian cat, score: 0.02394474856555462}, {label: tiger cat, score: 0.02288915030658245}] visual question answering: from transformers import pipeline pipeline pipeline(taskvisual-question-answering, modelSalesforce/blip-vqa-base) pipeline( imagehttps://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg, questionWhat is in the image?, ) [{answer: statue of liberty}]Parameters[参数]Device:Pipeline 兼容多种硬件类型包括 GPU、CPU、Apple Silicon 等。通过设备参数配置硬件类型。默认情况下若未设置设备则 Pipeline 会自动将模型部署在第一个可用的加速器上CUDA GPU、Apple Silicon MPS、XPU 等当没有可用加速器时才回退到 CPU。使用 pass devicecpu 可强制模型在 CPU 上运行。 from transformers import pipeline pipeline pipeline(tasktext-generation, modelgoogle/gemma-2-2b, device0) pipeline(the secret to baking a really good cake is ) Batch inference:Pipeline还可以通过 batch_size 参数处理批量输入。批量推理可能提高速度尤其是在 GPU 上但无法保证。硬件、数据以及模型本身等其他因素也会影响批量推理是否能提升速度。因此默认情况下批量推理功能被禁用。批量推理的另一个良好用例是在流水线中处理流式数据。 from transformers import pipeline from accelerate import Accelerator device Accelerator().device pipeline pipeline(tasktext-generation, modelgoogle/gemma-2-2b, devicedevice, batch_size2) pipeline([the secret to baking a really good cake is, a baguette is, paris is the, hotdogs are]) [[{generated_text: the secret to baking a really good cake is to use a good cake mix.\n\ni’}], [{generated_text: a baguette is}], [{generated_text: paris is the most beautiful city in the world.\n\ni’ve been to paris 3}], [{generated_text: hotdogs are a staple of the american diet. they are a great source of protein and can}]]四、Generate API1.1文本生成​ 文本生成是大语言模型LLM最广泛的应用场景。LLM 在训练过程中会根据给定的初始文本提示以及自身生成的输出在预设长度内或到达结束标记EOS时生成下一个词token。在 Transformers 中generate() API 用于文本生成适用于所有具备生成能力的模型。