-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathjupyter_main.py
379 lines (314 loc) Β· 12 KB
/
jupyter_main.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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import torch
from torch.utils.data import DataLoader # λ°μ΄ν°λ‘λ
from gluonnlp.data import SentencepieceTokenizer
from kogpt2.utils import get_tokenizer
from kogpt2.utils import download, tokenizer
from kogpt2.model.torch_gpt2 import GPT2Config, GPT2LMHeadModel
from kogpt2.data import Read_Dataset
import gluonnlp
from kogpt2.model.sample import sample_sequence
from tqdm import tqdm
import subprocess
from tensorboardX import SummaryWriter
import re
import copy
import logging
import dropbox.files
import os
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
import os
import sys
#λλ‘ λ°μ€λ₯Ό μ΄μ©νκΈ° μν΄μ μ°λ μ½λ λλ‘λ°μ€ 2Tλ₯Ό μ°κΈ° μν΄μ μ μΈ
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
my_drive = GoogleDrive(gauth)
# κ°μμ λλ‘λ°μ€ key μ
λ ₯
FORUS_AI_RESOURCES_APP_ACCESS_TOKEN = ''
logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d:%H:%M:%S',
level=logging.WARNING)
logger = logging.getLogger(__name__)
dbx = dropbox.Dropbox(FORUS_AI_RESOURCES_APP_ACCESS_TOKEN)
def auto_enter(text):
text = text.replace(" ", "\n")
text = text.split("\n")
text = [t.lstrip() for t in text if t != '']
text = "\n\n".join(text)
text = text.replace(" ", "")
return text
def get_gpu_memory_map():
"""Get the current gpu usage.
Returns
-------
usage: dict
Keys are device ids as integers.
Values are memory usage as integers in MB.
"""
result = subprocess.check_output(
[
'nvidia-smi', '--query-gpu=memory.used',
'--format=csv,nounits,noheader'
], encoding='utf-8')
# Convert lines into a dictionary
gpu_memory = [int(x) for x in result.strip().split('\n')]
gpu_memory_map = dict(zip(range(len(gpu_memory)), gpu_memory))
return gpu_memory_map
def main(epoch = 200, save_path = './checkpoint/', load_path = './checkpoint/KoGPT2_checkpoint_long.tar',
data_file_path = 'dataset/lyrics_dataset.txt',
batch_size = 8, summary_url = 'runs/', new = 0, text_size = 100):
ctx = 'cuda'
cachedir = '~/kogpt2/'
summary = SummaryWriter(summary_url)
pytorch_kogpt2 = {
'url': 'https://kobert.blob.core.windows.net/models/kogpt2/pytorch/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
}
# 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)
# KoGPT-2 μΈμ΄ λͺ¨λΈ νμ΅μ μν GPT2LMHeadModel μ μΈ
kogpt2model = GPT2LMHeadModel(config=GPT2Config.from_dict(kogpt2_config))
# model_path λ‘λΆν° λ€μ΄λ‘λ λ°μ λ΄μ©μ load_state_dict μΌλ‘ μ
λ‘λ
# κΈ°λ³Έ λͺ¨λΈμμ κ°μ Έμ€λ νλΌλ―Έν° μ
λ°μ΄νΈ
kogpt2model.load_state_dict(torch.load(model_path))
device = torch.device(ctx) #GPU
kogpt2model.to(device)
count = 0
# 체ν¬ν¬μΈνΈμμ λΆλ¬μ€κΈ° λΆλΆ
try:
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()
except:
print("count 0 : ", load_path)
else:
print("count check : ",re.findall("\d+", load_path))
count = max([int(i) for i in (re.findall("\d+", load_path))])
if new:
count = 0
# μΆκ°λ‘ νμ΅νκΈ° μν΄ .train() μ¬μ©
kogpt2model.train()
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
sentencepieceTokenizer = SentencepieceTokenizer(tok_path)
# μ°λ¦¬μ λ°μ΄ν°μ
λΆλ¬μ€λ λΆλΆ
dataset = Read_Dataset(data_file_path, vocab, sentencepieceTokenizer)
data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, pin_memory=True)
# 체ν¬
learning_rate = 3e-5
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
model = model.to(ctx)
# bpeλ‘ ν λ λλκ³ ν©μΉκ³ νλ κ³Όμ μ΄ νΈν΄μ§.
tok = SentencepieceTokenizer(tok_path)
print('KoGPT-2 Transfer Learning Start')
# μ₯λ₯΄λ³λ‘ 체ν¬ν¬μΈνΈ ν΄λ μμΌλ©΄ μμ±νκΈ°
try:
if not(os.path.isdir(save_path + data_file_path.split("/")[-1][:-4])):
os.makedirs(os.path.join(save_path + data_file_path.split("/")[-1][:-4]))
except OSError as e:
if e.errno != errno.EEXIST:
print("Failed to create directory!!!!!")
raise
avg_loss = (0.0, 0.0)
for epoch in range(epoch):
# λ°μ΄ν°μ
κ°μ Έμμ νμ΅ μμ
for datas in data_loader:
data = datas[0]
optimizer.zero_grad()
data = torch.stack(data) # list of Tensorλ‘ κ΅¬μ±λμ΄ μκΈ° λλ¬Έμ listλ₯Ό stackμ ν΅ν΄ λ³νν΄μ€λ€.
data = data.transpose(1,0)
data = data.to(ctx)
model = model.to(ctx)
# μ€μ νμ΅
outputs = model(data, labels=data)
loss, logits = outputs[:2]
nowloss = copy.copy(loss)
# νκ· loss λ§λ€κΈ° avg_loss[0] / avg_loss[1] <- loss μ κ·ν
avg_loss = (avg_loss[0] * 0.99 + loss, avg_loss[1] * 0.99 + 1.0)
loss *= datas[2][0] # νΉλ³ socre λΆλΆ
loss = loss.to(ctx)
loss.backward()
# νμ΅ λ
optimizer.step()
if count % 10 == 0:
print('epoch no.{0} train no.{1} loss = {2:.5f} avg_loss = {3:.5f}' . format(epoch, count, loss, avg_loss[0] / avg_loss[1]))
summary.add_scalar('loss/avg_loss', avg_loss[0] / avg_loss[1], count)
summary.add_scalar('loss/loss', loss, count)
# print("save")
# torch.save({
# 'epoch': epoch,
# 'train_no': count,
# 'model_state_dict': model.state_dict(),
# 'optimizer_state_dict': optimizer.state_dict(),
# 'loss': loss
# }, save_path + 'KoGPT2_checkpoint_' + str(count) + '.tar')
#generator μ§ν
if (count > 0 and count % 2500 == 0):
sent = sample_sequence(model.to("cpu"), tok, vocab, sent="κ°", text_size=text_size, temperature=0.7, top_p=0.9, top_k=100)
sent = sent.replace("//", "\n") # λΉν¨μ¨μ μ΄μ§λ§ μν°λ₯Ό μν΄μ λ±μ₯
sent = auto_enter(sent)
print(sent)
summary.add_text('Text', sent, count)
del sent
pass
#########################################
if (count > 0 and count % 10000 == 0):
print("λͺ¨λΈμ μ μ₯ν©λλ€.")
# λͺ¨λΈ μ μ₯
try:
torch.save({
'epoch': epoch,
'train_no': count,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss
}, save_path + data_file_path.split("/")[-1][:-4] + '/' + 'KoGPT2_checkpoint_' + str(count) + '.tar')
#print("λ¬Έμ μμ")
# λλ‘λ°μ€μ μ μ₯
large_file = open(save_path + data_file_path.split("/")[-1][:-4] + '/' + 'KoGPT2_checkpoint_' + str(count) + '.tar', 'rb')
names = 'KoGPT2_checkpoint_' + str(count) + '.tar'
# μ₯λ₯΄/체ν¬ν¬μΈνΈ λΆλΆμΌλ‘ μ μ₯
large_file_path = '/' + data_file_path.split("/")[-1][:-4] + '/' + names
#print("λ¬Έμ μμ2")
CHUNK_SIZE = 1024 * 1024 * 150
chunk = large_file.read(CHUNK_SIZE)
session_info = dbx.files_upload_session_start(chunk)
cursor = dropbox.files.UploadSessionCursor(
session_id=session_info.session_id,
offset=large_file.tell(),
)
print("λ¬Έμ μμ3")
# λ¨μ μ²ν¬λ€ μ
λ‘λμ© loop
while True:
chunk = large_file.read(CHUNK_SIZE)
if not chunk:
dbx.files_upload_session_finish(
b'',
dropbox.files.UploadSessionCursor(
session_id=session_info.session_id,
offset=large_file.tell(),
),
dropbox.files.CommitInfo(
large_file_path,
dropbox.files.WriteMode('add'),
),
)
break
else:
# μ²ν¬ λΆν ν λ¨μ λ°μ΄ν° appending
dbx.files_upload_session_append_v2(chunk, cursor)
cursor.offset = large_file.tell()
logger.warning('νμ΅ν λͺ¨λΈ νμΌ μ
λ‘λ μλ£')
#print("λ¬Έμ μμ4")
# μ‘μΈμ€ ν ν° ν΄λ λ΄ μ‘΄μ¬νλ ν΄λ/νμΌ μΆλ ₯
logger.warning('λμ©λ νμΌ μ
λ‘λ ν ν΄λ/νμΌ λͺ©λ‘:')
for entry in dbx.files_list_folder('').entries:
logger.warning("\t" + entry.name)
# νμΌ μμ
#print("λ¬Έμ μμ5")
os.remove(save_path + data_file_path.split("/")[-1][:-4] + '/' + 'KoGPT2_checkpoint_' + str(count) + '.tar')
# ν΄μ§ν΅ λΉμ°κΈ°
#print("λ¬Έμ μμ6")
logging.getLogger('googleapiclient.discovery').setLevel(logging.CRITICAL)
for a_file in my_drive.ListFile({'q': "trashed = true"}).GetList():
a_file.Delete()
except:
pass
if avg_loss[0] / avg_loss[1] < 1.0:
print("νμ΅μ΄ λλ¬μ΄μ©!!")
print("λͺ¨λΈμ μ μ₯ν©λλ€.")
# λͺ¨λΈ μ μ₯
#try:
torch.save({
'epoch': epoch,
'train_no': count,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss
}, save_path + data_file_path.split("/")[-1][:-4] + '/' + 'KoGPT2_checkpoint_' + str(count) + '.tar')
#print("λ¬Έμ μμ")
# λλ‘λ°μ€μ μ μ₯
large_file = open(save_path + data_file_path.split("/")[-1][:-4] + '/' + 'KoGPT2_checkpoint_' + str(count) + '.tar', 'rb')
names = 'KoGPT2_checkpoint_' + str(count) + '.tar'
# μ₯λ₯΄/체ν¬ν¬μΈνΈ λΆλΆμΌλ‘ μ μ₯
large_file_path = '/' + data_file_path.split("/")[-1][:-4] + '/' + names
#print("λ¬Έμ μμ2")
CHUNK_SIZE = 1024 * 1024 * 150
chunk = large_file.read(CHUNK_SIZE)
session_info = dbx.files_upload_session_start(chunk)
cursor = dropbox.files.UploadSessionCursor(
session_id=session_info.session_id,
offset=large_file.tell(),
)
print("λ¬Έμ μμ3")
# λ¨μ μ²ν¬λ€ μ
λ‘λμ© loop
while True:
chunk = large_file.read(CHUNK_SIZE)
if not chunk:
dbx.files_upload_session_finish(
b'',
dropbox.files.UploadSessionCursor(
session_id=session_info.session_id,
offset=large_file.tell(),
),
dropbox.files.CommitInfo(
large_file_path,
dropbox.files.WriteMode('add'),
),
)
break
else:
# μ²ν¬ λΆν ν λ¨μ λ°μ΄ν° appending
dbx.files_upload_session_append_v2(chunk, cursor)
cursor.offset = large_file.tell()
logger.warning('νμ΅ν λͺ¨λΈ νμΌ μ
λ‘λ μλ£')
#print("λ¬Έμ μμ4")
# μ‘μΈμ€ ν ν° ν΄λ λ΄ μ‘΄μ¬νλ ν΄λ/νμΌ μΆλ ₯
logger.warning('λμ©λ νμΌ μ
λ‘λ ν ν΄λ/νμΌ λͺ©λ‘:')
for entry in dbx.files_list_folder('').entries:
logger.warning("\t" + entry.name)
# νμΌ μμ
#print("λ¬Έμ μμ5")
os.remove(save_path + data_file_path.split("/")[-1][:-4] + '/' + 'KoGPT2_checkpoint_' + str(count) + '.tar')
# ν΄μ§ν΅ λΉμ°κΈ°
#print("λ¬Έμ μμ6")
logging.getLogger('googleapiclient.discovery').setLevel(logging.CRITICAL)
for a_file in my_drive.ListFile({'q': "trashed = true"}).GetList():
a_file.Delete()
return
count += 1