train.py 8.38 KB
Newer Older
Chen Sirui's avatar
Chen Sirui committed
1
import argparse
2
3
from functools import partial

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
4
5
import dgl

Chen Sirui's avatar
Chen Sirui committed
6
7
8
import numpy as np
import torch
import torch.nn as nn
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
9
10
11
12
13
14
15
16
17
18
from dataloading import (
    METR_LAGraphDataset,
    METR_LATestDataset,
    METR_LATrainDataset,
    METR_LAValidDataset,
    PEMS_BAYGraphDataset,
    PEMS_BAYTestDataset,
    PEMS_BAYTrainDataset,
    PEMS_BAYValidDataset,
)
Chen Sirui's avatar
Chen Sirui committed
19
20
from dcrnn import DiffConv
from gaan import GatedGAT
21
22
from model import GraphRNN
from torch.utils.data import DataLoader
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
23
from utils import get_learning_rate, masked_mae_loss, NormalizationLayer
Chen Sirui's avatar
Chen Sirui committed
24
25
26
27

batch_cnt = [0]


28
29
30
31
32
33
34
35
36
37
38
def train(
    model,
    graph,
    dataloader,
    optimizer,
    scheduler,
    normalizer,
    loss_fn,
    device,
    args,
):
Chen Sirui's avatar
Chen Sirui committed
39
40
41
42
43
44
45
46
47
    total_loss = []
    graph = graph.to(device)
    model.train()
    batch_size = args.batch_size
    for i, (x, y) in enumerate(dataloader):
        optimizer.zero_grad()
        # Padding: Since the diffusion graph is precmputed we need to pad the batch so that
        # each batch have same batch size
        if x.shape[0] != batch_size:
48
49
50
51
52
53
54
55
56
57
            x_buff = torch.zeros(batch_size, x.shape[1], x.shape[2], x.shape[3])
            y_buff = torch.zeros(batch_size, x.shape[1], x.shape[2], x.shape[3])
            x_buff[: x.shape[0], :, :, :] = x
            x_buff[x.shape[0] :, :, :, :] = x[-1].repeat(
                batch_size - x.shape[0], 1, 1, 1
            )
            y_buff[: x.shape[0], :, :, :] = y
            y_buff[x.shape[0] :, :, :, :] = y[-1].repeat(
                batch_size - x.shape[0], 1, 1, 1
            )
Chen Sirui's avatar
Chen Sirui committed
58
59
60
61
62
63
            x = x_buff
            y = y_buff
        # Permute the dimension for shaping
        x = x.permute(1, 0, 2, 3)
        y = y.permute(1, 0, 2, 3)

64
65
66
67
68
69
70
71
72
73
74
75
        x_norm = (
            normalizer.normalize(x)
            .reshape(x.shape[0], -1, x.shape[3])
            .float()
            .to(device)
        )
        y_norm = (
            normalizer.normalize(y)
            .reshape(x.shape[0], -1, x.shape[3])
            .float()
            .to(device)
        )
Chen Sirui's avatar
Chen Sirui committed
76
77
        y = y.reshape(y.shape[0], -1, y.shape[3]).float().to(device)

78
        batch_graph = dgl.batch([graph] * batch_size)
Chen Sirui's avatar
Chen Sirui committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
        output = model(batch_graph, x_norm, y_norm, batch_cnt[0], device)
        # Denormalization for loss compute
        y_pred = normalizer.denormalize(output)
        loss = loss_fn(y_pred, y)
        loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
        optimizer.step()
        if get_learning_rate(optimizer) > args.minimum_lr:
            scheduler.step()
        total_loss.append(float(loss))
        batch_cnt[0] += 1
        print("Batch: ", i)
    return np.mean(total_loss)


def eval(model, graph, dataloader, normalizer, loss_fn, device, args):
    total_loss = []
    graph = graph.to(device)
    model.eval()
    batch_size = args.batch_size
    for i, (x, y) in enumerate(dataloader):
        # Padding: Since the diffusion graph is precmputed we need to pad the batch so that
        # each batch have same batch size
        if x.shape[0] != batch_size:
103
104
105
106
107
108
109
110
111
112
            x_buff = torch.zeros(batch_size, x.shape[1], x.shape[2], x.shape[3])
            y_buff = torch.zeros(batch_size, x.shape[1], x.shape[2], x.shape[3])
            x_buff[: x.shape[0], :, :, :] = x
            x_buff[x.shape[0] :, :, :, :] = x[-1].repeat(
                batch_size - x.shape[0], 1, 1, 1
            )
            y_buff[: x.shape[0], :, :, :] = y
            y_buff[x.shape[0] :, :, :, :] = y[-1].repeat(
                batch_size - x.shape[0], 1, 1, 1
            )
Chen Sirui's avatar
Chen Sirui committed
113
114
115
116
117
118
            x = x_buff
            y = y_buff
        # Permute the order of dimension
        x = x.permute(1, 0, 2, 3)
        y = y.permute(1, 0, 2, 3)

119
120
121
122
123
124
125
126
127
128
129
130
        x_norm = (
            normalizer.normalize(x)
            .reshape(x.shape[0], -1, x.shape[3])
            .float()
            .to(device)
        )
        y_norm = (
            normalizer.normalize(y)
            .reshape(x.shape[0], -1, x.shape[3])
            .float()
            .to(device)
        )
