main.py 9.74 KB
Newer Older
1
import copy
2
3
4
from pathlib import Path

import click
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5
6

import dgl
7
8
9
10
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
11
import torch.optim as optim
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
12
from dgl.data.utils import Subset
13
from logzero import logger
14
15
16
17
from modules.dimenet import DimeNet
from modules.dimenet_pp import DimeNetPP
from modules.initializers import GlorotOrthogonal
from qm9 import QM9
18
from ruamel.yaml import YAML
19
from sklearn.metrics import mean_absolute_error
20
from torch.utils.data import DataLoader
21
22
23
24
25


def split_dataset(
    dataset, num_train, num_valid, shuffle=False, random_state=None
):
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
    """Split dataset into training, validation and test set.

    Parameters
    ----------
    dataset
        We assume that ``len(dataset)`` gives the number of datapoints and ``dataset[i]``
        gives the ith datapoint.
    num_train : int
        Number of training datapoints.
    num_valid : int
        Number of validation datapoints.
    shuffle : bool, optional
        By default we perform a consecutive split of the dataset. If True,
        we will first randomly shuffle the dataset.
    random_state : None, int or array_like, optional
        Random seed used to initialize the pseudo-random number generator.
        This can be any integer between 0 and 2^32 - 1 inclusive, an array
        (or other sequence) of such integers, or None (the default value).
        If seed is None, then RandomState will try to read data from /dev/urandom
        (or the Windows analogue) if available or seed from the clock otherwise.

    Returns
    -------
    list of length 3
        Subsets for training, validation and test.
    """
    from itertools import accumulate
53

54
55
56
57
58
59
60
    num_data = len(dataset)
    assert num_train + num_valid < num_data
    lengths = [num_train, num_valid, num_data - num_train - num_valid]
    if shuffle:
        indices = np.random.RandomState(seed=random_state).permutation(num_data)
    else:
        indices = np.arange(num_data)
61
62
63
64
65
    return [
        Subset(dataset, indices[offset - length : offset])
        for offset, length in zip(accumulate(lengths), lengths)
    ]

66
67
68
69
70
71

@torch.no_grad()
def ema(ema_model, model, decay):
    msd = model.state_dict()
    for k, ema_v in ema_model.state_dict().items():
        model_v = msd[k].detach()
72
73
        ema_v.copy_(ema_v * decay + (1.0 - decay) * model_v)

74
75

def edge_init(edges):
76
    R_src, R_dst = edges.src["R"], edges.dst["R"]
77
78
    dist = torch.sqrt(F.relu(torch.sum((R_src - R_dst) ** 2, -1)))
    # d: bond length, o: bond orientation
79
80
    return {"d": dist, "o": R_src - R_dst}

81
82
83
84
85
86
87

def _collate_fn(batch):
    graphs, line_graphs, labels = map(list, zip(*batch))
    g, l_g = dgl.batch(graphs), dgl.batch(line_graphs)
    labels = torch.tensor(labels, dtype=torch.float32)
    return g, l_g, labels

88

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
def train(device, model, opt, loss_fn, train_loader):
    model.train()
    epoch_loss = 0
    num_samples = 0

    for g, l_g, labels in train_loader:
        g = g.to(device)
        l_g = l_g.to(device)
        labels = labels.to(device)
        logits = model(g, l_g)
        loss = loss_fn(logits, labels.view([-1, 1]))
        epoch_loss += loss.data.item() * len(labels)
        num_samples += len(labels)
        opt.zero_grad()
        loss.backward()
        opt.step()

    return epoch_loss / num_samples

108

109
110
111
112
@torch.no_grad()
def evaluate(device, model, valid_loader):
    model.eval()
    predictions_all, labels_all = [], []
113

114
115
116
117
118
    for g, l_g, labels in valid_loader:
        g = g.to(device)
        l_g = l_g.to(device)
        logits = model(g, l_g)
        labels_all.extend(labels)
119
120
121
122
123
124
125
126
        predictions_all.extend(
            logits.view(
                -1,
            )
            .cpu()
            .numpy()
        )

127
128
    return np.array(predictions_all), np.array(labels_all)

129

130
@click.command()
131
132
133
134
135
136
@click.option(
    "-m",
    "--model-cnf",
    type=click.Path(exists=True),
    help="Path of model config yaml.",
)
137
def main(model_cnf):
138
    yaml = YAML(typ="safe")
139
    model_cnf = yaml.load(Path(model_cnf))
140
141
142
143
144
145
146
147
148
    model_name, model_params, train_params, pretrain_params = (
        model_cnf["name"],
        model_cnf["model"],
        model_cnf["train"],
        model_cnf["pretrain"],
    )
    logger.info(f"Model name: {model_name}")
    logger.info(f"Model params: {model_params}")
    logger.info(f"Train params: {train_params}")
149

150
151
    if model_params["targets"] in ["mu", "homo", "lumo", "gap", "zpve"]:
        model_params["output_init"] = nn.init.zeros_
152
153
    else:
        # 'GlorotOrthogonal' for alpha, R2, U0, U, H, G, and Cv
154
        model_params["output_init"] = GlorotOrthogonal
155

156
157
    logger.info("Loading Data Set")
    dataset = QM9(label_keys=model_params["targets"], edge_funcs=[edge_init])
158
159

    # data split
