yolox_mode_switch_hook.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. from typing import Sequence
  3. from mmengine.hooks import Hook
  4. from mmengine.model import is_model_wrapper
  5. from mmdet.registry import HOOKS
  6. @HOOKS.register_module()
  7. class YOLOXModeSwitchHook(Hook):
  8. """Switch the mode of YOLOX during training.
  9. This hook turns off the mosaic and mixup data augmentation and switches
  10. to use L1 loss in bbox_head.
  11. Args:
  12. num_last_epochs (int): The number of latter epochs in the end of the
  13. training to close the data augmentation and switch to L1 loss.
  14. Defaults to 15.
  15. skip_type_keys (Sequence[str], optional): Sequence of type string to be
  16. skip pipeline. Defaults to ('Mosaic', 'RandomAffine', 'MixUp').
  17. """
  18. def __init__(
  19. self,
  20. num_last_epochs: int = 15,
  21. skip_type_keys: Sequence[str] = ('Mosaic', 'RandomAffine', 'MixUp')
  22. ) -> None:
  23. self.num_last_epochs = num_last_epochs
  24. self.skip_type_keys = skip_type_keys
  25. self._restart_dataloader = False
  26. def before_train_epoch(self, runner) -> None:
  27. """Close mosaic and mixup augmentation and switches to use L1 loss."""
  28. epoch = runner.epoch
  29. train_loader = runner.train_dataloader
  30. model = runner.model
  31. # TODO: refactor after mmengine using model wrapper
  32. if is_model_wrapper(model):
  33. model = model.module
  34. if (epoch + 1) == runner.max_epochs - self.num_last_epochs:
  35. runner.logger.info('No mosaic and mixup aug now!')
  36. # The dataset pipeline cannot be updated when persistent_workers
  37. # is True, so we need to force the dataloader's multi-process
  38. # restart. This is a very hacky approach.
  39. train_loader.dataset.update_skip_type_keys(self.skip_type_keys)
  40. if hasattr(train_loader, 'persistent_workers'
  41. ) and train_loader.persistent_workers is True:
  42. train_loader._DataLoader__initialized = False
  43. train_loader._iterator = None
  44. self._restart_dataloader = True
  45. runner.logger.info('Add additional L1 loss now!')
  46. model.bbox_head.use_l1 = True
  47. else:
  48. # Once the restart is complete, we need to restore
  49. # the initialization flag.
  50. if self._restart_dataloader:
  51. train_loader._DataLoader__initialized = True