-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathgenerator.py
153 lines (128 loc) ยท 4.34 KB
/
generator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import os
import torch
from gluonnlp.data import SentencepieceTokenizer
from kogpt2.model.sample import sample_sequence
from kogpt2.utils import get_tokenizer
from kogpt2.utils import download, tokenizer
from kogpt2.model.torch_gpt2 import GPT2Config, GPT2LMHeadModel
import gluonnlp
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--temperature', type=float, default=0.7,
help="temperature ๋ฅผ ํตํด์ ๊ธ์ ์ฐฝ์์ฑ์ ์กฐ์ ํฉ๋๋ค.")
parser.add_argument('--top_p', type=float, default=0.9,
help="top_p ๋ฅผ ํตํด์ ๊ธ์ ํํ ๋ฒ์๋ฅผ ์กฐ์ ํฉ๋๋ค.")
parser.add_argument('--top_k', type=int, default=40,
help="top_k ๋ฅผ ํตํด์ ๊ธ์ ํํ ๋ฒ์๋ฅผ ์กฐ์ ํฉ๋๋ค.")
parser.add_argument('--text_size', type=int, default=250,
help="๊ฒฐ๊ณผ๋ฌผ์ ๊ธธ์ด๋ฅผ ์กฐ์ ํฉ๋๋ค.")
parser.add_argument('--loops', type=int, default=-1,
help="๊ธ์ ๋ช ๋ฒ ๋ฐ๋ณตํ ์ง ์ง์ ํฉ๋๋ค. -1์ ๋ฌดํ๋ฐ๋ณต์
๋๋ค.")
parser.add_argument('--tmp_sent', type=str, default="์ฌ๋",
help="๊ธ์ ์์ ๋ฌธ์ฅ์
๋๋ค.")
parser.add_argument('--load_path', type=str, default="./checkpoint/ent/KoGPT2_checkpoint_37000.tar",
help="ํ์ต๋ ๊ฒฐ๊ณผ๋ฌผ์ ์ ์ฅํ๋ ๊ฒฝ๋ก์
๋๋ค.")
args = parser.parse_args()
pytorch_kogpt2 = {
'url':
'checkpoint/pytorch_kogpt2_676e9bcfa7.params',
'fname': 'pytorch_kogpt2_676e9bcfa7.params',
'chksum': '676e9bcfa7'
}
kogpt2_config = {
"initializer_range": 0.02,
"layer_norm_epsilon": 1e-05,
"n_ctx": 1024,
"n_embd": 768,
"n_head": 12,
"n_layer": 12,
"n_positions": 1024,
"vocab_size": 50000
}
def auto_enter(text):
text = (text.replace(" ", "\n"))
text = text.split("\n")
text = [t.lstrip() for t in text if t != '']
return "\n\n".join(text)
def main(temperature = 0.7, top_p = 0.8, top_k = 40, tmp_sent = "", text_size = 100, loops = 0, load_path = ""):
ctx = 'cuda'
cachedir = '~/kogpt2/'
save_path = './checkpoint/'
# download model
model_info = pytorch_kogpt2
model_path = download(model_info['url'],
model_info['fname'],
model_info['chksum'],
cachedir=cachedir)
# download vocab
vocab_info = tokenizer
vocab_path = download(vocab_info['url'],
vocab_info['fname'],
vocab_info['chksum'],
cachedir=cachedir)
# Device ์ค์
device = torch.device(ctx)
# ์ ์ฅํ Checkpoint ๋ถ๋ฌ์ค๊ธฐ
checkpoint = torch.load(load_path, map_location=device)
# KoGPT-2 ์ธ์ด ๋ชจ๋ธ ํ์ต์ ์ํ GPT2LMHeadModel ์ ์ธ
kogpt2model = GPT2LMHeadModel(config=GPT2Config.from_dict(kogpt2_config))
kogpt2model.load_state_dict(checkpoint['model_state_dict'])
kogpt2model.eval()
vocab_b_obj = gluonnlp.vocab.BERTVocab.from_sentencepiece(vocab_path,
mask_token=None,
sep_token=None,
cls_token=None,
unknown_token='<unk>',
padding_token='<pad>',
bos_token='<s>',
eos_token='</s>')
tok_path = get_tokenizer()
model, vocab = kogpt2model, vocab_b_obj
tok = SentencepieceTokenizer(tok_path)
if loops:
num = 1
else:
num = 0
try:
load_path.split("/")[-2]
except:
pass
else:
load_path = load_path.split("/")[-2]
print("ok : ",load_path)
if not(os.path.isdir("samples/"+ load_path)):
os.makedirs(os.path.join("samples/"+ load_path))
while 1:
sent =''
if tmp_sent == "":
tmp_sent = input('input : ')
sent = sent+tmp_sent
toked = tok(sent)
if len(toked) > 1022:
break
sent = sample_sequence(model, tok, vocab, sent, text_size, temperature, top_p, top_k)
sent = sent.replace("//", "\n") # ๋นํจ์จ์ ์ด์ง๋ง ์ํฐ๋ฅผ ์ํด์ ๋ฑ์ฅ
sent = sent.replace("</s>", "")
sent = auto_enter(sent)
print(sent)
now = [int(n) for n in os.listdir("./samples/" + load_path)]
try:
now = max(now)
except:
now = 1
f = open("samples/"+ load_path + "/" + str(now + 1), 'w', encoding="utf-8")
head = [load_path, tmp_sent, text_size, temperature, top_p, top_k]
head = [str(h) for h in head]
f.write(",".join(head))
f.write(",")
f.write(sent)
f.close()
#tmp_sent = ""
if num != 0:
num += 1
if num >= loops:
print("good")
return
if __name__ == "__main__":
# execute only if run as a script
main(temperature=args.temperature, top_p=args.top_p, top_k=args.top_k, tmp_sent=args.tmp_sent, text_size=args.text_size, loops=args.loops+1, load_path=args.load_path)