"vscode:/vscode.git/clone" did not exist on "349b491c635a50f663fcc135b9d73f8b15ef079e"
train.py 8.42 KB
Newer Older
Chen Sirui's avatar
Chen Sirui committed
1
import argparse
2
3
from functools import partial

Chen Sirui's avatar
Chen Sirui committed
4
5
6
import numpy as np
import torch
import torch.nn as nn
7
8
9
10
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
11
12
from dcrnn import DiffConv
from gaan import GatedGAT
13
14
15
16
17
from model import GraphRNN
from torch.utils.data import DataLoader
from utils import NormalizationLayer, get_learning_rate, masked_mae_loss

import dgl
Chen Sirui's avatar
Chen Sirui committed
18
19
20
21

batch_cnt = [0]


22
23
24
25
26
27
28
29
30
31
32
def train(
    model,
    graph,
    dataloader,
    optimizer,
    scheduler,
    normalizer,
    loss_fn,
    device,
    args,
):
Chen Sirui's avatar
Chen Sirui committed
33
34
35
36
37
38
39
40
41
    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:
42
43
44
45
46
47
48
49
50
51
            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
52
53
54
55
56
57
            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)

58
59
60
61
62
63
64
65
66
67
68
69
        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
70
71
        y = y.reshape(y.shape[0], -1, y.shape[3]).float().to(device)

72
        batch_graph = dgl.batch([graph] * batch_size)
Chen Sirui's avatar
Chen Sirui committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
        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:
97
98
99
100
101
102
103
104
105
106
            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
107
108
109
110
111
112
            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)

113
114
115
116
117
118
119
120
121
122
123
124
        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
125
126
        y = y.reshape(x.shape[0], -1, x.shape[3]).to(device)

127
        batch_graph = dgl.batch([graph] * batch_size)
Chen Sirui's avatar
Chen Sirui committed
128
129
130
131
132
133
134
135
136
137
        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
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
    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
198
199
    args = parser.parse_args()
    # Load the datasets
200
    if args.dataset == "LA":
Chen Sirui's avatar
Chen Sirui committed
201
202
203
204
        g = METR_LAGraphDataset()
        train_data = METR_LATrainDataset()
        test_data = METR_LATestDataset()
        valid_data = METR_LAValidDataset()
205
    elif args.dataset == "BAY":
Chen Sirui's avatar
Chen Sirui committed
206
207
208
209
210
211
        g = PEMS_BAYGraphDataset()
        train_data = PEMS_BAYTrainDataset()
        test_data = PEMS_BAYTestDataset()
        valid_data = PEMS_BAYValidDataset()

    if args.gpu == -1:
212
        device = torch.device("cpu")
Chen Sirui's avatar
Chen Sirui committed
213
    else:
214
        device = torch.device("cuda:{}".format(args.gpu))
Chen Sirui's avatar
Chen Sirui committed
215
216

    train_loader = DataLoader(
217
218
219
220
221
        train_data,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        shuffle=True,
    )
Chen Sirui's avatar
Chen Sirui committed
222
    valid_loader = DataLoader(
223
224
225
226
227
        valid_data,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        shuffle=True,
    )
Chen Sirui's avatar
Chen Sirui committed
228
    test_loader = DataLoader(
229
230
231
232
233
        test_data,
        batch_size=args.batch_size,
        num_workers=args.num_workers,
        shuffle=True,
    )
Chen Sirui's avatar
Chen Sirui committed
234
235
    normalizer = NormalizationLayer(train_data.mean, train_data.std)

236
237
    if args.model == "dcrnn":
        batch_g = dgl.batch([g] * args.batch_size).to(device)
Chen Sirui's avatar
Chen Sirui committed
238
        out_gs, in_gs = DiffConv.attach_graph(batch_g, args.diffsteps)
239
240
241
242
243
244
245
        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
246
247
        net = partial(GatedGAT, map_feats=64, num_heads=args.num_heads)

248
249
250
251
252
253
254
255
    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
256
257
258
259
260
261
262

    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):
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
        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
            )
        )