lbfgs.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. import torch
  2. from functools import reduce
  3. from .optimizer import Optimizer
  4. def _cubic_interpolate(x1, f1, g1, x2, f2, g2, bounds=None):
  5. # ported from https://github.com/torch/optim/blob/master/polyinterp.lua
  6. # Compute bounds of interpolation area
  7. if bounds is not None:
  8. xmin_bound, xmax_bound = bounds
  9. else:
  10. xmin_bound, xmax_bound = (x1, x2) if x1 <= x2 else (x2, x1)
  11. # Code for most common case: cubic interpolation of 2 points
  12. # w/ function and derivative values for both
  13. # Solution in this case (where x2 is the farthest point):
  14. # d1 = g1 + g2 - 3*(f1-f2)/(x1-x2);
  15. # d2 = sqrt(d1^2 - g1*g2);
  16. # min_pos = x2 - (x2 - x1)*((g2 + d2 - d1)/(g2 - g1 + 2*d2));
  17. # t_new = min(max(min_pos,xmin_bound),xmax_bound);
  18. d1 = g1 + g2 - 3 * (f1 - f2) / (x1 - x2)
  19. d2_square = d1**2 - g1 * g2
  20. if d2_square >= 0:
  21. d2 = d2_square.sqrt()
  22. if x1 <= x2:
  23. min_pos = x2 - (x2 - x1) * ((g2 + d2 - d1) / (g2 - g1 + 2 * d2))
  24. else:
  25. min_pos = x1 - (x1 - x2) * ((g1 + d2 - d1) / (g1 - g2 + 2 * d2))
  26. return min(max(min_pos, xmin_bound), xmax_bound)
  27. else:
  28. return (xmin_bound + xmax_bound) / 2.
  29. def _strong_wolfe(obj_func,
  30. x,
  31. t,
  32. d,
  33. f,
  34. g,
  35. gtd,
  36. c1=1e-4,
  37. c2=0.9,
  38. tolerance_change=1e-9,
  39. max_ls=25):
  40. # ported from https://github.com/torch/optim/blob/master/lswolfe.lua
  41. d_norm = d.abs().max()
  42. g = g.clone(memory_format=torch.contiguous_format)
  43. # evaluate objective and gradient using initial step
  44. f_new, g_new = obj_func(x, t, d)
  45. ls_func_evals = 1
  46. gtd_new = g_new.dot(d)
  47. # bracket an interval containing a point satisfying the Wolfe criteria
  48. t_prev, f_prev, g_prev, gtd_prev = 0, f, g, gtd
  49. done = False
  50. ls_iter = 0
  51. while ls_iter < max_ls:
  52. # check conditions
  53. if f_new > (f + c1 * t * gtd) or (ls_iter > 1 and f_new >= f_prev):
  54. bracket = [t_prev, t]
  55. bracket_f = [f_prev, f_new]
  56. bracket_g = [g_prev, g_new.clone(memory_format=torch.contiguous_format)]
  57. bracket_gtd = [gtd_prev, gtd_new]
  58. break
  59. if abs(gtd_new) <= -c2 * gtd:
  60. bracket = [t]
  61. bracket_f = [f_new]
  62. bracket_g = [g_new]
  63. done = True
  64. break
  65. if gtd_new >= 0:
  66. bracket = [t_prev, t]
  67. bracket_f = [f_prev, f_new]
  68. bracket_g = [g_prev, g_new.clone(memory_format=torch.contiguous_format)]
  69. bracket_gtd = [gtd_prev, gtd_new]
  70. break
  71. # interpolate
  72. min_step = t + 0.01 * (t - t_prev)
  73. max_step = t * 10
  74. tmp = t
  75. t = _cubic_interpolate(
  76. t_prev,
  77. f_prev,
  78. gtd_prev,
  79. t,
  80. f_new,
  81. gtd_new,
  82. bounds=(min_step, max_step))
  83. # next step
  84. t_prev = tmp
  85. f_prev = f_new
  86. g_prev = g_new.clone(memory_format=torch.contiguous_format)
  87. gtd_prev = gtd_new
  88. f_new, g_new = obj_func(x, t, d)
  89. ls_func_evals += 1
  90. gtd_new = g_new.dot(d)
  91. ls_iter += 1
  92. # reached max number of iterations?
  93. if ls_iter == max_ls:
  94. bracket = [0, t]
  95. bracket_f = [f, f_new]
  96. bracket_g = [g, g_new]
  97. # zoom phase: we now have a point satisfying the criteria, or
  98. # a bracket around it. We refine the bracket until we find the
  99. # exact point satisfying the criteria
  100. insuf_progress = False
  101. # find high and low points in bracket
  102. low_pos, high_pos = (0, 1) if bracket_f[0] <= bracket_f[-1] else (1, 0)
  103. while not done and ls_iter < max_ls:
  104. # line-search bracket is so small
  105. if abs(bracket[1] - bracket[0]) * d_norm < tolerance_change:
  106. break
  107. # compute new trial value
  108. t = _cubic_interpolate(bracket[0], bracket_f[0], bracket_gtd[0],
  109. bracket[1], bracket_f[1], bracket_gtd[1])
  110. # test that we are making sufficient progress:
  111. # in case `t` is so close to boundary, we mark that we are making
  112. # insufficient progress, and if
  113. # + we have made insufficient progress in the last step, or
  114. # + `t` is at one of the boundary,
  115. # we will move `t` to a position which is `0.1 * len(bracket)`
  116. # away from the nearest boundary point.
  117. eps = 0.1 * (max(bracket) - min(bracket))
  118. if min(max(bracket) - t, t - min(bracket)) < eps:
  119. # interpolation close to boundary
  120. if insuf_progress or t >= max(bracket) or t <= min(bracket):
  121. # evaluate at 0.1 away from boundary
  122. if abs(t - max(bracket)) < abs(t - min(bracket)):
  123. t = max(bracket) - eps
  124. else:
  125. t = min(bracket) + eps
  126. insuf_progress = False
  127. else:
  128. insuf_progress = True
  129. else:
  130. insuf_progress = False
  131. # Evaluate new point
  132. f_new, g_new = obj_func(x, t, d)
  133. ls_func_evals += 1
  134. gtd_new = g_new.dot(d)
  135. ls_iter += 1
  136. if f_new > (f + c1 * t * gtd) or f_new >= bracket_f[low_pos]:
  137. # Armijo condition not satisfied or not lower than lowest point
  138. bracket[high_pos] = t
  139. bracket_f[high_pos] = f_new
  140. bracket_g[high_pos] = g_new.clone(memory_format=torch.contiguous_format)
  141. bracket_gtd[high_pos] = gtd_new
  142. low_pos, high_pos = (0, 1) if bracket_f[0] <= bracket_f[1] else (1, 0)
  143. else:
  144. if abs(gtd_new) <= -c2 * gtd:
  145. # Wolfe conditions satisfied
  146. done = True
  147. elif gtd_new * (bracket[high_pos] - bracket[low_pos]) >= 0:
  148. # old high becomes new low
  149. bracket[high_pos] = bracket[low_pos]
  150. bracket_f[high_pos] = bracket_f[low_pos]
  151. bracket_g[high_pos] = bracket_g[low_pos]
  152. bracket_gtd[high_pos] = bracket_gtd[low_pos]
  153. # new point becomes new low
  154. bracket[low_pos] = t
  155. bracket_f[low_pos] = f_new
  156. bracket_g[low_pos] = g_new.clone(memory_format=torch.contiguous_format)
  157. bracket_gtd[low_pos] = gtd_new
  158. # return stuff
  159. t = bracket[low_pos]
  160. f_new = bracket_f[low_pos]
  161. g_new = bracket_g[low_pos]
  162. return f_new, g_new, t, ls_func_evals
  163. class LBFGS(Optimizer):
  164. """Implements L-BFGS algorithm, heavily inspired by `minFunc
  165. <https://www.cs.ubc.ca/~schmidtm/Software/minFunc.html>`_.
  166. .. warning::
  167. This optimizer doesn't support per-parameter options and parameter
  168. groups (there can be only one).
  169. .. warning::
  170. Right now all parameters have to be on a single device. This will be
  171. improved in the future.
  172. .. note::
  173. This is a very memory intensive optimizer (it requires additional
  174. ``param_bytes * (history_size + 1)`` bytes). If it doesn't fit in memory
  175. try reducing the history size, or use a different algorithm.
  176. Args:
  177. lr (float): learning rate (default: 1)
  178. max_iter (int): maximal number of iterations per optimization step
  179. (default: 20)
  180. max_eval (int): maximal number of function evaluations per optimization
  181. step (default: max_iter * 1.25).
  182. tolerance_grad (float): termination tolerance on first order optimality
  183. (default: 1e-5).
  184. tolerance_change (float): termination tolerance on function
  185. value/parameter changes (default: 1e-9).
  186. history_size (int): update history size (default: 100).
  187. line_search_fn (str): either 'strong_wolfe' or None (default: None).
  188. """
  189. def __init__(self,
  190. params,
  191. lr=1,
  192. max_iter=20,
  193. max_eval=None,
  194. tolerance_grad=1e-7,
  195. tolerance_change=1e-9,
  196. history_size=100,
  197. line_search_fn=None):
  198. if max_eval is None:
  199. max_eval = max_iter * 5 // 4
  200. defaults = dict(
  201. lr=lr,
  202. max_iter=max_iter,
  203. max_eval=max_eval,
  204. tolerance_grad=tolerance_grad,
  205. tolerance_change=tolerance_change,
  206. history_size=history_size,
  207. line_search_fn=line_search_fn)
  208. super(LBFGS, self).__init__(params, defaults)
  209. if len(self.param_groups) != 1:
  210. raise ValueError("LBFGS doesn't support per-parameter options "
  211. "(parameter groups)")
  212. self._params = self.param_groups[0]['params']
  213. self._numel_cache = None
  214. def _numel(self):
  215. if self._numel_cache is None:
  216. self._numel_cache = reduce(lambda total, p: total + p.numel(), self._params, 0)
  217. return self._numel_cache
  218. def _gather_flat_grad(self):
  219. views = []
  220. for p in self._params:
  221. if p.grad is None:
  222. view = p.new(p.numel()).zero_()
  223. elif p.grad.is_sparse:
  224. view = p.grad.to_dense().view(-1)
  225. else:
  226. view = p.grad.view(-1)
  227. views.append(view)
  228. return torch.cat(views, 0)
  229. def _add_grad(self, step_size, update):
  230. offset = 0
  231. for p in self._params:
  232. numel = p.numel()
  233. # view as to avoid deprecated pointwise semantics
  234. p.add_(update[offset:offset + numel].view_as(p), alpha=step_size)
  235. offset += numel
  236. assert offset == self._numel()
  237. def _clone_param(self):
  238. return [p.clone(memory_format=torch.contiguous_format) for p in self._params]
  239. def _set_param(self, params_data):
  240. for p, pdata in zip(self._params, params_data):
  241. p.copy_(pdata)
  242. def _directional_evaluate(self, closure, x, t, d):
  243. self._add_grad(t, d)
  244. loss = float(closure())
  245. flat_grad = self._gather_flat_grad()
  246. self._set_param(x)
  247. return loss, flat_grad
  248. @torch.no_grad()
  249. def step(self, closure):
  250. """Performs a single optimization step.
  251. Args:
  252. closure (callable): A closure that reevaluates the model
  253. and returns the loss.
  254. """
  255. assert len(self.param_groups) == 1
  256. # Make sure the closure is always called with grad enabled
  257. closure = torch.enable_grad()(closure)
  258. group = self.param_groups[0]
  259. lr = group['lr']
  260. max_iter = group['max_iter']
  261. max_eval = group['max_eval']
  262. tolerance_grad = group['tolerance_grad']
  263. tolerance_change = group['tolerance_change']
  264. line_search_fn = group['line_search_fn']
  265. history_size = group['history_size']
  266. # NOTE: LBFGS has only global state, but we register it as state for
  267. # the first param, because this helps with casting in load_state_dict
  268. state = self.state[self._params[0]]
  269. state.setdefault('func_evals', 0)
  270. state.setdefault('n_iter', 0)
  271. # evaluate initial f(x) and df/dx
  272. orig_loss = closure()
  273. loss = float(orig_loss)
  274. current_evals = 1
  275. state['func_evals'] += 1
  276. flat_grad = self._gather_flat_grad()
  277. opt_cond = flat_grad.abs().max() <= tolerance_grad
  278. # optimal condition
  279. if opt_cond:
  280. return orig_loss
  281. # tensors cached in state (for tracing)
  282. d = state.get('d')
  283. t = state.get('t')
  284. old_dirs = state.get('old_dirs')
  285. old_stps = state.get('old_stps')
  286. ro = state.get('ro')
  287. H_diag = state.get('H_diag')
  288. prev_flat_grad = state.get('prev_flat_grad')
  289. prev_loss = state.get('prev_loss')
  290. n_iter = 0
  291. # optimize for a max of max_iter iterations
  292. while n_iter < max_iter:
  293. # keep track of nb of iterations
  294. n_iter += 1
  295. state['n_iter'] += 1
  296. ############################################################
  297. # compute gradient descent direction
  298. ############################################################
  299. if state['n_iter'] == 1:
  300. d = flat_grad.neg()
  301. old_dirs = []
  302. old_stps = []
  303. ro = []
  304. H_diag = 1
  305. else:
  306. # do lbfgs update (update memory)
  307. y = flat_grad.sub(prev_flat_grad)
  308. s = d.mul(t)
  309. ys = y.dot(s) # y*s
  310. if ys > 1e-10:
  311. # updating memory
  312. if len(old_dirs) == history_size:
  313. # shift history by one (limited-memory)
  314. old_dirs.pop(0)
  315. old_stps.pop(0)
  316. ro.pop(0)
  317. # store new direction/step
  318. old_dirs.append(y)
  319. old_stps.append(s)
  320. ro.append(1. / ys)
  321. # update scale of initial Hessian approximation
  322. H_diag = ys / y.dot(y) # (y*y)
  323. # compute the approximate (L-BFGS) inverse Hessian
  324. # multiplied by the gradient
  325. num_old = len(old_dirs)
  326. if 'al' not in state:
  327. state['al'] = [None] * history_size
  328. al = state['al']
  329. # iteration in L-BFGS loop collapsed to use just one buffer
  330. q = flat_grad.neg()
  331. for i in range(num_old - 1, -1, -1):
  332. al[i] = old_stps[i].dot(q) * ro[i]
  333. q.add_(old_dirs[i], alpha=-al[i])
  334. # multiply by initial Hessian
  335. # r/d is the final direction
  336. d = r = torch.mul(q, H_diag)
  337. for i in range(num_old):
  338. be_i = old_dirs[i].dot(r) * ro[i]
  339. r.add_(old_stps[i], alpha=al[i] - be_i)
  340. if prev_flat_grad is None:
  341. prev_flat_grad = flat_grad.clone(memory_format=torch.contiguous_format)
  342. else:
  343. prev_flat_grad.copy_(flat_grad)
  344. prev_loss = loss
  345. ############################################################
  346. # compute step length
  347. ############################################################
  348. # reset initial guess for step size
  349. if state['n_iter'] == 1:
  350. t = min(1., 1. / flat_grad.abs().sum()) * lr
  351. else:
  352. t = lr
  353. # directional derivative
  354. gtd = flat_grad.dot(d) # g * d
  355. # directional derivative is below tolerance
  356. if gtd > -tolerance_change:
  357. break
  358. # optional line search: user function
  359. ls_func_evals = 0
  360. if line_search_fn is not None:
  361. # perform line search, using user function
  362. if line_search_fn != "strong_wolfe":
  363. raise RuntimeError("only 'strong_wolfe' is supported")
  364. else:
  365. x_init = self._clone_param()
  366. def obj_func(x, t, d):
  367. return self._directional_evaluate(closure, x, t, d)
  368. loss, flat_grad, t, ls_func_evals = _strong_wolfe(
  369. obj_func, x_init, t, d, loss, flat_grad, gtd)
  370. self._add_grad(t, d)
  371. opt_cond = flat_grad.abs().max() <= tolerance_grad
  372. else:
  373. # no line search, simply move with fixed-step
  374. self._add_grad(t, d)
  375. if n_iter != max_iter:
  376. # re-evaluate function only if not in last iteration
  377. # the reason we do this: in a stochastic setting,
  378. # no use to re-evaluate that function here
  379. with torch.enable_grad():
  380. loss = float(closure())
  381. flat_grad = self._gather_flat_grad()
  382. opt_cond = flat_grad.abs().max() <= tolerance_grad
  383. ls_func_evals = 1
  384. # update func eval
  385. current_evals += ls_func_evals
  386. state['func_evals'] += ls_func_evals
  387. ############################################################
  388. # check conditions
  389. ############################################################
  390. if n_iter == max_iter:
  391. break
  392. if current_evals >= max_eval:
  393. break
  394. # optimal condition
  395. if opt_cond:
  396. break
  397. # lack of progress
  398. if d.mul(t).abs().max() <= tolerance_change:
  399. break
  400. if abs(loss - prev_loss) < tolerance_change:
  401. break
  402. state['d'] = d
  403. state['t'] = t
  404. state['old_dirs'] = old_dirs
  405. state['old_stps'] = old_stps
  406. state['ro'] = ro
  407. state['H_diag'] = H_diag
  408. state['prev_flat_grad'] = prev_flat_grad
  409. state['prev_loss'] = prev_loss
  410. return orig_loss