File size: 18,193 Bytes
8c212a5 |
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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 |
# python3.7
"""Contains the base class for runner.
This runner can be used for both training and inference with multi-threads.
"""
import os
import json
from copy import deepcopy
import torch
import torch.distributed as dist
from datasets import BaseDataset
from datasets import IterDataLoader
from models import build_model
from . import controllers
from . import losses
from . import misc
from .optimizer import build_optimizers
from .running_stats import RunningStats
def _strip_state_dict_prefix(state_dict, prefix='module.'):
"""Removes the name prefix in checkpoint.
Basically, when the model is deployed in parallel, the prefix `module.` will
be added to the saved checkpoint. This function is used to remove the
prefix, which is friendly to checkpoint loading.
Args:
state_dict: The state dict where the variable names are processed.
prefix: The prefix to remove. (default: `module.`)
"""
if not all(key.startswith(prefix) for key in state_dict.keys()):
return state_dict
stripped_state_dict = dict()
for key in state_dict:
stripped_state_dict[key.replace(prefix, '')] = state_dict[key]
return stripped_state_dict
class BaseRunner(object):
"""Defines the base runner class."""
def __init__(self, config, logger):
self._name = self.__class__.__name__
self._config = deepcopy(config)
self.logger = logger
self.work_dir = self.config.work_dir
os.makedirs(self.work_dir, exist_ok=True)
self.logger.info('Running Configuration:')
config_str = json.dumps(self.config, indent=4).replace('"', '\'')
self.logger.print(config_str + '\n')
with open(os.path.join(self.work_dir, 'config.json'), 'w') as f:
json.dump(self.config, f, indent=4)
self._rank = dist.get_rank()
self._world_size = dist.get_world_size()
self.batch_size = self.config.batch_size
self.val_batch_size = self.config.get('val_batch_size', self.batch_size)
self._iter = 0
self._start_iter = 0
self.seen_img = 0
self.total_iters = self.config.get('total_iters', 0)
if self.total_iters == 0 and self.config.get('total_img', 0) > 0:
total_image = self.config.get('total_img')
total_batch = self.world_size * self.batch_size
self.total_iters = int(total_image / total_batch + 0.5)
self.mode = None
self.train_loader = None
self.val_loader = None
self.models = dict()
self.optimizers = dict()
self.lr_schedulers = dict()
self.controllers = []
self.loss = None
self.running_stats = RunningStats()
self.start_time = 0
self.end_time = 0
self.timer = controllers.Timer()
self.timer.start(self)
self.build_models()
self.build_controllers()
def finish(self):
"""Finishes runner by ending controllers and timer."""
for controller in self.controllers:
controller.end(self)
self.timer.end(self)
self.logger.info(f'Finish runner in '
f'{misc.format_time(self.end_time - self.start_time)}')
@property
def name(self):
"""Returns the name of the runner."""
return self._name
@property
def config(self):
"""Returns the configuration of the runner."""
return self._config
@property
def rank(self):
"""Returns the rank of the current runner."""
return self._rank
@property
def world_size(self):
"""Returns the world size."""
return self._world_size
@property
def iter(self):
"""Returns the current iteration."""
return self._iter
@property
def start_iter(self):
"""Returns the start iteration."""
return self._start_iter
def convert_epoch_to_iter(self, epoch):
"""Converts number of epochs to number of iterations."""
return int(epoch * len(self.train_loader) + 0.5)
def build_dataset(self, mode):
"""Builds train/val dataset."""
if not hasattr(self.config, 'data'):
return
assert isinstance(mode, str)
mode = mode.lower()
self.logger.info(f'Building `{mode}` dataset ...')
if mode not in ['train', 'val']:
raise ValueError(f'Invalid dataset mode `{mode}`!')
dataset = BaseDataset(**self.config.data[mode])
if mode == 'train':
self.train_loader = IterDataLoader(
dataset=dataset,
batch_size=self.batch_size,
shuffle=True,
num_workers=self.config.data.get('num_workers', 2),
current_iter=self.iter,
repeat=self.config.data.get('repeat', 1))
elif mode == 'val':
self.val_loader = IterDataLoader(
dataset=dataset,
batch_size=self.val_batch_size,
shuffle=False,
num_workers=self.config.data.get('num_workers', 2),
current_iter=0,
repeat=1)
else:
raise NotImplementedError(f'Not implemented dataset mode `{mode}`!')
self.logger.info(f'Finish building `{mode}` dataset.')
def build_models(self):
"""Builds models, optimizers, and learning rate schedulers."""
self.logger.info(f'Building models ...')
lr_config = dict()
opt_config = dict()
for module, module_config in self.config.modules.items():
model_config = module_config['model']
self.models[module] = build_model(module=module, **model_config)
self.models[module].cuda()
opt_config[module] = module_config.get('opt', None)
lr_config[module] = module_config.get('lr', None)
build_optimizers(opt_config, self)
self.controllers.append(controllers.LRScheduler(lr_config))
self.logger.info(f'Finish building models.')
model_info = 'Model structures:\n'
model_info += '==============================================\n'
for module in self.models:
model_info += f'{module}\n'
model_info += '----------------------------------------------\n'
model_info += str(self.models[module])
model_info += '\n'
model_info += "==============================================\n"
self.logger.info(model_info)
def distribute(self):
"""Sets `self.model` as `torch.nn.parallel.DistributedDataParallel`."""
for name in self.models:
self.models[name] = torch.nn.parallel.DistributedDataParallel(
module=self.models[name],
device_ids=[torch.cuda.current_device()],
broadcast_buffers=False,
find_unused_parameters=True)
@staticmethod
def get_module(model):
"""Handles distributed model."""
if hasattr(model, 'module'):
return model.module
return model
def build_controllers(self):
"""Builds additional controllers besides LRScheduler."""
if not hasattr(self.config, 'controllers'):
return
self.logger.info(f'Building controllers ...')
for key, ctrl_config in self.config.controllers.items():
self.controllers.append(getattr(controllers, key)(ctrl_config))
self.controllers.sort(key=lambda x: x.priority)
for controller in self.controllers:
controller.start(self)
self.logger.info(f'Finish building controllers.')
def build_loss(self):
"""Builds loss functions."""
if not hasattr(self.config, 'loss'):
return
self.logger.info(f'Building loss function ...')
loss_config = deepcopy(self.config.loss)
loss_type = loss_config.pop('type')
self.loss = getattr(losses, loss_type)(self, **loss_config)
self.logger.info(f'Finish building loss function.')
def pre_execute_controllers(self):
"""Pre-executes all controllers in order of priority."""
for controller in self.controllers:
controller.pre_execute(self)
def post_execute_controllers(self):
"""Post-executes all controllers in order of priority."""
for controller in self.controllers:
controller.post_execute(self)
def cpu(self):
"""Puts models to CPU."""
for name in self.models:
self.models[name].cpu()
def cuda(self):
"""Puts models to CUDA."""
for name in self.models:
self.models[name].cuda()
def set_model_requires_grad(self, name, requires_grad):
"""Sets the `requires_grad` configuration for a particular model."""
for param in self.models[name].parameters():
param.requires_grad = requires_grad
def set_models_requires_grad(self, requires_grad):
"""Sets the `requires_grad` configuration for all models."""
for name in self.models:
self.set_model_requires_grad(name, requires_grad)
def set_model_mode(self, name, mode):
"""Sets the `train/val` mode for a particular model."""
if isinstance(mode, str):
mode = mode.lower()
if mode == 'train' or mode is True:
self.models[name].train()
elif mode in ['val', 'test', 'eval'] or mode is False:
self.models[name].eval()
else:
raise ValueError(f'Invalid model mode `{mode}`!')
def set_mode(self, mode):
"""Sets the `train/val` mode for all models."""
self.mode = mode
for name in self.models:
self.set_model_mode(name, mode)
def train_step(self, data, **train_kwargs):
"""Executes one training step."""
raise NotImplementedError('Should be implemented in derived class.')
def train(self, **train_kwargs):
"""Training function."""
self.set_mode('train')
self.distribute()
self.build_dataset('train')
self.build_loss()
self.logger.print()
self.logger.info(f'Start training.')
if self.total_iters == 0:
total_epochs = self.config.get('total_epochs', 0)
self.total_iters = self.convert_epoch_to_iter(total_epochs)
assert self.total_iters > 0
while self.iter < self.total_iters:
self._iter += 1
self.pre_execute_controllers()
data_batch = next(self.train_loader)
self.timer.pre_execute(self)
for key in data_batch:
assert data_batch[key].shape[0] == self.batch_size
data_batch[key] = data_batch[key].cuda(
torch.cuda.current_device(), non_blocking=True)
self.train_step(data_batch, **train_kwargs)
self.seen_img += self.batch_size * self.world_size
self.timer.post_execute(self)
self.post_execute_controllers()
self.finish()
def val(self, **val_kwargs):
"""Validation function."""
raise NotImplementedError('Should be implemented in derived class.')
def save(self,
filepath,
running_metadata=True,
learning_rate=True,
optimizer=True,
running_stats=False):
"""Saves the current running status.
Args:
filepath: File path to save the checkpoint.
running_metadata: Whether to save the running metadata, such as
batch size, current iteration, etc. (default: True)
learning_rate: Whether to save the learning rate. (default: True)
optimizer: Whether to save the optimizer. (default: True)
running_stats: Whether to save the running stats. (default: False)
"""
checkpoint = dict()
# Models.
checkpoint['models'] = dict()
for name, model in self.models.items():
checkpoint['models'][name] = self.get_module(model).state_dict()
# Running metadata.
if running_metadata:
checkpoint['running_metadata'] = {
'iter': self.iter,
'seen_img': self.seen_img,
}
# Optimizers.
if optimizer:
checkpoint['optimizers'] = dict()
for opt_name, opt in self.optimizers.items():
checkpoint['optimizers'][opt_name] = opt.state_dict()
# Learning rates.
if learning_rate:
checkpoint['learning_rates'] = dict()
for lr_name, lr in self.lr_schedulers.items():
checkpoint['learning_rates'][lr_name] = lr.state_dict()
# Running stats.
# TODO: Test saving and loading running stats.
if running_stats:
checkpoint['running_stats'] = self.running_stats
# Save checkpoint.
os.makedirs(os.path.dirname(filepath), exist_ok=True)
torch.save(checkpoint, filepath)
self.logger.info(f'Successfully saved checkpoint to `{filepath}`.')
def load(self,
filepath,
running_metadata=True,
learning_rate=True,
optimizer=True,
running_stats=False,
map_location='cpu'):
"""Loads previous running status.
Args:
filepath: File path to load the checkpoint.
running_metadata: Whether to load the running metadata, such as
batch size, current iteration, etc. (default: True)
learning_rate: Whether to load the learning rate. (default: True)
optimizer: Whether to load the optimizer. (default: True)
running_stats: Whether to load the running stats. (default: False)
map_location: Map location used for model loading. (default: `cpu`)
"""
self.logger.info(f'Resuming from checkpoint `{filepath}` ...')
if not os.path.isfile(filepath):
raise IOError(f'Checkpoint `{filepath}` does not exist!')
map_location = map_location.lower()
assert map_location in ['cpu', 'gpu']
if map_location == 'gpu':
device = torch.cuda.current_device()
map_location = lambda storage, location: storage.cuda(device)
checkpoint = torch.load(filepath, map_location=map_location)
# Load models.
if 'models' not in checkpoint:
checkpoint = {'models': checkpoint}
for model_name, model in self.models.items():
if model_name not in checkpoint['models']:
self.logger.warning(f'Model `{model_name}` is not included in '
f'the checkpoint, and hence will NOT be '
f'loaded!')
continue
state_dict = _strip_state_dict_prefix(
checkpoint['models'][model_name])
model.load_state_dict(state_dict)
self.logger.info(f' Successfully loaded model `{model_name}`.')
# Load running metedata.
if running_metadata:
if 'running_metadata' not in checkpoint:
self.logger.warning(f'Running metadata is not included in the '
f'checkpoint, and hence will NOT be '
f'loaded!')
else:
self._iter = checkpoint['running_metadata']['iter']
self._start_iter = self._iter
self.seen_img = checkpoint['running_metadata']['seen_img']
# Load optimizers.
if optimizer:
if 'optimizers' not in checkpoint:
self.logger.warning(f'Optimizers are not included in the '
f'checkpoint, and hence will NOT be '
f'loaded!')
else:
for opt_name, opt in self.optimizers.items():
if opt_name not in checkpoint['optimizers']:
self.logger.warning(f'Optimizer `{opt_name}` is not '
f'included in the checkpoint, and '
f'hence will NOT be loaded!')
continue
opt.load_state_dict(checkpoint['optimizers'][opt_name])
self.logger.info(f' Successfully loaded optimizer '
f'`{opt_name}`.')
# Load learning rates.
if learning_rate:
if 'learning_rates' not in checkpoint:
self.logger.warning(f'Learning rates are not included in the '
f'checkpoint, and hence will NOT be '
f'loaded!')
else:
for lr_name, lr in self.lr_schedulers.items():
if lr_name not in checkpoint['learning_rates']:
self.logger.warning(f'Learning rate `{lr_name}` is not '
f'included in the checkpoint, and '
f'hence will NOT be loaded!')
continue
lr.load_state_dict(checkpoint['learning_rates'][lr_name])
self.logger.info(f' Successfully loaded learning rate '
f'`{lr_name}`.')
# Load running stats.
if running_stats:
if 'running_stats' not in checkpoint:
self.logger.warning(f'Running stats is not included in the '
f'checkpoint, and hence will NOT be '
f'loaded!')
else:
self.running_stats = deepcopy(checkpoint['running_stats'])
self.logger.info(f' Successfully loaded running stats.')
# Log message.
tailing_message = ''
if running_metadata and 'running_metadata' in checkpoint:
tailing_message = f' (iteration {self.iter})'
self.logger.info(f'Successfully resumed from checkpoint `{filepath}`.'
f'{tailing_message}')
|