乐趣区

关于人工智能:Python文本生成的Beam-Search解码

贪心搜寻是在每个工夫步中抉择概率最高的单词,也是咱们最罕用的一种办法,Beam Search 不取每个标记自身的相对概率,而是思考每个标记的所有可能扩大。而后依据其对数概率抉择最合适的标记序列。

例如令牌的概率如下所示:

例如,Pancakes + looks 时间段 1 的概率等效于:

Pancakes looks so = log(0.2)+ log(0.7)= -1.9
Pancakes looks fluffy  = log(0.2)+ log(0.3)= -2.8

所以咱们须要定义一个函数来实现整句的概率计算:

import torch.nn.functional as F
def log_probability_single(logits, labels):
    logp = F.log_softmax(logits, dim=-1)
    logp_label = torch.gather(logp, 2, labels.unsqueeze(2)).squeeze(-1)
    return logp_label
def sentence_logprob(model, labels, input_len=0):
    with torch.no_grad():
        result = model(labels)
        log_probability = log_probability_single(result.logits[:, :-1, :],
                                                 labels[:, 1:])
    sentence_log_prob = torch.sum(log_probability[:, input_len:])
    return sentence_log_prob.cpu().numpy()

接下来,能够将其利用于贪心搜寻解码办法生成的输入,并计算生成的序列的对数概率。

在此示例中,我将在村上春木的书中简要介绍:1Q84。

input_sentence = "A love story, a mystery, a fantasy, a novel of self-discovery, a dystopia to rival George Orwell’s — 1Q84 is Haruki Murakami’s most ambitious undertaking yet: an instant best seller in his native Japan, and a tremendous feat of imagination from one of our most revered contemporary writers."

max_sequence = 100
input_ids = tokenizer(input_sentence,
                      return_tensors='pt')['input_ids'].to(device)
output = model.generate(input_ids, max_length=max_sequence, do_sample=False)

greedy_search_output = sentence_logprob(model,
                                        output,
                                        input_len=len(input_ids[0]))
print(tokenizer.decode(output[0]))

咱们能够看到生成的序列的对数概率为 -52.31。

当初,咱们将并比拟通过 Beam Search 生成的序列的对数概率得分,得分越高潜在后果越好。

咱们能够减少 n -gram 惩办参数 no_repeat_ngram_size,这有助于缩小输入中的反复生成的序列。

beam_search_output = model.generate(input_ids,
                                    max_length=max_sequence,
                                    num_beams=5,
                                    do_sample=False,
                                    no_repeat_ngram_size=2)
beam_search_log_prob = sentence_logprob(model,
                                        beam_search_output,
                                        input_len=len(input_ids[0]))
print(tokenizer.decode(beam_search_output[0]))
print(f"\nlog_prob: {beam_search_log_prob:.2f}")

输入如下:

分时和连贯性要比贪心的办法好很多,对吧。

https://avoid.overfit.cn/post/ba2eb47bb35d43d99fb58333d37f13cb

作者:Jason LZP

退出移动版