-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrainer.py
More file actions
149 lines (127 loc) · 7 KB
/
trainer.py
File metadata and controls
149 lines (127 loc) · 7 KB
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
import torch
from torch import nn
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau
from tqdm import tqdm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
class Trainer():
def __init__(self,
model,
device,
noise_schedule=lambda t: (1 - 2e-5) * (1 - t**2) + 1e-5,
lr=1.0e-3,
n_epoch=1000,
save_model=20,
save_path='output'):
self.model = model.to(device)
self.device = device
self.optimizer = Adam(model.parameters(), lr=lr)
self.scheduler = ReduceLROnPlateau(self.optimizer, verbose=True)
self.n_epoch = n_epoch
self.loss_func = nn.MSELoss()
self.noise_schedule = noise_schedule # alpha(t)
self.save_model = save_model
i = 1
while True:
if f'train_{i:02}' in os.listdir(save_path):
i += 1
else:
self.save_path = f'{save_path}/train_{i:02}'
os.mkdir(self.save_path)
break
self.loss_log = {'epoch':[], 'train': [], 'val':[]}
def train(self, train_dataloader, val_dataloader):
self.model.eval()
val_loss = []
for batch_data in iter(val_dataloader):
batch_X = batch_data['X'].to(self.device) # coordinates, (n_batch, n_atom, 3)
batch_Z = batch_data['Z'].to(self.device) # atom types, (n_batch, n_atom, n_atomtype)
batch_K1 = batch_data['K1'].to(self.device) # node masks, (n_batch, n_atom, 1)
batch_K2 = batch_data['K2'].to(self.device) # node masks, (n_batch, n_atom, n_atom)
n_batch = batch_X.shape[0]
n_atom = batch_X.shape[1]
n_atomfeat = batch_Z.shape[2]
batch_t = torch.rand(1, device=self.device).tile((n_batch, n_atom, 1))
batch_alpha = self.noise_schedule(batch_t) # alpha(t), weight of data
batch_sigma = torch.sqrt(1 - batch_alpha**2) # sigma(t), weight of noise
batch_epsilon = torch.randn((n_batch, n_atom, 3+n_atomfeat), device=self.device) * batch_K1 # noise
batch_X = batch_alpha * batch_X + batch_sigma * batch_epsilon[:, :, 0:3]
batch_Z = batch_alpha * batch_Z + batch_sigma * batch_epsilon[:, :, 3:3+n_atomfeat]
with torch.no_grad():
pred_epsilon = torch.cat(self.model.forward(batch_X, batch_Z, batch_K1, batch_K2, batch_t), dim=2)
loss = self.loss_func(pred_epsilon, batch_epsilon)
val_loss.append(loss.item())
val_loss = np.mean(val_loss)
print(f'No train - Val loss: {val_loss:.3f}')
for epoch in tqdm(range(self.n_epoch)):
self.model.train()
train_loss = []
for batch_data in iter(train_dataloader):
batch_X = batch_data['X'].to(self.device) # coordinates, (n_batch, n_atom, 3)
batch_Z = batch_data['Z'].to(self.device) # atom types, (n_batch, n_atom, n_atomtype)
batch_K1 = batch_data['K1'].to(self.device) # node masks, (n_batch, n_atom, 1)
batch_K2 = batch_data['K2'].to(self.device) # node masks, (n_batch, n_atom, n_atom)
n_batch = batch_X.shape[0]
n_atom = batch_X.shape[1]
n_atomfeat = batch_Z.shape[2]
batch_t = torch.rand(1, device=self.device).tile((n_batch, n_atom, 1))
batch_alpha = self.noise_schedule(batch_t) # alpha(t), weight of data
batch_sigma = torch.sqrt(1 - batch_alpha**2) # sigma(t), weight of noise
batch_epsilon = torch.randn((n_batch, n_atom, 3+n_atomfeat), device=self.device) * batch_K1 # noise
batch_X = batch_alpha * batch_X + batch_sigma * batch_epsilon[:, :, 0:3]
batch_Z = batch_alpha * batch_Z + batch_sigma * batch_epsilon[:, :, 3:3+n_atomfeat]
try:
pred_epsilon = torch.cat(self.model.forward(batch_X, batch_Z, batch_K1, batch_K2, batch_t), dim=2)
loss = self.loss_func(pred_epsilon, batch_epsilon)
self.optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=1.0, error_if_nonfinite=True)
self.optimizer.step()
train_loss.append(loss.item())
except:
print('RuntimeError: The total norm for gradients is non-finite, so it cannot be clipped.')
train_loss = np.mean(train_loss)
self.model.eval()
val_loss = []
for batch_data in iter(val_dataloader):
batch_X = batch_data['X'].to(self.device) # coordinates, (n_batch, n_atom, 3)
batch_Z = batch_data['Z'].to(self.device) # atom types, (n_batch, n_atom, n_atomtype)
batch_K1 = batch_data['K1'].to(self.device) # node masks, (n_batch, n_atom, 1)
batch_K2 = batch_data['K2'].to(self.device) # node masks, (n_batch, n_atom, n_atom)
n_batch = batch_X.shape[0]
n_atom = batch_X.shape[1]
n_atomfeat = batch_Z.shape[2]
batch_t = torch.rand(1, device=self.device).tile((n_batch, n_atom, 1))
batch_alpha = self.noise_schedule(batch_t) # alpha(t), weight of data
batch_sigma = torch.sqrt(1 - batch_alpha**2) # sigma(t), weight of noise
batch_epsilon = torch.randn((n_batch, n_atom, 3+n_atomfeat), device=self.device) * batch_K1 # noise
batch_X = batch_alpha * batch_X + batch_sigma * batch_epsilon[:, :, 0:3]
batch_Z = batch_alpha * batch_Z + batch_sigma * batch_epsilon[:, :, 3:3+n_atomfeat]
with torch.no_grad():
pred_epsilon = torch.cat(self.model.forward(batch_X, batch_Z, batch_K1, batch_K2, batch_t), dim=2)
loss = self.loss_func(pred_epsilon, batch_epsilon)
val_loss.append(loss.item())
val_loss = np.mean(val_loss)
print(f'Train loss: {train_loss:.3f} - Val loss: {val_loss:.3f}')
self.loss_log['epoch'].append(epoch+1)
self.loss_log['train'].append(train_loss)
self.loss_log['val'].append(val_loss)
if (epoch+1)%self.save_model==0:
torch.save(self.model.state_dict(), f'{self.save_path}/model.pt')
self.record_loss()
self.scheduler.step(val_loss)
def record_loss(self):
df = pd.DataFrame(self.loss_log)
df.to_csv(f'{self.save_path}/log.csv', index=False)
plt.figure()
plt.plot(self.loss_log['epoch'], self.loss_log['train'])
plt.plot(self.loss_log['epoch'], self.loss_log['val'])
plt.legend(['Training', 'Validation'])
plt.xlabel('Epoch')
plt.ylabel('MSE loss')
# plt.yscale('log')
plt.savefig(f'{self.save_path}/log.svg')
plt.close()