train.py 15.6 KB
Newer Older
1
2
3
import datetime
import os
import time
4
import warnings
5
6

import presets
7
8
9
10
11
import torch
import torch.utils.data
import torchvision
import torchvision.datasets.video_utils
import utils
12
13
14
from torch import nn
from torch.utils.data.dataloader import default_collate
from torchvision.datasets.samplers import DistributedSampler, UniformClipSampler, RandomClipSampler
15

16

17
def train_one_epoch(model, criterion, optimizer, lr_scheduler, data_loader, device, epoch, print_freq, scaler=None):
18
19
    model.train()
    metric_logger = utils.MetricLogger(delimiter="  ")
20
21
    metric_logger.add_meter("lr", utils.SmoothedValue(window_size=1, fmt="{value}"))
    metric_logger.add_meter("clips/s", utils.SmoothedValue(window_size=10, fmt="{value:.3f}"))
22

23
    header = f"Epoch: [{epoch}]"
24
25
26
    for video, target in metric_logger.log_every(data_loader, print_freq, header):
        start_time = time.time()
        video, target = video.to(device), target.to(device)
27
28
29
        with torch.cuda.amp.autocast(enabled=scaler is not None):
            output = model(video)
            loss = criterion(output, target)
30
31

        optimizer.zero_grad()
32
33
34
35
36

        if scaler is not None:
            scaler.scale(loss).backward()
            scaler.step(optimizer)
            scaler.update()
37
38
        else:
            loss.backward()
39
            optimizer.step()
40
41
42
43

        acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))
        batch_size = video.shape[0]
        metric_logger.update(loss=loss.item(), lr=optimizer.param_groups[0]["lr"])
44
45
46
        metric_logger.meters["acc1"].update(acc1.item(), n=batch_size)
        metric_logger.meters["acc5"].update(acc5.item(), n=batch_size)
        metric_logger.meters["clips/s"].update(batch_size / (time.time() - start_time))
47
48
49
50
51
52
        lr_scheduler.step()


def evaluate(model, criterion, data_loader, device):
    model.eval()
    metric_logger = utils.MetricLogger(delimiter="  ")
53
    header = "Test:"
54
    num_processed_samples = 0
55
    with torch.inference_mode():
56
57
58
59
60
61
62
63
64
65
66
        for video, target in metric_logger.log_every(data_loader, 100, header):
            video = video.to(device, non_blocking=True)
            target = target.to(device, non_blocking=True)
            output = model(video)
            loss = criterion(output, target)

            acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))
            # FIXME need to take into account that the datasets
            # could have been padded in distributed setup
            batch_size = video.shape[0]
            metric_logger.update(loss=loss.item())
67
68
            metric_logger.meters["acc1"].update(acc1.item(), n=batch_size)
            metric_logger.meters["acc5"].update(acc5.item(), n=batch_size)
69
            num_processed_samples += batch_size
70
    # gather the stats from all processes
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
    num_processed_samples = utils.reduce_across_processes(num_processed_samples)
    if isinstance(data_loader.sampler, DistributedSampler):
        # Get the len of UniformClipSampler inside DistributedSampler
        num_data_from_sampler = len(data_loader.sampler.dataset)
    else:
        num_data_from_sampler = len(data_loader.sampler)

    if (
        hasattr(data_loader.dataset, "__len__")
        and num_data_from_sampler != num_processed_samples
        and torch.distributed.get_rank() == 0
    ):
        # See FIXME above
        warnings.warn(
            f"It looks like the sampler has {num_data_from_sampler} samples, but {num_processed_samples} "
            "samples were used for the validation, which might bias the results. "
            "Try adjusting the batch size and / or the world size. "
            "Setting the world size to 1 is always a safe bet."
        )

91
92
    metric_logger.synchronize_between_processes()

93
94
95
96
97
    print(
        " * Clip Acc@1 {top1.global_avg:.3f} Clip Acc@5 {top5.global_avg:.3f}".format(
            top1=metric_logger.acc1, top5=metric_logger.acc5
        )
    )
98
99
100
101
102
    return metric_logger.acc1.global_avg


def _get_cache_path(filepath):
    import hashlib
103

