如何使用 BERT/GPT-2 生成释义

Taz*_*lam 4 nlp gpt-2

我正在努力理解如何使用 BERT/GPT-2 进行释义生成。我不明白我该怎么做。您能为我提供任何可以制作释义生成模型的资源吗? “输入是一个句子,输出是该句子的释义”

Dav*_*ale 8

这是我训练释义者的秘诀:

  1. 使用同时具有编码器和解码器的 seq2seq 模型,例如 T5、BART 或 Pegasus,而不是 BERT(仅编码器)或 GPT(仅解码器)。我建议使用 针对 101 种语言进行过预训练的多语言 T5 模型。如果您想加载您自己语言的嵌入(而不是使用全部 101 个),您可以按照此配方进行操作。

  2. 找到适合您的语言和领域的释义语料库。对于英语,ParaNMT、PAWS 和 QQP 都是不错的选择。从 Tatoeba 中提取的一个名为Tapaco的语料库是一个涵盖 73 种语言的释义语料库,因此如果您无法找到适合您的语言的释义语料库,那么这是一个很好的起点。

  3. 在此语料库上微调您的模型。代码可以是这样的:

import torch
from transformers import T5ForConditionalGeneration, T5Tokenizer
# use here a backbone model of your choice, e.g. google/mt5-base
backbone_model = 'cointegrated/rut5-base-multitask' 
model = T5ForConditionalGeneration.from_pretrained(backbone_model)
tokenizer = T5Tokenizer.from_pretrained(backbone_model)
model.cuda();
optimizer = torch.optim.Adam(params=[p for p in model.parameters() if p.requires_grad], lr=1e-5)

# todo: load the paraphrasing corpus and define the get_batch function

for i in range(100500):
    xx, yy = get_batch(mult=mult)
    x = tokenizer(xx, return_tensors='pt', padding=True).to(model.device)
    y = tokenizer(yy, return_tensors='pt', padding=True).to(model.device)
    # do not force the model to predict pad tokens
    y.input_ids[y.input_ids==0] = -100
    loss = model(
        input_ids=x.input_ids,
        attention_mask=x.attention_mask,
        labels=y.input_ids,
        decoder_attention_mask=y.attention_mask,
        return_dict=True
    ).loss
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

model.save_pretrained('my_paraphraser')
tokenizer.save_pretrained('my_paraphraser')
Run Code Online (Sandbox Code Playgroud)

可以在此笔记本中找到此代码的更完整版本。

训练完成后,模型可以通过以下方式使用:

from transformers import pipeline
pipe = pipeline(task='text2text-generation', model='my_paraphraser')
print(pipe('Here is your text'))
# [{'generated_text': 'Here is the paraphrase or your text.'}]
Run Code Online (Sandbox Code Playgroud)

如果您希望释义更加多样化,您可以使用以下参数控制生成过程:

print(pipe(
    'Here is your text', 
    encoder_no_repeat_ngram_size=3,  # make output different from input
    do_sample=True,  # randomize
    num_beams=5,  # try more options
    max_length=128,  # longer texts
))
Run Code Online (Sandbox Code Playgroud)

享受!