ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Transformers 文本摘要实战指南:基于 BillSum 数据集微调 T5 模型与推理部署

Transformers 文本摘要实战指南:基于 BillSum 数据集微调 T5 模型与推理部署 Transformers 文本摘要实战指南基于 BillSum 数据集微调 T5 模型与推理部署【免费下载链接】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摘要Summarization是自然语言处理中的核心任务之一它从长文档或文章中提炼出保留全部关键信息的短版本。在 Transformers 生态中摘要任务通常被建模为序列到序列sequence-to-sequenceseq2seq问题与机器翻译同属一类。本文以日文版官方任务文档 docs/source/ja/tasks/summarization.md 为主体结合当前仓库源码完整讲解如何利用 T5 在 BillSum 数据集的加州法案子集上微调抽象式摘要模型并给出从环境准备、数据加载、预处理、评估到训练与推理的端到端方案。读完本文你将掌握用Trainer/Seq2SeqTrainer微调 seq2seq 模型的标准流程以及用pipeline与model.generate()两种方式部署摘要模型。摘要任务的两种形态摘要任务可按生成方式分为两类抽取式Extractive直接从原文中挑选最具相关性的句子或片段进行拼接不产生新的表述。抽象式Abstractive理解原文语义后生成全新的、概括性的文本通常更贴近人类写作也是本文 T5 微调方案所针对的目标。在 T5 这类文本到文本统一架构中摘要与翻译一样被当作标准的 seq2seq 任务处理编码器读取长文本解码器自回归地生成短摘要。环境准备与前置依赖开始之前需要安装以下 Python 库pip install transformers datasets evaluate rouge_score各库职责如下transformers模型架构、Trainer训练框架与推理组件对应本仓库 src/transformersdatasets加载与预处理 BillSum 数据集evaluate加载并计算 ROUGE 指标rouge_scoreROUGE 指标的后端计算依赖基于 Google Research 的 rouge-score 实现。如需把模型上传到 Hugging Face Hub 与社区共享建议先登录账号按提示输入 token from huggingface_hub import notebook_login notebook_login()加载 BillSum 数据集使用 Datasets 加载 BillSum 数据集中较小的加州法案子集ca_test划分 from datasets import load_dataset billsum load_dataset(billsum, splitca_test)再用train_test_split方法按 20% 比例切分出训练集与测试集 billsum billsum.train_test_split(test_size0.2)查看一条样本观察数据结构 billsum[train][0] {summary: Existing law authorizes state agencies to enter into contracts for the acquisition of goods or services upon approval by the Department of General Services. ..., text: The people of the State of California do enact as follows:\n\n\nSECTION 1.\nSection 10295.35 is added to the Public Contract Code, to read:\n..., title: An act to add Section 10295.35 to the Public Contract Code, relating to public contracts.}样本中真正用于训练的两个字段是text法案正文作为模型的输入summarytext的浓缩版本作为模型的目标label。title字段在本流程中不使用。预处理提示词前缀与标签编码加载 T5 分词器 from transformers import AutoTokenizer checkpoint google-t5/t5-small tokenizer AutoTokenizer.from_pretrained(checkpoint)预处理函数需要完成三件事加任务前缀在输入前拼接summarize: 让 T5 识别当前是摘要任务。T5 支持多任务不同任务依赖不同的提示词来触发对应能力用text_target编码标签编码目标文本时使用text_target关键字参数而不是重复传入inputs截断序列通过max_length限制序列长度防止超出模型上下文。 prefix summarize: def preprocess_function(examples): ... inputs [prefix doc for doc in examples[text]] ... model_inputs tokenizer(inputs, max_length1024, truncationTrue) ... labels tokenizer(text_targetexamples[summary], max_length128, truncationTrue) ... model_inputs[labels] labels[input_ids] ... return model_inputs将预处理函数应用到整个数据集batchedTrue可一次处理多个样本以加速map tokenized_billsum billsum.map(preprocess_function, batchedTrue)动态填充DataCollatorForSeq2Seq直接用DataCollatorForSeq2Seq组装批次。它的核心价值是动态填充dynamic padding在 collation 阶段把同批样本填充到该批最长长度而非把整个数据集统一填充到最大长度从而显著减少无效计算与显存占用。 from transformers import DataCollatorForSeq2Seq data_collator DataCollatorForSeq2Seq(tokenizertokenizer, modelcheckpoint)从源码 src/transformers/data/data_collator.py 可以看到其内部实现逻辑输入部分交由 tokenizer 按paddingTrue即longest策略填充标签部分手动填充由于标签的填充符必须是-100PyTorch 损失函数会自动忽略该值无法直接复用 tokenizer 的 pad token因此 DataCollatorForSeq2Seq 将每个标签补齐到批内最大长度并用label_pad_token_id-100填充若传入的模型实现了prepare_decoder_input_ids_from_labels还会自动生成decoder_input_ids避免重复计算 decoder 输入——这对开启label_smoothing的训练尤其有用。T5 恰好实现了该方法modeling_t5.py其内部调用_shift_right(labels)将标签右移一位并填充起始 token从而构造解码器的自回归输入。评估用 ROUGE 衡量摘要质量训练过程中引入指标有助于评估模型表现。使用 Evaluate 库快速加载 ROUGE import evaluate rouge evaluate.load(rouge)编写compute_metrics函数将预测与标签解码为文本后计算 ROUGE import numpy as np def compute_metrics(eval_pred): ... predictions, labels eval_pred ... decoded_preds tokenizer.batch_decode(predictions, skip_special_tokensTrue) ... labels np.where(labels ! -100, labels, tokenizer.pad_token_id) ... decoded_labels tokenizer.batch_decode(labels, skip_special_tokensTrue) ... result rouge.compute(predictionsdecoded_preds, referencesdecoded_labels, use_stemmerTrue) ... prediction_lens [np.count_nonzero(pred ! tokenizer.pad_token_id) for pred in predictions] ... result[gen_len] np.mean(prediction_lens) ... return {k: round(v, 4) for k, v in result.items()}该函数的关键细节用skip_special_tokensTrue解码剔除pad、eos等特殊 token将标签中的-100替换为tokenizer.pad_token_id否则这些占位符会被解码成无意义 token污染指标use_stemmerTrue启用词干还原使 ROUGE 能匹配同词根变体如 running/run额外统计gen_len生成平均长度方便观察摘要长度是否符合预期。ROUGE 家族包含 ROUGE-1、ROUGE-2、ROUGE-L 等子指标分别衡量单字unigram、双字bigram与最长公共子序列层面的 n-gram 重叠度是摘要与机器翻译领域的事实标准。训练Seq2SeqTrainer 微调 T5先用AutoModelForSeq2SeqLM加载 T5 模型 from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer model AutoModelForSeq2SeqLM.from_pretrained(checkpoint)随后只需三步在Seq2SeqTrainingArguments中定义训练超参数唯一必填项是output_dir把训练参数连同模型、数据集、分词器、数据整理器与compute_metrics一起传给Seq2SeqTrainer调用trainer.train()开始微调。 training_args Seq2SeqTrainingArguments( ... output_dirmy_awesome_billsum_model, ... eval_strategyepoch, ... learning_rate2e-5, ... per_device_train_batch_size16, ... per_device_eval_batch_size16, ... weight_decay0.01, ... save_total_limit3, ... num_train_epochs4, ... predict_with_generateTrue, ... fp16True, # 在 XPU 设备上请改为 bf16True ... push_to_hubTrue, ... ) trainer Seq2SeqTrainer( ... modelmodel, ... argstraining_args, ... train_datasettokenized_billsum[train], ... eval_datasettokenized_billsum[test], ... processing_classtokenizer, ... data_collatordata_collator, ... compute_metricscompute_metrics, ... ) trainer.train()各超参数含义与取值参考参数值说明output_dirmy_awesome_billsum_model模型保存目录必填eval_strategyepoch每个 epoch 结束时评估一次并保存 checkpointlearning_rate2e-5Adam 优化器初始学习率微调场景常用 1e-55e-5per_device_train/eval_batch_size16每设备批大小需根据显存调整weight_decay0.01L2 权重衰减系数save_total_limit3最多保留 3 个 checkpoint防止磁盘占满num_train_epochs4训练轮数predict_with_generateTrue评估时用generate生成摘要来计算 ROUGE/BLEU 等生成式指标关键fp16/bf16True混合精度加速XPU 设备改用bf16True关于predict_with_generate从 training_args_seq2seq.py 的源码可知该参数决定评估阶段是否调用生成接口来计算生成式指标同时配套提供generation_max_length默认取模型配置的max_length与generation_num_beams默认取模型配置的num_beams两个可选参数用于精细控制评估时的解码策略此外还支持通过generation_config直接传入一个GenerationConfig对象或路径。训练完成后的显式解码参数如max_new_tokens仅影响推理不影响训练。训练结束后用push_to_hub把模型共享到 Hub trainer.push_to_hub()进阶示例脚本若想深入完整流程可参考仓库自带的 examples/pytorch/summarization 目录run_summarization.py基于Seq2SeqTrainer的完整训练脚本支持从命令行传入模型名、数据集名、--max_source_length、--max_target_length、--num_beams、--source_prefix等参数run_summarization_no_trainer.py不依赖Trainer、使用原生 PyTorch 训练循环的版本README.md两种脚本的详细参数说明与用法示例requirements.txt脚本运行所需依赖。推理两种部署方式微调完成后即可用于推理。准备一段待摘要文本——注意 T5 的输入同样需要summarize: 前缀 text summarize: The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. Its the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country. Itll lower the deficit and ask the ultra-wealthy and corporations to pay their fair share. And no one making under $400,000 per year will pay a penny more in taxes.方式一pipeline 一行推理将微调后的模型封装进摘要pipeline将stevhliu/my_awesome_billsum_model替换为你自己的模型仓库名 from transformers import pipeline summarizer pipeline(summarization, modelstevhliu/my_awesome_billsum_model) summarizer(text) [{summary_text: The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. Its the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country.}]pipeline内部自动完成了分词、生成与解码的完整链路适合快速验证与轻量部署。方式二手动调用 generate需要细粒度控制生成行为时可手动完成分词 → 生成 → 解码三步。先分词并返回 PyTorch 张量 from transformers import AutoTokenizer tokenizer AutoTokenizer.from_pretrained(stevhliu/my_awesome_billsum_model) inputs tokenizer(text, return_tensorspt).input_ids再调用model.generate生成摘要max_new_tokens100限制新增 token 数do_sampleFalse使用贪心解码 from transformers import AutoModelForSeq2SeqLM model AutoModelForSeq2SeqLM.from_pretrained(stevhliu/my_awesome_billsum_model) outputs model.generate(inputs, max_new_tokens100, do_sampleFalse)最后把生成的 token id 解码回文本 tokenizer.decode(outputs[0], skip_special_tokensTrue) the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. its the most aggressive action on tackling the climate crisis in american history. it will ask the ultra-wealthy and corporations to pay their fair share.generate背后是仓库 src/transformers/generation 模块实现的GenerationMixin支持贪心、束搜索beam search、采样sampling、对比搜索等丰富解码策略调整num_beams、temperature、top_k、top_p等参数可改变生成质量与多样性具体可参考仓库中的文本生成 API 文档 docs/source/en/main_classes/text_generation.md。小结本文以 BillSum 加州法案子集为例走通了数据加载 → 前缀与标签预处理 → 动态填充 → ROUGE 评估 →Seq2SeqTrainer微调 →pipeline/generate推理的完整摘要模型落地链路。核心要点可概括为摘要可划分为抽取式与抽象式T5 方案将抽象式摘要建模为 seq2seq 生成任务T5 等多任务模型要求输入带任务前缀summarize: 标签用text_target编码DataCollatorForSeq2Seq以-100填充标签并自动生成decoder_input_ids兼顾效率与正确性predict_with_generateTrue是让评估阶段真正生成摘要并计算 ROUGE 的关键开关推理既可用pipeline快速落地也可用model.generate()获得细粒度控制。【免费下载链接】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),仅供参考
返回列表