104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
    h = hashlib.sha1(filepath.encode()).hexdigest()
    cache_path = os.path.join("~", ".torch", "vision", "datasets", "kinetics", h[:10] + ".pt")
    cache_path = os.path.expanduser(cache_path)
    return cache_path


def collate_fn(batch):
    # remove audio from the batch
    batch = [(d[0], d[2]) for d in batch]
    return default_collate(batch)


def main(args):
    if args.output_dir:
        utils.mkdir(args.output_dir)

    utils.init_distributed_mode(args)
    print(args)

    device = torch.device(args.device)

125
126
127
128
129
    if args.use_deterministic_algorithms:
        torch.backends.cudnn.benchmark = False
        torch.use_deterministic_algorithms(True)
    else:
        torch.backends.cudnn.benchmark = True
130
131
132

    # Data loading code
    print("Loading data")
133
134
    traindir = os.path.join(args.data_path, "train")
    valdir = os.path.join(args.data_path, "val")
135
136
137
138

    print("Loading training data")
    st = time.time()
    cache_path = _get_cache_path(traindir)
139
    transform_train = presets.VideoClassificationPresetTrain(crop_size=(112, 112), resize_size=(128, 171))
140
141

    if args.cache_dataset and os.path.exists(cache_path):
142
        print(f"Loading dataset_train from {cache_path}")
143
144
145
146
        dataset, _ = torch.load(cache_path)
        dataset.transform = transform_train
    else:
        if args.distributed:
147
            print("It is recommended to pre-compute the dataset cache on a single-gpu first, as it will be faster")
148
149
        dataset = torchvision.datasets.Kinetics(
            args.data_path,
150
            frames_per_clip=args.clip_len,
151
152
            num_classes=args.kinetics_version,
            split="train",
153
            step_between_clips=1,
154
            transform=transform_train,
155
            frame_rate=15,
156
157
158
159
            extensions=(
                "avi",
                "mp4",
            ),
160
            output_format="TCHW",
161
162
        )
        if args.cache_dataset:
163
            print(f"Saving dataset_train to {cache_path}")
164
165
166
167
168
169
170
171
            utils.mkdir(os.path.dirname(cache_path))
            utils.save_on_master((dataset, traindir), cache_path)

    print("Took", time.time() - st)

    print("Loading validation data")
    cache_path = _get_cache_path(valdir)

172
173
174
    if args.weights and args.test_only:
        weights = torchvision.models.get_weight(args.weights)
        transform_test = weights.transforms()
175
    else:
176
        transform_test = presets.VideoClassificationPresetEval(crop_size=(112, 112), resize_size=(128, 171))
177
178

    if args.cache_dataset and os.path.exists(cache_path):
179
        print(f"Loading dataset_test from {cache_path}")
180
181
182
183
        dataset_test, _ = torch.load(cache_path)
        dataset_test.transform = transform_test
    else:
        if args.distributed:
184
            print("It is recommended to pre-compute the dataset cache on a single-gpu first, as it will be faster")
185
186
        dataset_test = torchvision.datasets.Kinetics(
            args.data_path,
187
            frames_per_clip=args.clip_len,
188
189
            num_classes=args.kinetics_version,
            split="val",
190
            step_between_clips=1,
191
            transform=transform_test,
192
            frame_rate=15,
193
194
195
196
            extensions=(
                "avi",
                "mp4",
            ),
197
            output_format="TCHW",
198
199
        )
        if args.cache_dataset:
200
            print(f"Saving dataset_test to {cache_path}")
201
202
203
204
            utils.mkdir(os.path.dirname(cache_path))
            utils.save_on_master((dataset_test, valdir), cache_path)

    print("Creating data loaders")
205
    train_sampler = RandomClipSampler(dataset.video_clips, args.clips_per_video)
206
207
208
    test_sampler = UniformClipSampler(dataset_test.video_clips, args.clips_per_video)
    if args.distributed:
        train_sampler = DistributedSampler(train_sampler)
209
        test_sampler = DistributedSampler(test_sampler, shuffle=False)
