train.py 11.6 KB
Newer Older
1
2
3
4
import datetime
import os
import time

5
import presets
6
7
8
9
import torch
import torch.utils.data
import torchvision
import utils
10
11
from coco_utils import get_coco
from torch import nn
12
13


14
try:
15
    from torchvision import prototype
16
except ImportError:
17
    prototype = None
18
19


20
def get_dataset(dir_path, name, image_set, transform):
21
    def sbd(*args, **kwargs):
22
23
        return torchvision.datasets.SBDataset(*args, mode="segmentation", **kwargs)

24
    paths = {
25
26
        "voc": (dir_path, torchvision.datasets.VOCSegmentation, 21),
        "voc_aug": (dir_path, sbd, 21),
27
        "coco": (dir_path, get_coco, 21),
28
29
30
31
32
33
34
    }
    p, ds_fn, num_classes = paths[name]

    ds = ds_fn(p, image_set=image_set, transforms=transform)
    return ds, num_classes


35
36
37
def get_transform(train, args):
    if train:
        return presets.SegmentationPresetTrain(base_size=520, crop_size=480)
38
    elif not args.prototype:
39
40
        return presets.SegmentationPresetEval(base_size=520)
    else:
41
42
43
44
45
        if args.weights:
            weights = prototype.models.get_weight(args.weights)
            return weights.transforms()
        else:
            return prototype.transforms.VocEval(resize_size=520)
46
47
48
49
50
51
52
53


def criterion(inputs, target):
    losses = {}
    for name, x in inputs.items():
        losses[name] = nn.functional.cross_entropy(x, target, ignore_index=255)

    if len(losses) == 1:
54
        return losses["out"]
55

56
    return losses["out"] + 0.5 * losses["aux"]
57
58
59
60
61
62


def evaluate(model, data_loader, device, num_classes):
    model.eval()
    confmat = utils.ConfusionMatrix(num_classes)
    metric_logger = utils.MetricLogger(delimiter="  ")
63
    header = "Test:"
64
    with torch.inference_mode():
65
66
67
        for image, target in metric_logger.log_every(data_loader, 100, header):
            image, target = image.to(device), target.to(device)
            output = model(image)
68
            output = output["out"]
69
70
71
72
73
74
75
76

            confmat.update(target.flatten(), output.argmax(1).flatten())

        confmat.reduce_from_all_processes()

    return confmat


77
def train_one_epoch(model, criterion, optimizer, data_loader, lr_scheduler, device, epoch, print_freq, scaler=None):
78
79
    model.train()
    metric_logger = utils.MetricLogger(delimiter="  ")
80
    metric_logger.add_meter("lr", utils.SmoothedValue(window_size=1, fmt="{value}"))
81
    header = f"Epoch: [{epoch}]"
82
83
    for image, target in metric_logger.log_every(data_loader, print_freq, header):
        image, target = image.to(device), target.to(device)
84
85
86
        with torch.cuda.amp.autocast(enabled=scaler is not None):
            output = model(image)
            loss = criterion(output, target)
87
88

        optimizer.zero_grad()
89
90
91
92
93
94
95
        if scaler is not None:
            scaler.scale(loss).backward()
            scaler.step(optimizer)
            scaler.update()
        else:
            loss.backward()
            optimizer.step()
96
97
98
99
100
101
102

        lr_scheduler.step()

        metric_logger.update(loss=loss.item(), lr=optimizer.param_groups[0]["lr"])


def main(args):
103
    if args.prototype and prototype is None:
104
        raise ImportError("The prototype module couldn't be found. Please install the latest torchvision nightly.")
105
106
    if not args.prototype and args.weights:
        raise ValueError("The weights parameter works only in prototype mode. Please pass the --prototype argument.")
107
108
109
110
111
112
113
114
    if args.output_dir:
        utils.mkdir(args.output_dir)

    utils.init_distributed_mode(args)
    print(args)

    device = torch.device(args.device)

