🚀 LONGFORMER-BASE-4096在SQuAD v1上微调
这是一个在SQuAD v1数据集上针对问答任务进行微调的longformer-base-4096模型。该模型能够有效处理问答场景,为长文本问答提供了强大的支持。
数据集
许可证
🚀 快速开始
本模型是基于Transformer架构的问答模型,可用于处理长文本的问答任务。以下是使用该模型的示例代码:
import torch
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
tokenizer = AutoTokenizer.from_pretrained("valhalla/longformer-base-4096-finetuned-squadv1")
model = AutoModelForQuestionAnswering.from_pretrained("valhalla/longformer-base-4096-finetuned-squadv1")
text = "Huggingface has democratized NLP. Huge thanks to Huggingface for this."
question = "What has Huggingface done ?"
encoding = tokenizer(question, text, return_tensors="pt")
input_ids = encoding["input_ids"]
attention_mask = encoding["attention_mask"]
start_scores, end_scores = model(input_ids, attention_mask=attention_mask)
all_tokens = tokenizer.convert_ids_to_tokens(input_ids[0].tolist())
answer_tokens = all_tokens[torch.argmax(start_scores) :torch.argmax(end_scores)+1]
answer = tokenizer.decode(tokenizer.convert_tokens_to_ids(answer_tokens))
目前,LongformerForQuestionAnswering
还不支持 pipeline
。待支持添加后,我会更新此文档。
✨ 主要特性
- 长文本处理能力:预训练模型可以处理长达4096个标记的序列,适合处理长文档问答。
- 自动处理全局注意力:
LongformerForQuestionAnswering
模型会自动为问题标记设置全局注意力。
📦 安装指南
文档未提及安装步骤,故跳过此章节。
💻 使用示例
基础用法
import torch
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
tokenizer = AutoTokenizer.from_pretrained("valhalla/longformer-base-4096-finetuned-squadv1")
model = AutoModelForQuestionAnswering.from_pretrained("valhalla/longformer-base-4096-finetuned-squadv1")
text = "Huggingface has democratized NLP. Huge thanks to Huggingface for this."
question = "What has Huggingface done ?"
encoding = tokenizer(question, text, return_tensors="pt")
input_ids = encoding["input_ids"]
attention_mask = encoding["attention_mask"]
start_scores, end_scores = model(input_ids, attention_mask=attention_mask)
all_tokens = tokenizer.convert_ids_to_tokens(input_ids[0].tolist())
answer_tokens = all_tokens[torch.argmax(start_scores) :torch.argmax(end_scores)+1]
answer = tokenizer.decode(tokenizer.convert_tokens_to_ids(answer_tokens))
高级用法
文档未提及高级用法代码示例,故跳过此部分。
📚 详细文档
模型介绍
Longformer 模型由AllenAI的Iz Beltagy、Matthew E. Peters和Arman Coha创建。正如论文中所解释的,Longformer
是一个用于长文档的类BERT模型。
模型训练
此模型在Google Colab的v100 GPU上进行训练。你可以通过以下链接找到微调的Colab笔记本
。
在为问答任务训练Longformer时,需要注意以下几点:
默认情况下,Longformer对所有标记使用滑动窗口局部注意力。但对于问答任务,所有问题标记都应该具有全局注意力。LongformerForQuestionAnswering
模型会自动为你完成此操作。为了让它能够正常工作:
- 输入序列必须有三个分隔标记,即序列应该按照以下方式编码:
<s> question</s></s> context</s>
。如果你将问题和答案作为输入对进行编码,那么分词器会自动处理这个问题,你无需担心。
input_ids
应该始终是一批示例。
模型效果
指标 |
值 |
精确匹配 |
85.1466 |
F1值 |
91.5415 |
🔧 技术细节
输入序列要求
输入序列必须有三个分隔标记,编码格式为 <s> question</s></s> context</s>
。若将问题和答案作为输入对编码,分词器会自动处理。
全局注意力设置
LongformerForQuestionAnswering
模型会自动为问题标记设置全局注意力。
输入批次要求
input_ids
必须是一批示例。
📄 许可证
本项目采用MIT许可证。
由Suraj Patil ❤️ 创建