210
211

    data_loader = torch.utils.data.DataLoader(
212
213
214
215
216
217
218
        dataset,
        batch_size=args.batch_size,
        sampler=train_sampler,
        num_workers=args.workers,
        pin_memory=True,
        collate_fn=collate_fn,
    )
219
220

    data_loader_test = torch.utils.data.DataLoader(
221
222
223
224
225
226
227
        dataset_test,
        batch_size=args.batch_size,
        sampler=test_sampler,
        num_workers=args.workers,
        pin_memory=True,
        collate_fn=collate_fn,
    )
228
229

    print("Creating model")
230
    model = torchvision.models.video.__dict__[args.model](weights=args.weights)
231
232
233
234
235
236
237
    model.to(device)
    if args.distributed and args.sync_bn:
        model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)

    criterion = nn.CrossEntropyLoss()

    lr = args.lr * args.world_size
238
    optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=args.momentum, weight_decay=args.weight_decay)
239
    scaler = torch.cuda.amp.GradScaler() if args.amp else None
240
241
242

    # convert scheduler to be per iteration, not per epoch, for warmup that lasts
    # between different epochs
243
244
245
246
247
248
249
    iters_per_epoch = len(data_loader)
    lr_milestones = [iters_per_epoch * (m - args.lr_warmup_epochs) for m in args.lr_milestones]
    main_lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=lr_milestones, gamma=args.lr_gamma)

    if args.lr_warmup_epochs > 0:
        warmup_iters = iters_per_epoch * args.lr_warmup_epochs
        args.lr_warmup_method = args.lr_warmup_method.lower()
250
251
252
253
254
255
256
257
        if args.lr_warmup_method == "linear":
            warmup_lr_scheduler = torch.optim.lr_scheduler.LinearLR(
                optimizer, start_factor=args.lr_warmup_decay, total_iters=warmup_iters
            )
        elif args.lr_warmup_method == "constant":
            warmup_lr_scheduler = torch.optim.lr_scheduler.ConstantLR(
                optimizer, factor=args.lr_warmup_decay, total_iters=warmup_iters
            )
258
        else:
259
            raise RuntimeError(
260
                f"Invalid warmup lr method '{args.lr_warmup_method}'. Only linear and constant are supported."
261
            )
262
263

        lr_scheduler = torch.optim.lr_scheduler.SequentialLR(
264
            optimizer, schedulers=[warmup_lr_scheduler, main_lr_scheduler], milestones=[warmup_iters]
265
266
267
        )
    else:
        lr_scheduler = main_lr_scheduler
268
269
270
271
272
273
274

    model_without_ddp = model
    if args.distributed:
        model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
        model_without_ddp = model.module

    if args.resume:
275
276
277
278
279
        checkpoint = torch.load(args.resume, map_location="cpu")
        model_without_ddp.load_state_dict(checkpoint["model"])
        optimizer.load_state_dict(checkpoint["optimizer"])
        lr_scheduler.load_state_dict(checkpoint["lr_scheduler"])
        args.start_epoch = checkpoint["epoch"] + 1
280
281
        if args.amp:
            scaler.load_state_dict(checkpoint["scaler"])
282
283

    if args.test_only:
284
285
286
        # We disable the cudnn benchmarking because it can noticeably affect the accuracy
        torch.backends.cudnn.benchmark = False
        torch.backends.cudnn.deterministic = True
287
288
289
290
291
292
293
294
        evaluate(model, criterion, data_loader_test, device=device)
        return

    print("Start training")
    start_time = time.time()
    for epoch in range(args.start_epoch, args.epochs):
        if args.distributed:
            train_sampler.set_epoch(epoch)
295
        train_one_epoch(model, criterion, optimizer, lr_scheduler, data_loader, device, epoch, args.print_freq, scaler)
296
297
298
        evaluate(model, criterion, data_loader_test, device=device)
        if args.output_dir:
            checkpoint = {
299
300
301
302
303
304
                "model": model_without_ddp.state_dict(),
                "optimizer": optimizer.state_dict(),
                "lr_scheduler": lr_scheduler.state_dict(),
                "epoch": epoch,
                "args": args,
            }
305
306
            if args.amp:
                checkpoint["scaler"] = scaler.state_dict()