115
116
    dataset, num_classes = get_dataset(args.data_path, args.dataset, "train", get_transform(True, args))
    dataset_test, _ = get_dataset(args.data_path, args.dataset, "val", get_transform(False, args))
117
118
119
120
121
122
123
124
125

    if args.distributed:
        train_sampler = torch.utils.data.distributed.DistributedSampler(dataset)
        test_sampler = torch.utils.data.distributed.DistributedSampler(dataset_test)
    else:
        train_sampler = torch.utils.data.RandomSampler(dataset)
        test_sampler = torch.utils.data.SequentialSampler(dataset_test)

    data_loader = torch.utils.data.DataLoader(
126
127
128
129
130
131
132
        dataset,
        batch_size=args.batch_size,
        sampler=train_sampler,
        num_workers=args.workers,
        collate_fn=utils.collate_fn,
        drop_last=True,
    )
133
134

    data_loader_test = torch.utils.data.DataLoader(
135
136
        dataset_test, batch_size=1, sampler=test_sampler, num_workers=args.workers, collate_fn=utils.collate_fn
    )
137

138
    if not args.prototype:
139
140
141
142
143
144
        model = torchvision.models.segmentation.__dict__[args.model](
            pretrained=args.pretrained,
            num_classes=num_classes,
            aux_loss=args.aux_loss,
        )
    else:
145
        model = prototype.models.segmentation.__dict__[args.model](
146
147
            weights=args.weights, num_classes=num_classes, aux_loss=args.aux_loss
        )
148
149
    model.to(device)
    if args.distributed:
Francisco Massa's avatar
Francisco Massa committed
150
        model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
151
152
153
154
155
156
157
158
159
160
161
162
163

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

    params_to_optimize = [
        {"params": [p for p in model_without_ddp.backbone.parameters() if p.requires_grad]},
        {"params": [p for p in model_without_ddp.classifier.parameters() if p.requires_grad]},
    ]
    if args.aux_loss:
        params = [p for p in model_without_ddp.aux_classifier.parameters() if p.requires_grad]
        params_to_optimize.append({"params": params, "lr": args.lr * 10})
164
    optimizer = torch.optim.SGD(params_to_optimize, lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)
165

166
167
    scaler = torch.cuda.amp.GradScaler() if args.amp else None

168
169
    iters_per_epoch = len(data_loader)
    main_lr_scheduler = torch.optim.lr_scheduler.LambdaLR(
170
171
        optimizer, lambda x: (1 - x / (iters_per_epoch * (args.epochs - args.lr_warmup_epochs))) ** 0.9
    )
172
173
174
175

    if args.lr_warmup_epochs > 0:
        warmup_iters = iters_per_epoch * args.lr_warmup_epochs
        args.lr_warmup_method = args.lr_warmup_method.lower()
176
177
178
179
180
181
182
183
        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
            )
184
        else:
185
            raise RuntimeError(
186
                f"Invalid warmup lr method '{args.lr_warmup_method}'. Only linear and constant are supported."
187
            )
188
        lr_scheduler = torch.optim.lr_scheduler.SequentialLR(
189
            optimizer, schedulers=[warmup_lr_scheduler, main_lr_scheduler], milestones=[warmup_iters]
190
191
192
        )
    else:
        lr_scheduler = main_lr_scheduler
193

194
    if args.resume:
195
196
        checkpoint = torch.load(args.resume, map_location="cpu")
        model_without_ddp.load_state_dict(checkpoint["model"], strict=not args.test_only)
197
        if not args.test_only:
198
199
200
            optimizer.load_state_dict(checkpoint["optimizer"])
            lr_scheduler.load_state_dict(checkpoint["lr_scheduler"])
            args.start_epoch = checkpoint["epoch"] + 1
201
202
            if args.amp:
                scaler.load_state_dict(checkpoint["scaler"])
203
204
205
206
207

    if args.test_only:
        confmat = evaluate(model, data_loader_test, device=device, num_classes=num_classes)
        print(confmat)
        return
208

209
    start_time = time.time()
