Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

train.py 13 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
198
199
200
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
  1. r"""PyTorch Detection Training.
  2. To run in a multi-gpu environment, use the distributed launcher::
  3. python -m torch.distributed.launch --nproc_per_node=$NGPU --use_env \
  4. train.py ... --world-size $NGPU
  5. The default hyperparameters are tuned for training on 8 gpus and 2 images per gpu.
  6. --lr 0.02 --batch-size 2 --world-size 8
  7. If you use different number of gpus, the learning rate should be changed to 0.02/8*$NGPU.
  8. On top of that, for training Faster/Mask R-CNN, the default hyperparameters are
  9. --epochs 26 --lr-steps 16 22 --aspect-ratio-group-factor 3
  10. Also, if you train Keypoint R-CNN, the default hyperparameters are
  11. --epochs 46 --lr-steps 36 43 --aspect-ratio-group-factor 3
  12. Because the number of images is smaller in the person keypoint subset of COCO,
  13. the number of epochs should be adapted so that we have the same number of iterations.
  14. """
  15. import datetime
  16. import os
  17. import time
  18. import presets
  19. import torch
  20. import torch.utils.data
  21. import torchvision
  22. import torchvision.models.detection
  23. import torchvision.models.detection.mask_rcnn
  24. import utils
  25. from coco_utils import get_coco
  26. from engine import evaluate, train_one_epoch
  27. from group_by_aspect_ratio import create_aspect_ratio_groups, GroupedBatchSampler
  28. from torchvision.transforms import InterpolationMode
  29. from transforms import SimpleCopyPaste
  30. def copypaste_collate_fn(batch):
  31. copypaste = SimpleCopyPaste(blending=True, resize_interpolation=InterpolationMode.BILINEAR)
  32. return copypaste(*utils.collate_fn(batch))
  33. def get_dataset(is_train, args):
  34. image_set = "train" if is_train else "val"
  35. num_classes, mode = {"coco": (91, "instances"), "coco_kp": (2, "person_keypoints")}[args.dataset]
  36. with_masks = "mask" in args.model
  37. ds = get_coco(
  38. root=args.data_path,
  39. image_set=image_set,
  40. transforms=get_transform(is_train, args),
  41. mode=mode,
  42. use_v2=args.use_v2,
  43. with_masks=with_masks,
  44. )
  45. return ds, num_classes
  46. def get_transform(is_train, args):
  47. if is_train:
  48. return presets.DetectionPresetTrain(
  49. data_augmentation=args.data_augmentation, backend=args.backend, use_v2=args.use_v2
  50. )
  51. elif args.weights and args.test_only:
  52. weights = torchvision.models.get_weight(args.weights)
  53. trans = weights.transforms()
  54. return lambda img, target: (trans(img), target)
  55. else:
  56. return presets.DetectionPresetEval(backend=args.backend, use_v2=args.use_v2)
  57. def get_args_parser(add_help=True):
  58. import argparse
  59. parser = argparse.ArgumentParser(description="PyTorch Detection Training", add_help=add_help)
  60. parser.add_argument("--data-path", default="/datasets01/COCO/022719/", type=str, help="dataset path")
  61. parser.add_argument(
  62. "--dataset",
  63. default="coco",
  64. type=str,
  65. help="dataset name. Use coco for object detection and instance segmentation and coco_kp for Keypoint detection",
  66. )
  67. parser.add_argument("--model", default="maskrcnn_resnet50_fpn", type=str, help="model name")
  68. parser.add_argument("--device", default="cuda", type=str, help="device (Use cuda or cpu Default: cuda)")
  69. parser.add_argument(
  70. "-b", "--batch-size", default=2, type=int, help="images per gpu, the total batch size is $NGPU x batch_size"
  71. )
  72. parser.add_argument("--epochs", default=26, type=int, metavar="N", help="number of total epochs to run")
  73. parser.add_argument(
  74. "-j", "--workers", default=4, type=int, metavar="N", help="number of data loading workers (default: 4)"
  75. )
  76. parser.add_argument("--opt", default="sgd", type=str, help="optimizer")
  77. parser.add_argument(
  78. "--lr",
  79. default=0.02,
  80. type=float,
  81. help="initial learning rate, 0.02 is the default value for training on 8 gpus and 2 images_per_gpu",
  82. )
  83. parser.add_argument("--momentum", default=0.9, type=float, metavar="M", help="momentum")
  84. parser.add_argument(
  85. "--wd",
  86. "--weight-decay",
  87. default=1e-4,
  88. type=float,
  89. metavar="W",
  90. help="weight decay (default: 1e-4)",
  91. dest="weight_decay",
  92. )
  93. parser.add_argument(
  94. "--norm-weight-decay",
  95. default=None,
  96. type=float,
  97. help="weight decay for Normalization layers (default: None, same value as --wd)",
  98. )
  99. parser.add_argument(
  100. "--lr-scheduler", default="multisteplr", type=str, help="name of lr scheduler (default: multisteplr)"
  101. )
  102. parser.add_argument(
  103. "--lr-step-size", default=8, type=int, help="decrease lr every step-size epochs (multisteplr scheduler only)"
  104. )
  105. parser.add_argument(
  106. "--lr-steps",
  107. default=[16, 22],
  108. nargs="+",
  109. type=int,
  110. help="decrease lr every step-size epochs (multisteplr scheduler only)",
  111. )
  112. parser.add_argument(
  113. "--lr-gamma", default=0.1, type=float, help="decrease lr by a factor of lr-gamma (multisteplr scheduler only)"
  114. )
  115. parser.add_argument("--print-freq", default=20, type=int, help="print frequency")
  116. parser.add_argument("--output-dir", default=".", type=str, help="path to save outputs")
  117. parser.add_argument("--resume", default="", type=str, help="path of checkpoint")
  118. parser.add_argument("--start_epoch", default=0, type=int, help="start epoch")
  119. parser.add_argument("--aspect-ratio-group-factor", default=3, type=int)
  120. parser.add_argument("--rpn-score-thresh", default=None, type=float, help="rpn score threshold for faster-rcnn")
  121. parser.add_argument(
  122. "--trainable-backbone-layers", default=None, type=int, help="number of trainable layers of backbone"
  123. )
  124. parser.add_argument(
  125. "--data-augmentation", default="hflip", type=str, help="data augmentation policy (default: hflip)"
  126. )
  127. parser.add_argument(
  128. "--sync-bn",
  129. dest="sync_bn",
  130. help="Use sync batch norm",
  131. action="store_true",
  132. )
  133. parser.add_argument(
  134. "--test-only",
  135. dest="test_only",
  136. help="Only test the model",
  137. action="store_true",
  138. )
  139. parser.add_argument(
  140. "--use-deterministic-algorithms", action="store_true", help="Forces the use of deterministic algorithms only."
  141. )
  142. # distributed training parameters
  143. parser.add_argument("--world-size", default=1, type=int, help="number of distributed processes")
  144. parser.add_argument("--dist-url", default="env://", type=str, help="url used to set up distributed training")
  145. parser.add_argument("--weights", default=None, type=str, help="the weights enum name to load")
  146. parser.add_argument("--weights-backbone", default=None, type=str, help="the backbone weights enum name to load")
  147. # Mixed precision training parameters
  148. parser.add_argument("--amp", action="store_true", help="Use torch.cuda.amp for mixed precision training")
  149. # Use CopyPaste augmentation training parameter
  150. parser.add_argument(
  151. "--use-copypaste",
  152. action="store_true",
  153. help="Use CopyPaste data augmentation. Works only with data-augmentation='lsj'.",
  154. )
  155. parser.add_argument("--backend", default="PIL", type=str.lower, help="PIL or tensor - case insensitive")
  156. parser.add_argument("--use-v2", action="store_true", help="Use V2 transforms")
  157. return parser
  158. def main(args):
  159. if args.backend.lower() == "tv_tensor" and not args.use_v2:
  160. raise ValueError("Use --use-v2 if you want to use the tv_tensor backend.")
  161. if args.dataset not in ("coco", "coco_kp"):
  162. raise ValueError(f"Dataset should be coco or coco_kp, got {args.dataset}")
  163. if "keypoint" in args.model and args.dataset != "coco_kp":
  164. raise ValueError("Oops, if you want Keypoint detection, set --dataset coco_kp")
  165. if args.dataset == "coco_kp" and args.use_v2:
  166. raise ValueError("KeyPoint detection doesn't support V2 transforms yet")
  167. if args.output_dir:
  168. utils.mkdir(args.output_dir)
  169. utils.init_distributed_mode(args)
  170. print(args)
  171. device = torch.device(args.device)
  172. if args.use_deterministic_algorithms:
  173. torch.use_deterministic_algorithms(True)
  174. # Data loading code
  175. print("Loading data")
  176. dataset, num_classes = get_dataset(is_train=True, args=args)
  177. dataset_test, _ = get_dataset(is_train=False, args=args)
  178. print("Creating data loaders")
  179. if args.distributed:
  180. train_sampler = torch.utils.data.distributed.DistributedSampler(dataset)
  181. test_sampler = torch.utils.data.distributed.DistributedSampler(dataset_test, shuffle=False)
  182. else:
  183. train_sampler = torch.utils.data.RandomSampler(dataset)
  184. test_sampler = torch.utils.data.SequentialSampler(dataset_test)
  185. if args.aspect_ratio_group_factor >= 0:
  186. group_ids = create_aspect_ratio_groups(dataset, k=args.aspect_ratio_group_factor)
  187. train_batch_sampler = GroupedBatchSampler(train_sampler, group_ids, args.batch_size)
  188. else:
  189. train_batch_sampler = torch.utils.data.BatchSampler(train_sampler, args.batch_size, drop_last=True)
  190. train_collate_fn = utils.collate_fn
  191. if args.use_copypaste:
  192. if args.data_augmentation != "lsj":
  193. raise RuntimeError("SimpleCopyPaste algorithm currently only supports the 'lsj' data augmentation policies")
  194. train_collate_fn = copypaste_collate_fn
  195. data_loader = torch.utils.data.DataLoader(
  196. dataset, batch_sampler=train_batch_sampler, num_workers=args.workers, collate_fn=train_collate_fn
  197. )
  198. data_loader_test = torch.utils.data.DataLoader(
  199. dataset_test, batch_size=1, sampler=test_sampler, num_workers=args.workers, collate_fn=utils.collate_fn
  200. )
  201. print("Creating model")
  202. kwargs = {"trainable_backbone_layers": args.trainable_backbone_layers}
  203. if args.data_augmentation in ["multiscale", "lsj"]:
  204. kwargs["_skip_resize"] = True
  205. if "rcnn" in args.model:
  206. if args.rpn_score_thresh is not None:
  207. kwargs["rpn_score_thresh"] = args.rpn_score_thresh
  208. model = torchvision.models.get_model(
  209. args.model, weights=args.weights, weights_backbone=args.weights_backbone, num_classes=num_classes, **kwargs
  210. )
  211. model.to(device)
  212. if args.distributed and args.sync_bn:
  213. model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
  214. model_without_ddp = model
  215. if args.distributed:
  216. model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
  217. model_without_ddp = model.module
  218. if args.norm_weight_decay is None:
  219. parameters = [p for p in model.parameters() if p.requires_grad]
  220. else:
  221. param_groups = torchvision.ops._utils.split_normalization_params(model)
  222. wd_groups = [args.norm_weight_decay, args.weight_decay]
  223. parameters = [{"params": p, "weight_decay": w} for p, w in zip(param_groups, wd_groups) if p]
  224. opt_name = args.opt.lower()
  225. if opt_name.startswith("sgd"):
  226. optimizer = torch.optim.SGD(
  227. parameters,
  228. lr=args.lr,
  229. momentum=args.momentum,
  230. weight_decay=args.weight_decay,
  231. nesterov="nesterov" in opt_name,
  232. )
  233. elif opt_name == "adamw":
  234. optimizer = torch.optim.AdamW(parameters, lr=args.lr, weight_decay=args.weight_decay)
  235. else:
  236. raise RuntimeError(f"Invalid optimizer {args.opt}. Only SGD and AdamW are supported.")
  237. scaler = torch.cuda.amp.GradScaler() if args.amp else None
  238. args.lr_scheduler = args.lr_scheduler.lower()
  239. if args.lr_scheduler == "multisteplr":
  240. lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=args.lr_steps, gamma=args.lr_gamma)
  241. elif args.lr_scheduler == "cosineannealinglr":
  242. lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
  243. else:
  244. raise RuntimeError(
  245. f"Invalid lr scheduler '{args.lr_scheduler}'. Only MultiStepLR and CosineAnnealingLR are supported."
  246. )
  247. if args.resume:
  248. checkpoint = torch.load(args.resume, map_location="cpu", weights_only=True)
  249. model_without_ddp.load_state_dict(checkpoint["model"])
  250. optimizer.load_state_dict(checkpoint["optimizer"])
  251. lr_scheduler.load_state_dict(checkpoint["lr_scheduler"])
  252. args.start_epoch = checkpoint["epoch"] + 1
  253. if args.amp:
  254. scaler.load_state_dict(checkpoint["scaler"])
  255. if args.test_only:
  256. torch.backends.cudnn.deterministic = True
  257. evaluate(model, data_loader_test, device=device)
  258. return
  259. print("Start training")
  260. start_time = time.time()
  261. for epoch in range(args.start_epoch, args.epochs):
  262. if args.distributed:
  263. train_sampler.set_epoch(epoch)
  264. train_one_epoch(model, optimizer, data_loader, device, epoch, args.print_freq, scaler)
  265. lr_scheduler.step()
  266. if args.output_dir:
  267. checkpoint = {
  268. "model": model_without_ddp.state_dict(),
  269. "optimizer": optimizer.state_dict(),
  270. "lr_scheduler": lr_scheduler.state_dict(),
  271. "args": args,
  272. "epoch": epoch,
  273. }
  274. if args.amp:
  275. checkpoint["scaler"] = scaler.state_dict()
  276. utils.save_on_master(checkpoint, os.path.join(args.output_dir, f"model_{epoch}.pth"))
  277. utils.save_on_master(checkpoint, os.path.join(args.output_dir, "checkpoint.pth"))
  278. # evaluate after every epoch
  279. evaluate(model, data_loader_test, device=device)
  280. total_time = time.time() - start_time
  281. total_time_str = str(datetime.timedelta(seconds=int(total_time)))
  282. print(f"Training time {total_time_str}")
  283. if __name__ == "__main__":
  284. args = get_args_parser().parse_args()
  285. main(args)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...