-
Notifications
You must be signed in to change notification settings - Fork 1
/
train_net_mount.py
381 lines (318 loc) · 11.6 KB
/
train_net_mount.py
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
r"""
Basic training script for PyTorch
"""
# Set up custom environment before nearly anything else is imported
# NOTE: this should be the first import (no not reorder)
from maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:skip
import argparse
import os
import functools
import torch
from maskrcnn_benchmark.config import cfg
from maskrcnn_benchmark.data import make_data_loader
from maskrcnn_benchmark.solver import make_lr_scheduler
from maskrcnn_benchmark.solver import make_optimizer
from maskrcnn_benchmark.engine.inference import inference
from maskrcnn_benchmark.engine.trainer import do_train
from maskrcnn_benchmark.modeling.detector import build_detection_model
from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
from maskrcnn_benchmark.utils.comm import synchronize, get_rank, is_main_process
from maskrcnn_benchmark.utils.miscellaneous import mkdir
from maskrcnn_benchmark.engine.tester import test
import dllogger
from maskrcnn_benchmark.utils.logger import format_step
from azureml_adapter import (
set_environment_variables_for_nccl_backend,
get_local_size,
get_local_rank,
get_global_size,
)
from azureml.core import Dataset, Run
from download_weights import download_weights
def configure_nccl_settings_from_env():
# Start by collecting parallel env info
global_size = get_global_size()
local_size = get_local_size()
print("local_size = {}".format(local_size))
print("global_size = {}".format(global_size))
set_environment_variables_for_nccl_backend(True, master_port=6105)
# See if we can use apex.DistributedDataParallel instead of the torch default,
# and enable mixed-precision via apex.amp
try:
from apex import amp
use_amp = True
except ImportError:
print("Use APEX for multi-precision via apex.amp")
use_amp = False
try:
from apex.parallel import DistributedDataParallel as DDP
use_apex_ddp = True
except ImportError:
print("Use APEX for better performance")
use_apex_ddp = False
def test_and_exchange_map(tester, model, distributed):
results = tester(model=model, distributed=distributed)
# main process only
if is_main_process():
# Note: one indirection due to possibility of multiple test datasets, we only
# care about the first tester returns (parsed results, raw results). In our case,
# don't care about the latter
map_results, raw_results = results[0]
bbox_map = map_results.results["bbox"]["AP"]
segm_map = map_results.results["segm"]["AP"]
else:
bbox_map = 0.0
segm_map = 0.0
if distributed:
map_tensor = torch.tensor(
[bbox_map, segm_map], dtype=torch.float32, device=torch.device("cuda")
)
torch.distributed.broadcast(map_tensor, 0)
bbox_map = map_tensor[0].item()
segm_map = map_tensor[1].item()
return bbox_map, segm_map
def mlperf_test_early_exit(
iteration, iters_per_epoch, tester, model, distributed, min_bbox_map, min_segm_map
):
if iteration > 0 and iteration % iters_per_epoch == 0:
epoch = iteration // iters_per_epoch
dllogger.log(step="PARAMETER", data={"eval_start": True})
bbox_map, segm_map = test_and_exchange_map(tester, model, distributed)
# necessary for correctness
model.train()
dllogger.log(
step=(
iteration,
epoch,
),
data={"BBOX_mAP": bbox_map, "MASK_mAP": segm_map},
)
# terminating condition
if bbox_map >= min_bbox_map and segm_map >= min_segm_map:
dllogger.log(step="PARAMETER", data={"target_accuracy_reached": True})
return True
return False
def train(cfg, local_rank, distributed, fp16, dllogger):
model = build_detection_model(cfg)
device = torch.device(cfg.MODEL.DEVICE)
model.to(device)
optimizer = make_optimizer(cfg, model)
scheduler = make_lr_scheduler(cfg, optimizer)
if use_amp:
# Initialize mixed-precision training
if fp16:
use_mixed_precision = True
else:
use_mixed_precision = cfg.DTYPE == "float16"
amp_opt_level = "O1" if use_mixed_precision else "O0"
model, optimizer = amp.initialize(model, optimizer, opt_level=amp_opt_level)
if distributed:
if use_apex_ddp:
model = DDP(model, delay_allreduce=True)
else:
model = torch.nn.parallel.DistributedDataParallel(
model,
device_ids=[local_rank],
output_device=local_rank,
# this should be removed if we update BatchNorm stats
broadcast_buffers=False,
)
arguments = {}
arguments["iteration"] = 0
output_dir = cfg.OUTPUT_DIR
save_to_disk = get_rank() == 0
checkpointer = DetectronCheckpointer(
cfg, model, optimizer, scheduler, output_dir, save_to_disk
)
extra_checkpoint_data = checkpointer.load(cfg.MODEL.WEIGHT)
arguments.update(extra_checkpoint_data)
data_loader, iters_per_epoch = make_data_loader(
cfg,
is_train=True,
is_distributed=distributed,
start_iter=arguments["iteration"],
)
checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD
# set the callback function to evaluate and potentially
# early exit each epoch
if cfg.PER_EPOCH_EVAL:
per_iter_callback_fn = functools.partial(
mlperf_test_early_exit,
iters_per_epoch=iters_per_epoch,
tester=functools.partial(test, cfg=cfg, dllogger=dllogger),
model=model,
distributed=distributed,
min_bbox_map=cfg.MIN_BBOX_MAP,
min_segm_map=cfg.MIN_MASK_MAP,
)
else:
per_iter_callback_fn = None
do_train(
model,
data_loader,
optimizer,
scheduler,
checkpointer,
device,
checkpoint_period,
arguments,
use_amp,
cfg,
dllogger,
per_iter_end_callback_fn=per_iter_callback_fn,
)
return model, iters_per_epoch
def test_model(cfg, model, distributed, iters_per_epoch, dllogger):
if distributed:
model = model.module
torch.cuda.empty_cache() # TODO check if it helps
iou_types = ("bbox",)
if cfg.MODEL.MASK_ON:
iou_types = iou_types + ("segm",)
output_folders = [None] * len(cfg.DATASETS.TEST)
dataset_names = cfg.DATASETS.TEST
if cfg.OUTPUT_DIR:
for idx, dataset_name in enumerate(dataset_names):
output_folder = os.path.join(cfg.OUTPUT_DIR, "inference", dataset_name)
mkdir(output_folder)
output_folders[idx] = output_folder
data_loaders_val = make_data_loader(cfg, is_train=False, is_distributed=distributed)
results = []
for output_folder, dataset_name, data_loader_val in zip(
output_folders, dataset_names, data_loaders_val
):
result = inference(
model,
data_loader_val,
dataset_name=dataset_name,
iou_types=iou_types,
box_only=cfg.MODEL.RPN_ONLY,
device=cfg.MODEL.DEVICE,
expected_results=cfg.TEST.EXPECTED_RESULTS,
expected_results_sigma_tol=cfg.TEST.EXPECTED_RESULTS_SIGMA_TOL,
output_folder=output_folder,
dllogger=dllogger,
)
synchronize()
results.append(result)
if is_main_process():
map_results, raw_results = results[0]
bbox_map = map_results.results["bbox"]["AP"]
segm_map = map_results.results["segm"]["AP"]
dllogger.log(
step=(
cfg.SOLVER.MAX_ITER,
cfg.SOLVER.MAX_ITER / iters_per_epoch,
),
data={"BBOX_mAP": bbox_map, "MASK_mAP": segm_map},
)
dllogger.log(step=tuple(), data={"BBOX_mAP": bbox_map, "MASK_mAP": segm_map})
def main():
run = Run.get_context()
workspace = run.experiment.workspace
# First thing to do is try to set up from environment
configure_nccl_settings_from_env()
parser = argparse.ArgumentParser(description="PyTorch Object Detection Training")
parser.add_argument(
"--config-file",
default="",
metavar="FILE",
help="path to config file",
type=str,
)
parser.add_argument("--local_rank", type=int, default=os.getenv("LOCAL_RANK", 0))
parser.add_argument(
"--max_steps",
type=int,
default=0,
help="Override number of training steps in the config",
)
parser.add_argument("--dataset", type=str, required=True)
parser.add_argument(
"--skip-test",
dest="skip_test",
help="Do not test the final model",
action="store_true",
)
parser.add_argument("--fp16", help="Mixed precision training", action="store_true")
parser.add_argument("--amp", help="Mixed precision training", action="store_true")
parser.add_argument(
"--skip_checkpoint",
default=False,
action="store_true",
help="Whether to save checkpoints",
)
parser.add_argument(
"--json-summary",
help="Out file for DLLogger",
default="dllogger.out",
type=str,
)
parser.add_argument(
"opts",
help="Modify config options using the command-line",
default=None,
nargs=argparse.REMAINDER,
)
args = parser.parse_args()
args.fp16 = args.fp16 or args.amp
num_gpus = get_global_size()
args.distributed = num_gpus > 1
args.local_rank = get_local_rank()
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
# Redundant option - Override config parameter with command line input
if args.max_steps > 0:
cfg.SOLVER.MAX_ITER = args.max_steps
if args.skip_checkpoint:
cfg.SAVE_CHECKPOINT = False
cfg.freeze()
output_dir = cfg.OUTPUT_DIR
if output_dir:
mkdir(output_dir)
if is_main_process():
dllogger.init(
backends=[
dllogger.JSONStreamBackend(
verbosity=dllogger.Verbosity.VERBOSE, filename=args.json_summary
),
dllogger.StdOutBackend(
verbosity=dllogger.Verbosity.VERBOSE, step_format=format_step
),
]
)
else:
dllogger.init(backends=[])
dllogger.log(step="PARAMETER", data={"gpu_count": num_gpus})
# dllogger.log(step="PARAMETER", data={"environment_info": collect_env_info()})
dllogger.log(step="PARAMETER", data={"config_file": args.config_file})
dllogger.log(step="PARAMETER", data={"config": cfg})
if args.fp16:
fp16 = True
else:
fp16 = False
if args.local_rank == 0:
dllogger.log(step="WEIGHT DOWNLOAD", data={"complete": False})
download_weights(cfg.MODEL.WEIGHT, cfg.PATHS_CATALOG)
dllogger.log(step="WEIGHT DOWNLOAD", data={"complete": True})
dllogger.log(
step="DATASET MOUNT", data={"complete": False, "dataset": args.dataset}
)
coco2017 = Dataset.get_by_name(workspace, args.dataset)
cc2017mount = coco2017.mount("/data")
cc2017mount.start()
dllogger.log(
step="DATASET MOUNT", data={"complete": True, "dataset": args.dataset}
)
if args.distributed:
torch.cuda.set_device(args.local_rank)
torch.distributed.init_process_group(backend="nccl", init_method="env://")
synchronize()
model, iters_per_epoch = train(
cfg, args.local_rank, args.distributed, fp16, dllogger
)
if __name__ == "__main__":
main()
dllogger.log(step=tuple(), data={})
dllogger.flush()