adahessian.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. """ AdaHessian Optimizer
  2. Lifted from https://github.com/davda54/ada-hessian/blob/master/ada_hessian.py
  3. Originally licensed MIT, Copyright 2020, David Samuel
  4. """
  5. import torch
  6. class Adahessian(torch.optim.Optimizer):
  7. """
  8. Implements the AdaHessian algorithm from "ADAHESSIAN: An Adaptive Second OrderOptimizer for Machine Learning"
  9. Arguments:
  10. params (iterable): iterable of parameters to optimize or dicts defining parameter groups
  11. lr (float, optional): learning rate (default: 0.1)
  12. betas ((float, float), optional): coefficients used for computing running averages of gradient and the
  13. squared hessian trace (default: (0.9, 0.999))
  14. eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8)
  15. weight_decay (float, optional): weight decay (L2 penalty) (default: 0.0)
  16. hessian_power (float, optional): exponent of the hessian trace (default: 1.0)
  17. update_each (int, optional): compute the hessian trace approximation only after *this* number of steps
  18. (to save time) (default: 1)
  19. n_samples (int, optional): how many times to sample `z` for the approximation of the hessian trace (default: 1)
  20. """
  21. def __init__(
  22. self,
  23. params,
  24. lr=0.1,
  25. betas=(0.9, 0.999),
  26. eps=1e-8,
  27. weight_decay=0.0,
  28. hessian_power=1.0,
  29. update_each=1,
  30. n_samples=1,
  31. avg_conv_kernel=False,
  32. ):
  33. if not 0.0 <= lr:
  34. raise ValueError(f"Invalid learning rate: {lr}")
  35. if not 0.0 <= eps:
  36. raise ValueError(f"Invalid epsilon value: {eps}")
  37. if not 0.0 <= betas[0] < 1.0:
  38. raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
  39. if not 0.0 <= betas[1] < 1.0:
  40. raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
  41. if not 0.0 <= hessian_power <= 1.0:
  42. raise ValueError(f"Invalid Hessian power value: {hessian_power}")
  43. self.n_samples = n_samples
  44. self.update_each = update_each
  45. self.avg_conv_kernel = avg_conv_kernel
  46. # use a separate generator that deterministically generates the same `z`s across all GPUs in case of distributed training
  47. self.seed = 2147483647
  48. self.generator = torch.Generator().manual_seed(self.seed)
  49. defaults = dict(
  50. lr=lr,
  51. betas=betas,
  52. eps=eps,
  53. weight_decay=weight_decay,
  54. hessian_power=hessian_power,
  55. )
  56. super(Adahessian, self).__init__(params, defaults)
  57. for p in self.get_params():
  58. p.hess = 0.0
  59. self.state[p]["hessian step"] = 0
  60. @property
  61. def is_second_order(self):
  62. return True
  63. def get_params(self):
  64. """
  65. Gets all parameters in all param_groups with gradients
  66. """
  67. return (p for group in self.param_groups for p in group['params'] if p.requires_grad)
  68. def zero_hessian(self):
  69. """
  70. Zeros out the accumulated hessian traces.
  71. """
  72. for p in self.get_params():
  73. if not isinstance(p.hess, float) and self.state[p]["hessian step"] % self.update_each == 0:
  74. p.hess.zero_()
  75. @torch.no_grad()
  76. def set_hessian(self):
  77. """
  78. Computes the Hutchinson approximation of the hessian trace and accumulates it for each trainable parameter.
  79. """
  80. params = []
  81. for p in filter(lambda p: p.grad is not None, self.get_params()):
  82. if self.state[p]["hessian step"] % self.update_each == 0: # compute the trace only each `update_each` step
  83. params.append(p)
  84. self.state[p]["hessian step"] += 1
  85. if len(params) == 0:
  86. return
  87. if self.generator.device != params[0].device: # hackish way of casting the generator to the right device
  88. self.generator = torch.Generator(params[0].device).manual_seed(self.seed)
  89. grads = [p.grad for p in params]
  90. for i in range(self.n_samples):
  91. # Rademacher distribution {-1.0, 1.0}
  92. zs = [torch.randint(0, 2, p.size(), generator=self.generator, device=p.device) * 2.0 - 1.0 for p in params]
  93. h_zs = torch.autograd.grad(
  94. grads, params, grad_outputs=zs, only_inputs=True, retain_graph=i < self.n_samples - 1)
  95. for h_z, z, p in zip(h_zs, zs, params):
  96. p.hess += h_z * z / self.n_samples # approximate the expected values of z*(H@z)
  97. @torch.no_grad()
  98. def step(self, closure=None):
  99. """
  100. Performs a single optimization step.
  101. Arguments:
  102. closure (callable, optional) -- a closure that reevaluates the model and returns the loss (default: None)
  103. """
  104. loss = None
  105. if closure is not None:
  106. loss = closure()
  107. self.zero_hessian()
  108. self.set_hessian()
  109. for group in self.param_groups:
  110. for p in group['params']:
  111. if p.grad is None or p.hess is None:
  112. continue
  113. if self.avg_conv_kernel and p.dim() == 4:
  114. p.hess = torch.abs(p.hess).mean(dim=[2, 3], keepdim=True).expand_as(p.hess).clone()
  115. # Perform correct stepweight decay as in AdamW
  116. p.mul_(1 - group['lr'] * group['weight_decay'])
  117. state = self.state[p]
  118. # State initialization
  119. if len(state) == 1:
  120. state['step'] = 0
  121. # Exponential moving average of gradient values
  122. state['exp_avg'] = torch.zeros_like(p)
  123. # Exponential moving average of Hessian diagonal square values
  124. state['exp_hessian_diag_sq'] = torch.zeros_like(p)
  125. exp_avg, exp_hessian_diag_sq = state['exp_avg'], state['exp_hessian_diag_sq']
  126. beta1, beta2 = group['betas']
  127. state['step'] += 1
  128. # Decay the first and second moment running average coefficient
  129. exp_avg.mul_(beta1).add_(p.grad, alpha=1 - beta1)
  130. exp_hessian_diag_sq.mul_(beta2).addcmul_(p.hess, p.hess, value=1 - beta2)
  131. bias_correction1 = 1 - beta1 ** state['step']
  132. bias_correction2 = 1 - beta2 ** state['step']
  133. k = group['hessian_power']
  134. denom = (exp_hessian_diag_sq / bias_correction2).pow_(k / 2).add_(group['eps'])
  135. # make update
  136. step_size = group['lr'] / bias_correction1
  137. p.addcdiv_(exp_avg, denom, value=-step_size)
  138. return loss