Chen Sirui's avatar
Chen Sirui committed
131
132
        y = y.reshape(x.shape[0], -1, x.shape[3]).to(device)

133
        batch_graph = dgl.batch([graph] * batch_size)
Chen Sirui's avatar
Chen Sirui committed
134
135
136
137
138
139
140
141
142
143
        output = model(batch_graph, x_norm, y_norm, i, device)
        y_pred = normalizer.denormalize(output)
        loss = loss_fn(y_pred, y)
        total_loss.append(float(loss))
    return np.mean(total_loss)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    # Define the arguments
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
    parser.add_argument(
        "--batch_size",
        type=int,
        default=64,
        help="Size of batch for minibatch Training",
    )
    parser.add_argument(
        "--num_workers",
        type=int,
        default=0,
        help="Number of workers for parallel dataloading",
    )
    parser.add_argument(
        "--model",
        type=str,
        default="dcrnn",
        help="WHich model to use DCRNN vs GaAN",
    )
    parser.add_argument(
        "--gpu", type=int, default=-1, help="GPU indexm -1 for CPU training"
    )
    parser.add_argument(
        "--diffsteps",
        type=int,
        default=2,
        help="Step of constructing the diffusiob matrix",
    )
    parser.add_argument(
        "--num_heads", type=int, default=2, help="Number of multiattention head"
    )
    parser.add_argument(
        "--decay_steps",
        type=int,
        default=2000,
        help="Teacher forcing probability decay ratio",
    )
    parser.add_argument(
        "--lr", type=float, default=0.01, help="Initial learning rate"
    )
    parser.add_argument(
        "--minimum_lr",
        type=float,
        default=2e-6,
        help="Lower bound of learning rate",
    )
    parser.add_argument(
        "--dataset",
        type=str,
        default="LA",
        help="dataset LA for METR_LA; BAY for PEMS_BAY",
    )
    parser.add_argument(
        "--epochs", type=int, default=100, help="Number of epoches for training"
    )
    parser.add_argument(
        "--max_grad_norm",
        type=float,
        default=5.0,
        help="Maximum gradient norm for update parameters",
    )
Chen Sirui's avatar
Chen Sirui committed
204
205
    args = parser.parse_args()
    # Load the datasets
206
    if args.dataset == "LA":
Chen Sirui's avatar
Chen Sirui committed
207
208
209
210
        g = METR_LAGraphDataset()
        train_data = METR_LATrainDataset()
        test_data = METR_LATestDataset()
        valid_data = METR_LAValidDataset()
211
    elif args.dataset == "BAY":
Chen Sirui's avatar
Chen Sirui committed
212
213
214
215
216
217
        g = PEMS_BAYGraphDataset()
        train_data = PEMS_BAYTrainDataset()
        test_data = PEMS_BAYTestDataset()
        valid_data = PEMS_BAYValidDataset()

    if args.gpu == -1:
218
        device = torch.device("cpu")
Chen Sirui's avatar
Chen Sirui committed
219
    else:
220
        device = torch.device("cuda:{}".format(args.gpu))
Chen Sirui's avatar
Chen Sirui committed
221
222

    train_loader = DataLoader(
223
224
225
226
227
        train_data,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        shuffle=True,
    )
Chen Sirui's avatar
Chen Sirui committed
228
    valid_loader = DataLoader(
229
230
231
232
233
        valid_data,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        shuffle=True,
    )
Chen Sirui's avatar
Chen Sirui committed
234
    test_loader = DataLoader(
235
236
237
238
239
        test_data,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        shuffle=True,
    )
Chen Sirui's avatar
Chen Sirui committed
240
241
    normalizer = NormalizationLayer(train_data.mean, train_data.std)

242
243
    if args.model == "dcrnn":
        batch_g = dgl.batch([g] * args.batch_size).to(device)
Chen Sirui's avatar
Chen Sirui committed
244
        out_gs, in_gs = DiffConv.attach_graph(batch_g, args.diffsteps)
245
246
247
248
249
250
251
        net = partial(
            DiffConv,
            k=args.diffsteps,
            in_graph_list=in_gs,
            out_graph_list=out_gs,
        )
    elif args.model == "gaan":
Chen Sirui's avatar
Chen Sirui committed
252
253
        net = partial(GatedGAT, map_feats=64, num_heads=args.num_heads)

254
255
256
257
258
259
260
261
    dcrnn = GraphRNN(
        in_feats=2,
        out_feats=64,
        seq_len=12,
        num_layers=2,
        net=net,
        decay_steps=args.decay_steps,
    ).to(device)
Chen Sirui's avatar
Chen Sirui committed
262
263
264
265
266
267
268

    optimizer = torch.optim.Adam(dcrnn.parameters(), lr=args.lr)
    scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.99)

    loss_fn = masked_mae_loss

    for e in range(args.epochs):
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
        train_loss = train(
            dcrnn,
            g,
            train_loader,
            optimizer,
            scheduler,
            normalizer,
            loss_fn,
            device,
            args,
        )
        valid_loss = eval(
            dcrnn, g, valid_loader, normalizer, loss_fn, device, args
        )
        test_loss = eval(
            dcrnn, g, test_loader, normalizer, loss_fn, device, args
        )
        print(
            "Epoch: {} Train Loss: {} Valid Loss: {} Test Loss: {}".format(
                e, train_loss, valid_loss, test_loss
            )
        )