-
Notifications
You must be signed in to change notification settings - Fork 0
/
GPT_trainer_accuracy.py
373 lines (319 loc) · 15.3 KB
/
GPT_trainer_accuracy.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
"""
The MIT License (MIT) Copyright (c) 2020 Andrej Karpathy
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
"""
Simple training loop; Boilerplate that could apply to any arbitrary neural network,
so nothing in this file really has anything to do with GPT specifically.
"""
import math
import logging
import torch.nn as nn
from tqdm import tqdm
import numpy as np
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data.dataloader import DataLoader
logger = logging.getLogger(__name__)
from CasualGPT.utils import sample
import atari_py
from collections import deque
import random
import cv2
import torch
from PIL import Image
from CasualGPT.gpu_mem_track import MemTracker
import inspect
import time
class TrainerConfig:
# optimization parameters
max_epochs = 10
batch_size = 64
learning_rate = 3e-4
betas = (0.9, 0.95)
grad_norm_clip = 1.0
weight_decay = 0.1 # only applied on matmul weights
# learning rate decay params: linear warmup followed by cosine decay to 10% of original
lr_decay = False
warmup_tokens = 375e6 # these two numbers come from the GPT-3 paper, but may not be good defaults elsewhere
final_tokens = 260e9 # (at what point we reach 10% of original LR)
# checkpoint settings
ckpt_path = None
num_workers = 0 # for DataLoader
def __init__(self, **kwargs):
for k,v in kwargs.items():
setattr(self, k, v)
def get_parameter_number(net):
total_num = sum(p.numel() for p in net.parameters())
trainable_num = sum(p.numel() for p in net.parameters() if p.requires_grad)
return {'Total': total_num, 'Trainable': trainable_num}
class Trainer:
def __init__(self, model, train_dataset, test_dataset, config):
self.model = model
# self.model_simu = model_simu
self.train_dataset = train_dataset
self.test_dataset = test_dataset
self.config = config
# take over whatever gpus are on the system
self.device = 'cpu'
if torch.cuda.is_available():
#self.device = torch.cuda.current_device()
self.device = 'cuda:0'
#self.device = 'cpu'
self.model = self.model.to(self.device)
#model = nn.DataParallel(model)
def save_checkpoint(self):
# DataParallel wrappers keep raw model object in .module attribute
raw_model = self.model.module if hasattr(self.model, "module") else self.model
logger.info("saving %s", self.config.ckpt_path)
# torch.save(raw_model.state_dict(), self.config.ckpt_path)
def train(self):
model, config = self.model, self.config
raw_model = model.module if hasattr(self.model, "module") else model
optimizer = raw_model.configure_optimizers(config)
def evaluator(rankedlist, testlist,k):
data_shape=rankedlist.shape # (batch_size,block_size,voc_size)
Hits_i = 0
Len_R = 0
Len_T = data_shape[0]
MRR_i = 0
HR_i = 0
NDCG_i = 0
for i in range(data_shape[0]):
rec_list=rankedlist[i,-1,:]
values,topk_index=rec_list.topk(k, largest=True, sorted=True)
topk_index=list(topk_index)
for p in range(k):
if testlist[i,-1,0]==topk_index[p]:
Hits_i+=1
HR_i+=1
# 注意j的取值从0开始
MRR_i+=1/(p+1)
NDCG_i+=1/(math.log2(1+p+1))
break
HR_i/=Len_T
MRR_i/=Len_T
NDCG_i/=Len_T
return MRR_i, HR_i, NDCG_i
def run_epoch(split, epoch_num=0):
is_train = split == 'train'
model.train(is_train)
# model_simu.train(is_train)
data = self.train_dataset if is_train else self.test_dataset
loader = DataLoader(data, shuffle=True, pin_memory=True,
batch_size=config.batch_size,
num_workers=config.num_workers)
losses = []
scores = []
rouge_scores = []
hrs = []
ndcgs = []
recalls = []
precisions = []
return_total=[]
pbar = tqdm(enumerate(loader), total=len(loader)) if is_train else enumerate(loader)
# frame=inspect.currentframe()
# gpu_tracker=MemTracker(frame)
gpu_tracker=MemTracker()
for it, (x, y, y_neg, y_len, r_step, r, t) in pbar:
x = x.to(self.device)
y = y.to(self.device)
y_neg = y_neg.to(self.device)
r = r.to(self.device)
t = t.to(self.device)
y_len = y_len.to(self.device)
r_step = r_step.to(self.device)
# forward the model
MRR=[]
HR=[]
NDCG=[]
if is_train:
with torch.set_grad_enabled(is_train):
logits, loss = model(x, y, y_neg, y_len, y, r, r_step, t)
losses.append(loss.item())
if not is_train:
with torch.set_grad_enabled(is_train):
score, rouge_score, hr_score, ndcg_score, precision = model.predict_seq2seq(x, y, y_len, y, r,r_step, t, 20, self.device)
scores.append(score)
rouge_scores.append(rouge_score)
hrs.append(hr_score)
ndcgs.append(ndcg_score)
precisions.append(precision)
if is_train:
model.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), config.grad_norm_clip)
optimizer.step()
# decay the learning rate based on our progress
if config.lr_decay:
self.tokens += (y >= 0).sum() # number of tokens processed this step (i.e. label is not -100)
if self.tokens < config.warmup_tokens:
# linear warmup
lr_mult = float(self.tokens) / float(max(1, config.warmup_tokens))
else:
# cosine learning rate decay
progress = float(self.tokens - config.warmup_tokens) / float(max(1, config.final_tokens - config.warmup_tokens))
lr_mult = max(0.1, 0.5 * (1.0 + math.cos(math.pi * progress)))
lr = config.learning_rate * lr_mult
for param_group in optimizer.param_groups:
param_group['lr'] = lr
else:
lr = config.learning_rate
# report progress
# pbar.set_description(f"epoch {epoch+1} iter {it}: train loss {loss.item():.5f} MRR{topk} {MRR_batch:.5f} HR{topk} {HR_batch:.5f} NDCG{topk} {NDCG_batch:.5f}. lr {lr:e}")
pbar.set_description(f"epoch {epoch+1} iter {it}: train loss {loss.item():.5f}. lr {lr:e}")
if not is_train:
scores=sum(scores)/len(scores)
rouge_scores=sum(rouge_scores)/len(rouge_scores)
hrs=sum(hrs)/len(hrs)
ndcgs=sum(ndcgs)/len(ndcgs)
precisions=sum(precisions)/len(precisions)
print('bleu score is:',scores)
print('rouge score is:',rouge_scores)
print('hr is:',hrs)
print('NDCG is:',ndcgs)
print('CTR Precision is:',precisions)
# return test_loss
# Rec accuracy eval
best_loss = float('inf')
best_return = -float('inf')
self.tokens = 0 # counter used for learning rate decay
for epoch in range(config.max_epochs):
run_epoch('train', epoch_num=epoch)
if self.test_dataset is not None:
time1=time.time()
# test_loss = run_epoch('test')
run_epoch('test')
time2=time.time()
print(time2-time1)
def get_returns(self, ret):
self.model.train(False)
args=Args(self.config.game.lower(), self.config.seed)
env = Env(args)
env.eval()
T_rewards, T_Qs = [], []
done = True
for i in range(10):
state = env.reset()
state = state.type(torch.float32).to(self.device).unsqueeze(0).unsqueeze(0)
rtgs = [ret]
# first state is from env, first rtg is target return, and first timestep is 0
sampled_action = sample(self.model.module, state, 1, temperature=1.0, sample=True, actions=None,
rtgs=torch.tensor(rtgs, dtype=torch.long).to(self.device).unsqueeze(0).unsqueeze(-1),
timesteps=torch.zeros((1, 1, 1), dtype=torch.int64).to(self.device))
j = 0
all_states = state
actions = []
while True:
if done:
state, reward_sum, done = env.reset(), 0, False
action = sampled_action.cpu().numpy()[0,-1]
actions += [sampled_action]
state, reward, done = env.step(action)
reward_sum += reward
j += 1
if done:
T_rewards.append(reward_sum)
break
state = state.unsqueeze(0).unsqueeze(0).to(self.device)
all_states = torch.cat([all_states, state], dim=0)
rtgs += [rtgs[-1] - reward]
# all_states has all previous states and rtgs has all previous rtgs (will be cut to block_size in utils.sample)
# timestep is just current timestep
sampled_action = sample(self.model.module, all_states.unsqueeze(0), 1, temperature=1.0, sample=True,
actions=torch.tensor(actions, dtype=torch.long).to(self.device).unsqueeze(1).unsqueeze(0),
rtgs=torch.tensor(rtgs, dtype=torch.long).to(self.device).unsqueeze(0).unsqueeze(-1),
timesteps=(min(j, self.config.max_timestep) * torch.ones((1, 1, 1), dtype=torch.int64).to(self.device)))
env.close()
eval_return = sum(T_rewards)/10.
print("target return: %d, eval return: %d" % (ret, eval_return))
self.model.train(True)
return eval_return
class Env():
def __init__(self, args):
self.device = args.device
self.ale = atari_py.ALEInterface()
self.ale.setInt('random_seed', args.seed)
self.ale.setInt('max_num_frames_per_episode', args.max_episode_length)
self.ale.setFloat('repeat_action_probability', 0) # Disable sticky actions
self.ale.setInt('frame_skip', 0)
self.ale.setBool('color_averaging', False)
self.ale.loadROM(atari_py.get_game_path(args.game)) # ROM loading must be done after setting options
actions = self.ale.getMinimalActionSet()
self.actions = dict([i, e] for i, e in zip(range(len(actions)), actions))
self.lives = 0 # Life counter (used in DeepMind training)
self.life_termination = False # Used to check if resetting only from loss of life
self.window = args.history_length # Number of frames to concatenate
self.state_buffer = deque([], maxlen=args.history_length)
self.training = True # Consistent with model training mode
def _get_state(self):
state = cv2.resize(self.ale.getScreenGrayscale(), (84, 84), interpolation=cv2.INTER_LINEAR)
return torch.tensor(state, dtype=torch.float32, device=self.device).div_(255)
def _reset_buffer(self):
for _ in range(self.window):
self.state_buffer.append(torch.zeros(84, 84, device=self.device))
def reset(self):
if self.life_termination:
self.life_termination = False # Reset flag
self.ale.act(0) # Use a no-op after loss of life
else:
# Reset internals
self._reset_buffer()
self.ale.reset_game()
# Perform up to 30 random no-ops before starting
for _ in range(random.randrange(30)):
self.ale.act(0) # Assumes raw action 0 is always no-op
if self.ale.game_over():
self.ale.reset_game()
# Process and return "initial" state
observation = self._get_state()
self.state_buffer.append(observation)
self.lives = self.ale.lives()
return torch.stack(list(self.state_buffer), 0)
def step(self, action):
# Repeat action 4 times, max pool over last 2 frames
frame_buffer = torch.zeros(2, 84, 84, device=self.device)
reward, done = 0, False
for t in range(4):
reward += self.ale.act(self.actions.get(action))
if t == 2:
frame_buffer[0] = self._get_state()
elif t == 3:
frame_buffer[1] = self._get_state()
done = self.ale.game_over()
if done:
break
observation = frame_buffer.max(0)[0]
self.state_buffer.append(observation)
# Detect loss of life as terminal in training mode
if self.training:
lives = self.ale.lives()
if lives < self.lives and lives > 0: # Lives > 0 for Q*bert
self.life_termination = not done # Only set flag when not truly done
done = True
self.lives = lives
# Return state, reward, done
return torch.stack(list(self.state_buffer), 0), reward, done
# Uses loss of life as terminal signal
def train(self):
self.training = True
# Uses standard terminal signal
def eval(self):
self.training = False
def action_space(self):
return len(self.actions)
def render(self):
cv2.imshow('screen', self.ale.getScreenRGB()[:, :, ::-1])
cv2.waitKey(1)
def close(self):
cv2.destroyAllWindows()
class Args:
def __init__(self, game, seed):
self.device = torch.device('cuda')
self.seed = seed
self.max_episode_length = 108e3
self.game = game
self.history_length = 4