-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add gradient cumulative optimizer #784
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -34,6 +34,38 @@ def after_train_iter(self, runner): | |
runner.optimizer.step() | ||
|
||
|
||
@HOOKS.register_module() | ||
class GradientCumulativeOptimizerHook(OptimizerHook): | ||
|
||
def __init__(self, grad_clip=None, cumulative_iters=1): | ||
super(GradientCumulativeOptimizerHook, self).__init__(grad_clip) | ||
self.cumulative_iters = cumulative_iters | ||
self.divisible_ietrs = 0 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
self.remainder_iters = 0 | ||
self.initialized = False | ||
|
||
def _init(self, runner): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please put a warning for the usage of BN. |
||
self.divisible_ietrs = runner.max_iters // self.cumulative_iters * self.cumulative_iters | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is another corner case where users resume from |
||
self.remainder_iters = runner.max_iters % self.cumulative_iters | ||
self.initialized = True | ||
|
||
def after_train_iter(self, runner): | ||
if not self.initialized: | ||
self._init(runner) | ||
loss_factor = self.cumulative_iters if runner.iter < self.divisible_ietrs else self.remainder_iters | ||
runner.outputs['loss'] = runner.outputs['loss'] / loss_factor | ||
runner.outputs['loss'].backward() | ||
if (runner.iter + 1) % self.cumulative_iters == 0 or runner.iter == runner.max_iters: | ||
runner.optimizer.step() | ||
if self.grad_clip is not None: | ||
grad_norm = self.clip_grads(runner.model.parameters()) | ||
if grad_norm is not None: | ||
# Add grad norm to the logger | ||
runner.log_buffer.update({'grad_norm': float(grad_norm)}, | ||
runner.outputs['num_samples']) | ||
runner.optimizer.zero_grad() | ||
|
||
|
||
@HOOKS.register_module() | ||
class Fp16OptimizerHook(OptimizerHook): | ||
"""FP16 optimizer hook. | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Docs are missing.