☰
Transformers详解
2026/10/11 15:18:33 网站建设 项目流程

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_map="auto")
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、BertForSequenceClassification

GPT-2架构:GPT2Model、GPT2LMHeadModel

T5 架构 :T5Model、T5ForConditionalGeneration

LLaMA 架构: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、AutoModelForCausalLM
1.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_tensors="pt") { '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_tensors="pt" ) 批量处理要求所有序列具有相同的长度。填充和截断是处理不同长度序列的策略。 填充操作会添加特殊标记,使较短的序列与批次中最长的序列匹配。注意力掩码将填充位置标记为0,以便模型忽略这些位置。设置 padding=True 可以将序列填充到最长长度,或传入 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_tensors="pt", padding=True, ) { '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] ]) } 截断片段令牌,使序列长度不超过最大长度。设置 truncation=True 并指定 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_tensors="pt", padding=True, truncation=True, max_length=5 ) { '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,请设置 task="text-generation" 和 model="google/gemma-2-2b" from transformers import pipeline pipeline = pipeline(task="text-generation", model="google/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(task="automatic-speech-recognition", model="openai/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(task="image-classification", model="google/vit-base-patch16-224") pipeline(images="https://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(task="visual-question-answering", model="Salesforce/blip-vqa-base") pipeline( image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg", question="What is in the image?", ) [{'answer': 'statue of liberty'}]

Parameters[参数]:

Device:Pipeline 兼容多种硬件类型,包括 GPU、CPU、Apple Silicon 等。通过设备参数配置硬件类型。默认情况下,若未设置设备,则 Pipeline 会自动将模型部署在第一个可用的加速器上(CUDA GPU、Apple Silicon MPS、XPU 等),当没有可用加速器时才回退到 CPU。使用 pass device="cpu" 可强制模型在 CPU 上运行。 from transformers import pipeline pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device=0) 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(task="text-generation", model="google/gemma-2-2b", device=device, batch_size=2) 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 API

1.1文本生成

​ 文本生成是大语言模型(LLM)最广泛的应用场景。LLM 在训练过程中,会根据给定的初始文本(提示)以及自身生成的输出,在预设长度内或到达结束标记(EOS)时,生成下一个词(token)。在 Transformers 中,generate() API 用于文本生成,适用于所有具备生成能力的模型。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询