160
161
162
163
164
165
166
167
168
169
    train_data, valid_data, test_data = split_dataset(
        dataset,
        num_train=train_params["num_train"],
        num_valid=train_params["num_valid"],
        shuffle=True,
        random_state=train_params["data_seed"],
    )
    logger.info(f"Size of Training Set: {len(train_data)}")
    logger.info(f"Size of Validation Set: {len(valid_data)}")
    logger.info(f"Size of Test Set: {len(test_data)}")
170
171

    # data loader
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
    train_loader = DataLoader(
        train_data,
        batch_size=train_params["batch_size"],
        shuffle=True,
        collate_fn=_collate_fn,
        num_workers=train_params["num_workers"],
    )

    valid_loader = DataLoader(
        valid_data,
        batch_size=train_params["batch_size"],
        shuffle=False,
        collate_fn=_collate_fn,
        num_workers=train_params["num_workers"],
    )

    test_loader = DataLoader(
        test_data,
        batch_size=train_params["batch_size"],
        shuffle=False,
        collate_fn=_collate_fn,
        num_workers=train_params["num_workers"],
    )
195
196

    # check cuda
197
198
    gpu = train_params["gpu"]
    device = f"cuda:{gpu}" if gpu >= 0 and torch.cuda.is_available() else "cpu"
199
200

    # model initialization
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
    logger.info("Loading Model")
    if model_name == "dimenet":
        model = DimeNet(
            emb_size=model_params["emb_size"],
            num_blocks=model_params["num_blocks"],
            num_bilinear=model_params["num_bilinear"],
            num_spherical=model_params["num_spherical"],
            num_radial=model_params["num_radial"],
            cutoff=model_params["cutoff"],
            envelope_exponent=model_params["envelope_exponent"],
            num_before_skip=model_params["num_before_skip"],
            num_after_skip=model_params["num_after_skip"],
            num_dense_output=model_params["num_dense_output"],
            num_targets=len(model_params["targets"]),
            output_init=model_params["output_init"],
        ).to(device)
    elif model_name == "dimenet++":
        model = DimeNetPP(
            emb_size=model_params["emb_size"],
            out_emb_size=model_params["out_emb_size"],
            int_emb_size=model_params["int_emb_size"],
            basis_emb_size=model_params["basis_emb_size"],
            num_blocks=model_params["num_blocks"],
            num_spherical=model_params["num_spherical"],
            num_radial=model_params["num_radial"],
            cutoff=model_params["cutoff"],
            envelope_exponent=model_params["envelope_exponent"],
            num_before_skip=model_params["num_before_skip"],
            num_after_skip=model_params["num_after_skip"],
            num_dense_output=model_params["num_dense_output"],
            num_targets=len(model_params["targets"]),
            extensive=model_params["extensive"],
            output_init=model_params["output_init"],
        ).to(device)
235
    else:
236
        raise ValueError(f"Invalid Model Name {model_name}")
237

238
239
240
241
    if pretrain_params["flag"]:
        torch_path = pretrain_params["path"]
        target = model_params["targets"][0]
        model.load_state_dict(torch.load(f"{torch_path}/{target}.pt"))
242

243
        logger.info("Testing with Pretrained model")
244
245
        predictions, labels = evaluate(device, model, test_loader)
        test_mae = mean_absolute_error(labels, predictions)
246
        logger.info(f"Test MAE {test_mae:.4f}")
247
248
249
250

        return
    # define loss function and optimization
    loss_fn = nn.L1Loss()
251
252
253
254
255
256
257
258
259
    opt = optim.Adam(
        model.parameters(),
        lr=train_params["lr"],
        weight_decay=train_params["weight_decay"],
        amsgrad=True,
    )
    scheduler = optim.lr_scheduler.StepLR(
        opt, train_params["step_size"], gamma=train_params["gamma"]
    )
260
261
262
263

    # model training
    best_mae = 1e9
    no_improvement = 0
264

265
    # EMA for valid and test
266
    logger.info("EMA Init")
267
268
269
    ema_model = copy.deepcopy(model)
    for p in ema_model.parameters():
        p.requires_grad_(False)
270

271
272
    best_model = copy.deepcopy(ema_model)

273
274
    logger.info("Training")
    for i in range(train_params["epochs"]):
275
        train_loss = train(device, model, opt, loss_fn, train_loader)
276
277
        ema(ema_model, model, train_params["ema_decay"])
        if i % train_params["interval"] == 0:
278
279
280
            predictions, labels = evaluate(device, ema_model, valid_loader)

            valid_mae = mean_absolute_error(labels, predictions)
281
282
283
            logger.info(
                f"Epoch {i} | Train Loss {train_loss:.4f} | Val MAE {valid_mae:.4f}"
            )
284
285
286

            if valid_mae > best_mae:
                no_improvement += 1
287
288
                if no_improvement == train_params["early_stopping"]:
                    logger.info("Early stop.")
289
290
291
292
293
294
                    break
            else:
                no_improvement = 0
                best_mae = valid_mae
                best_model = copy.deepcopy(ema_model)
        else:
295
296
            logger.info(f"Epoch {i} | Train Loss {train_loss:.4f}")

297
298
        scheduler.step()

299
    logger.info("Testing")
300
301
    predictions, labels = evaluate(device, best_model, test_loader)
    test_mae = mean_absolute_error(labels, predictions)
302
303
    logger.info("Test MAE {:.4f}".format(test_mae))

304
305
306

if __name__ == "__main__":
    main()