Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
'''
|
3 |
+
saved_models文件夹包含两个文件:
|
4 |
+
1).在原有bert-base-chinese基础上fine-tune的pytorch_model.bin
|
5 |
+
2).配置文件config.json,和原有bert-base-chinese的配置文件一样
|
6 |
+
'''
|
7 |
+
|
8 |
+
import sys
|
9 |
+
sys.path.append(r'./4-5.Bert-seq2seq/')
|
10 |
+
import torch
|
11 |
+
import torch.nn.functional as F
|
12 |
+
import numpy as np
|
13 |
+
from model import BertForSeq2Seq
|
14 |
+
from tokenizer import Tokenizer
|
15 |
+
|
16 |
+
def top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):
|
17 |
+
""" Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
|
18 |
+
Args:
|
19 |
+
logits: logits distribution shape (vocabulary size)
|
20 |
+
top_k > 0: keep only top k tokens with highest probability (top-k filtering).
|
21 |
+
top_p > 0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).
|
22 |
+
Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)
|
23 |
+
From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317
|
24 |
+
"""
|
25 |
+
assert logits.dim() == 1 # batch size 1 for now - could be updated for more but the code would be less clear
|
26 |
+
top_k = min(top_k, logits.size(-1)) # Safety check
|
27 |
+
if top_k > 0:
|
28 |
+
# Remove all tokens with a probability less than the last token of the top-k
|
29 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
30 |
+
logits[indices_to_remove] = filter_value
|
31 |
+
|
32 |
+
if top_p > 0.0:
|
33 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
34 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
35 |
+
|
36 |
+
# Remove tokens with cumulative probability above the threshold
|
37 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
38 |
+
# Shift the indices to the right to keep also the first token above the threshold
|
39 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
40 |
+
sorted_indices_to_remove[..., 0] = 0
|
41 |
+
|
42 |
+
indices_to_remove = sorted_indices[sorted_indices_to_remove]
|
43 |
+
logits[indices_to_remove] = filter_value
|
44 |
+
return logits
|
45 |
+
|
46 |
+
def sample_generate(text, model_path, out_max_length=40, top_k=30, top_p=0.0, max_length=512):
|
47 |
+
device = "cuda" if torch.cuda.is_available() else 'cpu'
|
48 |
+
|
49 |
+
model = BertForSeq2Seq.from_pretrained(model_path)
|
50 |
+
model.to(device)
|
51 |
+
model.eval()
|
52 |
+
|
53 |
+
input_max_length = max_length - out_max_length
|
54 |
+
input_ids, token_type_ids, token_type_ids_for_mask, labels = Tokenizer.encode(text, max_length=input_max_length)
|
55 |
+
|
56 |
+
input_ids = torch.tensor(input_ids, device=device, dtype=torch.long).view(1, -1)
|
57 |
+
token_type_ids = torch.tensor(token_type_ids, device=device, dtype=torch.long).view(1, -1)
|
58 |
+
token_type_ids_for_mask = torch.tensor(token_type_ids_for_mask, device=device, dtype=torch.long).view(1, -1)
|
59 |
+
#print(input_ids, token_type_ids, token_type_ids_for_mask)
|
60 |
+
output_ids = []
|
61 |
+
|
62 |
+
with torch.no_grad():
|
63 |
+
for step in range(out_max_length):
|
64 |
+
scores = model(input_ids, token_type_ids, token_type_ids_for_mask)
|
65 |
+
logit_score = torch.log_softmax(scores[:, -1], dim=-1).squeeze(0)
|
66 |
+
logit_score[Tokenizer.unk_id] = -float('Inf')
|
67 |
+
|
68 |
+
# 对于已生成的结果generated中的每个token添加一个重复惩罚项,降低其生成概率
|
69 |
+
for id_ in set(output_ids):
|
70 |
+
logit_score[id_] /= 1.5
|
71 |
+
|
72 |
+
filtered_logits = top_k_top_p_filtering(logit_score, top_k=top_k, top_p=top_p)
|
73 |
+
next_token = torch.multinomial(F.softmax(filtered_logits, dim=-1), num_samples=1)
|
74 |
+
if Tokenizer.sep_id == next_token.item():
|
75 |
+
break
|
76 |
+
output_ids.append(next_token.item())
|
77 |
+
input_ids = torch.cat((input_ids, next_token.long().unsqueeze(0)), dim=1)
|
78 |
+
token_type_ids = torch.cat([token_type_ids, torch.ones((1, 1), device=device, dtype=torch.long)], dim=1)
|
79 |
+
token_type_ids_for_mask = torch.cat([token_type_ids_for_mask, torch.zeros((1, 1), device=device, dtype=torch.long)], dim=1)
|
80 |
+
#print(input_ids, token_type_ids, token_type_ids_for_mask)
|
81 |
+
|
82 |
+
|
83 |
+
return Tokenizer.decode(np.array(output_ids))
|
84 |
+
|
85 |
+
import gradio as gr
|
86 |
+
def greet(a):
|
87 |
+
summary = sample_generate(text=a,model_path='/hy-tmp/4-5.Bert-seq2seq/saved_models',top_k=5,top_p=0.95)
|
88 |
+
return summary
|
89 |
+
demo=gr.Interface(fn=greet,inputs="text",outputs="text")
|
90 |
+
demo.launch(share=True)
|
91 |
+
|
92 |
+
|
93 |
+
|
94 |
+
|
95 |
+
'''while 1:
|
96 |
+
a=input('请输入需要提取的新闻段落')
|
97 |
+
summary = sample_generate(text=a,model_path='/hy-tmp/4-5.Bert-seq2seq/saved_models',top_k=5,top_p=0.95)
|
98 |
+
print(summary)
|
99 |
+
|
100 |
+
|
101 |
+
|
102 |
+
|