307
            utils.save_on_master(checkpoint, os.path.join(args.output_dir, f"model_{epoch}.pth"))
308
            utils.save_on_master(checkpoint, os.path.join(args.output_dir, "checkpoint.pth"))
309
310
311

    total_time = time.time() - start_time
    total_time_str = str(datetime.timedelta(seconds=int(total_time)))
312
    print(f"Training time {total_time_str}")
313
314
315
316


def parse_args():
    import argparse
317
318
319

    parser = argparse.ArgumentParser(description="PyTorch Video Classification Training")

320
    parser.add_argument("--data-path", default="/datasets01_101/kinetics/070618/", type=str, help="dataset path")
321
322
323
    parser.add_argument(
        "--kinetics-version", default="400", type=str, choices=["400", "600"], help="Select kinetics version"
    )
324
325
    parser.add_argument("--model", default="r2plus1d_18", type=str, help="model name")
    parser.add_argument("--device", default="cuda", type=str, help="device (Use cuda or cpu Default: cuda)")
326
327
328
329
    parser.add_argument("--clip-len", default=16, type=int, metavar="N", help="number of frames per clip")
    parser.add_argument(
        "--clips-per-video", default=5, type=int, metavar="N", help="maximum number of clips per video to consider"
    )
330
331
332
    parser.add_argument(
        "-b", "--batch-size", default=24, type=int, help="images per gpu, the total batch size is $NGPU x batch_size"
    )
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
    parser.add_argument("--epochs", default=45, type=int, metavar="N", help="number of total epochs to run")
    parser.add_argument(
        "-j", "--workers", default=10, type=int, metavar="N", help="number of data loading workers (default: 10)"
    )
    parser.add_argument("--lr", default=0.01, type=float, help="initial learning rate")
    parser.add_argument("--momentum", default=0.9, type=float, metavar="M", help="momentum")
    parser.add_argument(
        "--wd",
        "--weight-decay",
        default=1e-4,
        type=float,
        metavar="W",
        help="weight decay (default: 1e-4)",
        dest="weight_decay",
    )
    parser.add_argument("--lr-milestones", nargs="+", default=[20, 30, 40], type=int, help="decrease lr on milestones")
    parser.add_argument("--lr-gamma", default=0.1, type=float, help="decrease lr by a factor of lr-gamma")
    parser.add_argument("--lr-warmup-epochs", default=10, type=int, help="the number of epochs to warmup (default: 10)")
    parser.add_argument("--lr-warmup-method", default="linear", type=str, help="the warmup method (default: linear)")
    parser.add_argument("--lr-warmup-decay", default=0.001, type=float, help="the decay for lr")
    parser.add_argument("--print-freq", default=10, type=int, help="print frequency")
354
355
    parser.add_argument("--output-dir", default=".", type=str, help="path to save outputs")
    parser.add_argument("--resume", default="", type=str, help="path of checkpoint")
356
    parser.add_argument("--start-epoch", default=0, type=int, metavar="N", help="start epoch")
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
    parser.add_argument(
        "--cache-dataset",
        dest="cache_dataset",
        help="Cache the datasets for quicker initialization. It also serializes the transforms",
        action="store_true",
    )
    parser.add_argument(
        "--sync-bn",
        dest="sync_bn",
        help="Use sync batch norm",
        action="store_true",
    )
    parser.add_argument(
        "--test-only",
        dest="test_only",
        help="Only test the model",
        action="store_true",
    )
375
376
377
    parser.add_argument(
        "--use-deterministic-algorithms", action="store_true", help="Forces the use of deterministic algorithms only."
    )
378
379

    # distributed training parameters
380
    parser.add_argument("--world-size", default=1, type=int, help="number of distributed processes")
381
    parser.add_argument("--dist-url", default="env://", type=str, help="url used to set up distributed training")
382

383
384
    parser.add_argument("--weights", default=None, type=str, help="the weights enum name to load")

385
386
387
    # Mixed precision training parameters
    parser.add_argument("--amp", action="store_true", help="Use torch.cuda.amp for mixed precision training")

388
389
390
391
392
393
394
395
    args = parser.parse_args()

    return args


if __name__ == "__main__":
    args = parse_args()
    main(args)