chenjg commited on
Commit
d7a8568
1 Parent(s): 08e90d5

add app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -0
app.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Hugging Face's logo
2
+ Hugging Face
3
+ Search models, datasets, users...
4
+ Models
5
+ Datasets
6
+ Spaces
7
+ Docs
8
+ Solutions
9
+ Pricing
10
+
11
+
12
+
13
+ Spaces:
14
+
15
+ lewiswu1209
16
+ /
17
+ gpt2-chinese-couplet Copied
18
+ like
19
+ 0
20
+ App
21
+ Files and versions
22
+ Community
23
+ gpt2-chinese-couplet
24
+ /
25
+ app.py
26
+ lewiswu1209's picture
27
+ lewiswu1209
28
+ initial commit
29
+ 147e546
30
+ 19 days ago
31
+ raw
32
+ history
33
+ blame
34
+ contribute
35
+ delete
36
+ Safe
37
+ 2.07 kB
38
+
39
+ import torch
40
+
41
+ import gradio as gr
42
+ import torch.nn.functional as F
43
+
44
+ from transformers import BertTokenizer, GPT2LMHeadModel
45
+
46
+ tokenizer = BertTokenizer.from_pretrained("uer/gpt2-chinese-couplet")
47
+ model = GPT2LMHeadModel.from_pretrained("uer/gpt2-chinese-couplet")
48
+ model.eval()
49
+
50
+ def top_k_top_p_filtering( logits, top_k=0, top_p=0.0, filter_value=-float('Inf') ):
51
+ assert logits.dim() == 1
52
+ top_k = min( top_k, logits.size(-1) )
53
+ if top_k > 0:
54
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
55
+ logits[indices_to_remove] = filter_value
56
+ if top_p > 0.0:
57
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
58
+ cumulative_probs = torch.cumsum( F.softmax(sorted_logits, dim=-1), dim=-1 )
59
+ sorted_indices_to_remove = cumulative_probs > top_p
60
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
61
+ sorted_indices_to_remove[..., 0] = 0
62
+ indices_to_remove = sorted_indices[sorted_indices_to_remove]
63
+ logits[indices_to_remove] = filter_value
64
+ return logits
65
+
66
+ def generate(input_text):
67
+ input_ids = [tokenizer.cls_token_id]
68
+ input_ids.extend( tokenizer.encode(input_text + "-", add_special_tokens=False) )
69
+ input_ids = torch.tensor( [input_ids] )
70
+
71
+ generated = []
72
+ for _ in range(100):
73
+ output = model(input_ids)
74
+
75
+ next_token_logits = output.logits[0, -1, :]
76
+ next_token_logits[ tokenizer.convert_tokens_to_ids('[UNK]') ] = -float('Inf')
77
+ filtered_logits = top_k_top_p_filtering(next_token_logits, top_k=8, top_p=1)
78
+ next_token = torch.multinomial( F.softmax(filtered_logits, dim=-1), num_samples=1 )
79
+ if next_token == tokenizer.sep_token_id:
80
+ break
81
+ generated.append( next_token.item() )
82
+ input_ids = torch.cat( (input_ids, next_token.unsqueeze(0)), dim=1 )
83
+
84
+ return "".join( tokenizer.convert_ids_to_tokens(generated) )
85
+
86
+ if __name__ == "__main__":
87
+
88
+ gr.Interface(
89
+ fn=generate,
90
+ inputs="text",
91
+ outputs="text"
92
+ ).launch()
93
+