210
    for epoch in range(args.start_epoch, args.epochs):
211
212
        if args.distributed:
            train_sampler.set_epoch(epoch)
213
        train_one_epoch(model, criterion, optimizer, data_loader, lr_scheduler, device, epoch, args.print_freq, scaler)
214
215
        confmat = evaluate(model, data_loader_test, device=device, num_classes=num_classes)
        print(confmat)
216
        checkpoint = {
217
218
219
220
221
            "model": model_without_ddp.state_dict(),
            "optimizer": optimizer.state_dict(),
            "lr_scheduler": lr_scheduler.state_dict(),
            "epoch": epoch,
            "args": args,
222
        }
223
224
        if args.amp:
            checkpoint["scaler"] = scaler.state_dict()
225
        utils.save_on_master(checkpoint, os.path.join(args.output_dir, f"model_{epoch}.pth"))
226
        utils.save_on_master(checkpoint, os.path.join(args.output_dir, "checkpoint.pth"))
227
228
229

    total_time = time.time() - start_time
    total_time_str = str(datetime.timedelta(seconds=int(total_time)))
230
    print(f"Training time {total_time_str}")
231
232


233
def get_args_parser(add_help=True):
234
    import argparse
235
236
237

    parser = argparse.ArgumentParser(description="PyTorch Segmentation Training", add_help=add_help)

238
239
240
    parser.add_argument("--data-path", default="/datasets01/COCO/022719/", type=str, help="dataset path")
    parser.add_argument("--dataset", default="coco", type=str, help="dataset name")
    parser.add_argument("--model", default="fcn_resnet101", type=str, help="model name")
241
    parser.add_argument("--aux-loss", action="store_true", help="auxiliar loss")
242
243
244
245
    parser.add_argument("--device", default="cuda", type=str, help="device (Use cuda or cpu Default: cuda)")
    parser.add_argument(
        "-b", "--batch-size", default=8, type=int, help="images per gpu, the total batch size is $NGPU x batch_size"
    )
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
    parser.add_argument("--epochs", default=30, type=int, metavar="N", help="number of total epochs to run")

    parser.add_argument(
        "-j", "--workers", default=16, type=int, metavar="N", help="number of data loading workers (default: 16)"
    )
    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-warmup-epochs", default=0, type=int, help="the number of epochs to warmup (default: 0)")
    parser.add_argument("--lr-warmup-method", default="linear", type=str, help="the warmup method (default: linear)")
    parser.add_argument("--lr-warmup-decay", default=0.01, type=float, help="the decay for lr")
    parser.add_argument("--print-freq", default=10, type=int, help="print frequency")
266
267
    parser.add_argument("--output-dir", default=".", type=str, help="path to save outputs")
    parser.add_argument("--resume", default="", type=str, help="path of checkpoint")
268
    parser.add_argument("--start-epoch", default=0, type=int, metavar="N", help="start epoch")
269
270
271
272
273
274
    parser.add_argument(
        "--test-only",
        dest="test_only",
        help="Only test the model",
        action="store_true",
    )
275
276
277
278
279
280
    parser.add_argument(
        "--pretrained",
        dest="pretrained",
        help="Use pre-trained models from the modelzoo",
        action="store_true",
    )
281
    # distributed training parameters
282
    parser.add_argument("--world-size", default=1, type=int, help="number of distributed processes")
283
    parser.add_argument("--dist-url", default="env://", type=str, help="url used to set up distributed training")
284

285
    # Prototype models only
286
287
288
289
290
291
    parser.add_argument(
        "--prototype",
        dest="prototype",
        help="Use prototype model builders instead those from main area",
        action="store_true",
    )
292
293
    parser.add_argument("--weights", default=None, type=str, help="the weights enum name to load")

294
295
296
    # Mixed precision training parameters
    parser.add_argument("--amp", action="store_true", help="Use torch.cuda.amp for mixed precision training")

297
    return parser
298
299
300


if __name__ == "__main__":
301
    args = get_args_parser().parse_args()
302
    main(args)