torchzero 0.3.11__py3-none-any.whl → 0.3.13__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. tests/test_opts.py +95 -69
  2. tests/test_tensorlist.py +8 -7
  3. torchzero/__init__.py +1 -1
  4. torchzero/core/__init__.py +2 -2
  5. torchzero/core/module.py +225 -72
  6. torchzero/core/reformulation.py +65 -0
  7. torchzero/core/transform.py +44 -24
  8. torchzero/modules/__init__.py +13 -5
  9. torchzero/modules/{optimizers → adaptive}/__init__.py +5 -2
  10. torchzero/modules/adaptive/adagrad.py +356 -0
  11. torchzero/modules/{optimizers → adaptive}/adahessian.py +53 -52
  12. torchzero/modules/{optimizers → adaptive}/adam.py +0 -3
  13. torchzero/modules/{optimizers → adaptive}/adan.py +26 -40
  14. torchzero/modules/{optimizers → adaptive}/adaptive_heavyball.py +3 -6
  15. torchzero/modules/adaptive/aegd.py +54 -0
  16. torchzero/modules/{optimizers → adaptive}/esgd.py +1 -1
  17. torchzero/modules/{optimizers/ladagrad.py → adaptive/lmadagrad.py} +42 -39
  18. torchzero/modules/{optimizers → adaptive}/mars.py +24 -36
  19. torchzero/modules/adaptive/matrix_momentum.py +146 -0
  20. torchzero/modules/{optimizers → adaptive}/msam.py +14 -12
  21. torchzero/modules/{optimizers → adaptive}/muon.py +19 -20
  22. torchzero/modules/adaptive/natural_gradient.py +175 -0
  23. torchzero/modules/{optimizers → adaptive}/rprop.py +0 -2
  24. torchzero/modules/{optimizers → adaptive}/sam.py +1 -1
  25. torchzero/modules/{optimizers → adaptive}/shampoo.py +8 -4
  26. torchzero/modules/{optimizers → adaptive}/soap.py +27 -50
  27. torchzero/modules/{optimizers → adaptive}/sophia_h.py +2 -3
  28. torchzero/modules/clipping/clipping.py +85 -92
  29. torchzero/modules/clipping/ema_clipping.py +5 -5
  30. torchzero/modules/conjugate_gradient/__init__.py +11 -0
  31. torchzero/modules/{quasi_newton → conjugate_gradient}/cg.py +355 -369
  32. torchzero/modules/experimental/__init__.py +9 -32
  33. torchzero/modules/experimental/dct.py +2 -2
  34. torchzero/modules/experimental/fft.py +2 -2
  35. torchzero/modules/experimental/gradmin.py +4 -3
  36. torchzero/modules/experimental/l_infinity.py +111 -0
  37. torchzero/modules/{momentum/experimental.py → experimental/momentum.py} +3 -40
  38. torchzero/modules/experimental/newton_solver.py +79 -17
  39. torchzero/modules/experimental/newtonnewton.py +27 -14
  40. torchzero/modules/experimental/scipy_newton_cg.py +105 -0
  41. torchzero/modules/experimental/structural_projections.py +1 -1
  42. torchzero/modules/functional.py +50 -14
  43. torchzero/modules/grad_approximation/fdm.py +19 -20
  44. torchzero/modules/grad_approximation/forward_gradient.py +4 -2
  45. torchzero/modules/grad_approximation/grad_approximator.py +43 -47
  46. torchzero/modules/grad_approximation/rfdm.py +144 -122
  47. torchzero/modules/higher_order/__init__.py +1 -1
  48. torchzero/modules/higher_order/higher_order_newton.py +31 -23
  49. torchzero/modules/least_squares/__init__.py +1 -0
  50. torchzero/modules/least_squares/gn.py +161 -0
  51. torchzero/modules/line_search/__init__.py +2 -2
  52. torchzero/modules/line_search/_polyinterp.py +289 -0
  53. torchzero/modules/line_search/adaptive.py +69 -44
  54. torchzero/modules/line_search/backtracking.py +83 -70
  55. torchzero/modules/line_search/line_search.py +159 -68
  56. torchzero/modules/line_search/scipy.py +1 -1
  57. torchzero/modules/line_search/strong_wolfe.py +319 -218
  58. torchzero/modules/misc/__init__.py +8 -0
  59. torchzero/modules/misc/debug.py +4 -4
  60. torchzero/modules/misc/escape.py +9 -7
  61. torchzero/modules/misc/gradient_accumulation.py +88 -22
  62. torchzero/modules/misc/homotopy.py +59 -0
  63. torchzero/modules/misc/misc.py +82 -15
  64. torchzero/modules/misc/multistep.py +47 -11
  65. torchzero/modules/misc/regularization.py +5 -9
  66. torchzero/modules/misc/split.py +55 -35
  67. torchzero/modules/misc/switch.py +1 -1
  68. torchzero/modules/momentum/__init__.py +1 -5
  69. torchzero/modules/momentum/averaging.py +3 -3
  70. torchzero/modules/momentum/cautious.py +42 -47
  71. torchzero/modules/momentum/momentum.py +35 -1
  72. torchzero/modules/ops/__init__.py +9 -1
  73. torchzero/modules/ops/binary.py +9 -8
  74. torchzero/modules/{momentum/ema.py → ops/higher_level.py} +10 -33
  75. torchzero/modules/ops/multi.py +15 -15
  76. torchzero/modules/ops/reduce.py +1 -1
  77. torchzero/modules/ops/utility.py +12 -8
  78. torchzero/modules/projections/projection.py +4 -4
  79. torchzero/modules/quasi_newton/__init__.py +1 -16
  80. torchzero/modules/quasi_newton/damping.py +105 -0
  81. torchzero/modules/quasi_newton/diagonal_quasi_newton.py +167 -163
  82. torchzero/modules/quasi_newton/lbfgs.py +256 -200
  83. torchzero/modules/quasi_newton/lsr1.py +167 -132
  84. torchzero/modules/quasi_newton/quasi_newton.py +346 -446
  85. torchzero/modules/restarts/__init__.py +7 -0
  86. torchzero/modules/restarts/restars.py +252 -0
  87. torchzero/modules/second_order/__init__.py +2 -1
  88. torchzero/modules/second_order/multipoint.py +238 -0
  89. torchzero/modules/second_order/newton.py +133 -88
  90. torchzero/modules/second_order/newton_cg.py +141 -80
  91. torchzero/modules/smoothing/__init__.py +1 -1
  92. torchzero/modules/smoothing/sampling.py +300 -0
  93. torchzero/modules/step_size/__init__.py +1 -1
  94. torchzero/modules/step_size/adaptive.py +312 -47
  95. torchzero/modules/termination/__init__.py +14 -0
  96. torchzero/modules/termination/termination.py +207 -0
  97. torchzero/modules/trust_region/__init__.py +5 -0
  98. torchzero/modules/trust_region/cubic_regularization.py +170 -0
  99. torchzero/modules/trust_region/dogleg.py +92 -0
  100. torchzero/modules/trust_region/levenberg_marquardt.py +128 -0
  101. torchzero/modules/trust_region/trust_cg.py +97 -0
  102. torchzero/modules/trust_region/trust_region.py +350 -0
  103. torchzero/modules/variance_reduction/__init__.py +1 -0
  104. torchzero/modules/variance_reduction/svrg.py +208 -0
  105. torchzero/modules/weight_decay/weight_decay.py +65 -64
  106. torchzero/modules/zeroth_order/__init__.py +1 -0
  107. torchzero/modules/zeroth_order/cd.py +359 -0
  108. torchzero/optim/root.py +65 -0
  109. torchzero/optim/utility/split.py +8 -8
  110. torchzero/optim/wrappers/directsearch.py +0 -1
  111. torchzero/optim/wrappers/fcmaes.py +3 -2
  112. torchzero/optim/wrappers/nlopt.py +0 -2
  113. torchzero/optim/wrappers/optuna.py +2 -2
  114. torchzero/optim/wrappers/scipy.py +81 -22
  115. torchzero/utils/__init__.py +40 -4
  116. torchzero/utils/compile.py +1 -1
  117. torchzero/utils/derivatives.py +123 -111
  118. torchzero/utils/linalg/__init__.py +9 -2
  119. torchzero/utils/linalg/linear_operator.py +329 -0
  120. torchzero/utils/linalg/matrix_funcs.py +2 -2
  121. torchzero/utils/linalg/orthogonalize.py +2 -1
  122. torchzero/utils/linalg/qr.py +2 -2
  123. torchzero/utils/linalg/solve.py +226 -154
  124. torchzero/utils/metrics.py +83 -0
  125. torchzero/utils/python_tools.py +6 -0
  126. torchzero/utils/tensorlist.py +105 -34
  127. torchzero/utils/torch_tools.py +9 -4
  128. torchzero-0.3.13.dist-info/METADATA +14 -0
  129. torchzero-0.3.13.dist-info/RECORD +166 -0
  130. {torchzero-0.3.11.dist-info → torchzero-0.3.13.dist-info}/top_level.txt +0 -1
  131. docs/source/conf.py +0 -59
  132. docs/source/docstring template.py +0 -46
  133. torchzero/modules/experimental/absoap.py +0 -253
  134. torchzero/modules/experimental/adadam.py +0 -118
  135. torchzero/modules/experimental/adamY.py +0 -131
  136. torchzero/modules/experimental/adam_lambertw.py +0 -149
  137. torchzero/modules/experimental/adaptive_step_size.py +0 -90
  138. torchzero/modules/experimental/adasoap.py +0 -177
  139. torchzero/modules/experimental/cosine.py +0 -214
  140. torchzero/modules/experimental/cubic_adam.py +0 -97
  141. torchzero/modules/experimental/eigendescent.py +0 -120
  142. torchzero/modules/experimental/etf.py +0 -195
  143. torchzero/modules/experimental/exp_adam.py +0 -113
  144. torchzero/modules/experimental/expanded_lbfgs.py +0 -141
  145. torchzero/modules/experimental/hnewton.py +0 -85
  146. torchzero/modules/experimental/modular_lbfgs.py +0 -265
  147. torchzero/modules/experimental/parabolic_search.py +0 -220
  148. torchzero/modules/experimental/subspace_preconditioners.py +0 -145
  149. torchzero/modules/experimental/tensor_adagrad.py +0 -42
  150. torchzero/modules/line_search/polynomial.py +0 -233
  151. torchzero/modules/momentum/matrix_momentum.py +0 -193
  152. torchzero/modules/optimizers/adagrad.py +0 -165
  153. torchzero/modules/quasi_newton/trust_region.py +0 -397
  154. torchzero/modules/smoothing/gaussian.py +0 -198
  155. torchzero-0.3.11.dist-info/METADATA +0 -404
  156. torchzero-0.3.11.dist-info/RECORD +0 -159
  157. torchzero-0.3.11.dist-info/licenses/LICENSE +0 -21
  158. /torchzero/modules/{optimizers → adaptive}/lion.py +0 -0
  159. /torchzero/modules/{optimizers → adaptive}/orthograd.py +0 -0
  160. /torchzero/modules/{optimizers → adaptive}/rmsprop.py +0 -0
  161. {torchzero-0.3.11.dist-info → torchzero-0.3.13.dist-info}/WHEEL +0 -0
@@ -4,7 +4,7 @@ from typing import Literal
4
4
  import torch
5
5
 
6
6
  from ...core import Module, Target, Transform
7
- from ...utils import NumberList, TensorList, as_tensorlist, unpack_dicts, unpack_states
7
+ from ...utils import NumberList, TensorList, as_tensorlist, unpack_dicts, unpack_states, Metrics
8
8
 
9
9
 
10
10
  @torch.no_grad
@@ -14,7 +14,7 @@ def weight_decay_(
14
14
  weight_decay: float | NumberList,
15
15
  ord: int = 2
16
16
  ):
17
- """returns `grad_`."""
17
+ """modifies in-place and returns ``grad_``."""
18
18
  if ord == 1: return grad_.add_(params.sign().mul_(weight_decay))
19
19
  if ord == 2: return grad_.add_(params.mul(weight_decay))
20
20
  if ord - 1 % 2 != 0: return grad_.add_(params.pow(ord-1).mul_(weight_decay))
@@ -29,39 +29,38 @@ class WeightDecay(Transform):
29
29
  ord (int, optional): order of the penalty, e.g. 1 for L1 and 2 for L2. Defaults to 2.
30
30
  target (Target, optional): what to set on var. Defaults to 'update'.
31
31
 
32
- Examples:
33
- Adam with non-decoupled weight decay
34
-
35
- .. code-block:: python
36
-
37
- opt = tz.Modular(
38
- model.parameters(),
39
- tz.m.WeightDecay(1e-3),
40
- tz.m.Adam(),
41
- tz.m.LR(1e-3)
42
- )
43
-
44
- Adam with decoupled weight decay that still scales with learning rate
45
-
46
- .. code-block:: python
47
-
48
- opt = tz.Modular(
49
- model.parameters(),
50
- tz.m.Adam(),
51
- tz.m.WeightDecay(1e-3),
52
- tz.m.LR(1e-3)
53
- )
54
-
55
- Adam with fully decoupled weight decay that doesn't scale with learning rate
56
-
57
- .. code-block:: python
58
-
59
- opt = tz.Modular(
60
- model.parameters(),
61
- tz.m.Adam(),
62
- tz.m.LR(1e-3),
63
- tz.m.WeightDecay(1e-6)
64
- )
32
+ ### Examples:
33
+
34
+ Adam with non-decoupled weight decay
35
+ ```python
36
+ opt = tz.Modular(
37
+ model.parameters(),
38
+ tz.m.WeightDecay(1e-3),
39
+ tz.m.Adam(),
40
+ tz.m.LR(1e-3)
41
+ )
42
+ ```
43
+
44
+ Adam with decoupled weight decay that still scales with learning rate
45
+ ```python
46
+
47
+ opt = tz.Modular(
48
+ model.parameters(),
49
+ tz.m.Adam(),
50
+ tz.m.WeightDecay(1e-3),
51
+ tz.m.LR(1e-3)
52
+ )
53
+ ```
54
+
55
+ Adam with fully decoupled weight decay that doesn't scale with learning rate
56
+ ```python
57
+ opt = tz.Modular(
58
+ model.parameters(),
59
+ tz.m.Adam(),
60
+ tz.m.LR(1e-3),
61
+ tz.m.WeightDecay(1e-6)
62
+ )
63
+ ```
65
64
 
66
65
  """
67
66
  def __init__(self, weight_decay: float, ord: int = 2, target: Target = 'update'):
@@ -77,7 +76,7 @@ class WeightDecay(Transform):
77
76
  return weight_decay_(as_tensorlist(tensors), as_tensorlist(params), weight_decay, ord)
78
77
 
79
78
  class RelativeWeightDecay(Transform):
80
- """Weight decay relative to the mean absolute value of update, gradient or parameters depending on value of :code:`norm_input` argument.
79
+ """Weight decay relative to the mean absolute value of update, gradient or parameters depending on value of ``norm_input`` argument.
81
80
 
82
81
  Args:
83
82
  weight_decay (float): relative weight decay scale.
@@ -85,40 +84,42 @@ class RelativeWeightDecay(Transform):
85
84
  norm_input (str, optional):
86
85
  determines what should weight decay be relative to. "update", "grad" or "params".
87
86
  Defaults to "update".
87
+ metric (Ords, optional):
88
+ metric (norm, etc) that weight decay should be relative to.
89
+ defaults to 'mad' (mean absolute deviation).
88
90
  target (Target, optional): what to set on var. Defaults to 'update'.
89
91
 
90
- Examples:
91
- Adam with non-decoupled relative weight decay
92
-
93
- .. code-block:: python
94
-
95
- opt = tz.Modular(
96
- model.parameters(),
97
- tz.m.RelativeWeightDecay(1e-3),
98
- tz.m.Adam(),
99
- tz.m.LR(1e-3)
100
- )
101
-
102
- Adam with decoupled relative weight decay
103
-
104
- .. code-block:: python
105
-
106
- opt = tz.Modular(
107
- model.parameters(),
108
- tz.m.Adam(),
109
- tz.m.RelativeWeightDecay(1e-3),
110
- tz.m.LR(1e-3)
111
- )
112
-
92
+ ### Examples:
93
+
94
+ Adam with non-decoupled relative weight decay
95
+ ```python
96
+ opt = tz.Modular(
97
+ model.parameters(),
98
+ tz.m.RelativeWeightDecay(1e-1),
99
+ tz.m.Adam(),
100
+ tz.m.LR(1e-3)
101
+ )
102
+ ```
103
+
104
+ Adam with decoupled relative weight decay
105
+ ```python
106
+ opt = tz.Modular(
107
+ model.parameters(),
108
+ tz.m.Adam(),
109
+ tz.m.RelativeWeightDecay(1e-1),
110
+ tz.m.LR(1e-3)
111
+ )
112
+ ```
113
113
  """
114
114
  def __init__(
115
115
  self,
116
116
  weight_decay: float = 0.1,
117
117
  ord: int = 2,
118
118
  norm_input: Literal["update", "grad", "params"] = "update",
119
+ metric: Metrics = 'mad',
119
120
  target: Target = "update",
120
121
  ):
121
- defaults = dict(weight_decay=weight_decay, ord=ord, norm_input=norm_input)
122
+ defaults = dict(weight_decay=weight_decay, ord=ord, norm_input=norm_input, metric=metric)
122
123
  super().__init__(defaults, uses_grad=norm_input == 'grad', target=target)
123
124
 
124
125
  @torch.no_grad
@@ -127,6 +128,7 @@ class RelativeWeightDecay(Transform):
127
128
 
128
129
  ord = settings[0]['ord']
129
130
  norm_input = settings[0]['norm_input']
131
+ metric = settings[0]['metric']
130
132
 
131
133
  if norm_input == 'update': src = TensorList(tensors)
132
134
  elif norm_input == 'grad':
@@ -137,9 +139,8 @@ class RelativeWeightDecay(Transform):
137
139
  else:
138
140
  raise ValueError(norm_input)
139
141
 
140
- mean_abs = src.abs().global_mean()
141
-
142
- return weight_decay_(as_tensorlist(tensors), as_tensorlist(params), weight_decay * mean_abs, ord)
142
+ norm = src.global_metric(metric)
143
+ return weight_decay_(as_tensorlist(tensors), as_tensorlist(params), weight_decay * norm, ord)
143
144
 
144
145
 
145
146
  @torch.no_grad
@@ -162,7 +163,7 @@ class DirectWeightDecay(Module):
162
163
  @torch.no_grad
163
164
  def step(self, var):
164
165
  weight_decay = self.get_settings(var.params, 'weight_decay', cls=NumberList)
165
- ord = self.settings[var.params[0]]['ord']
166
+ ord = self.defaults['ord']
166
167
 
167
168
  decay_weights_(var.params, weight_decay, ord)
168
169
  return var
@@ -0,0 +1 @@
1
+ from .cd import CD, CCD, CCDLS
@@ -0,0 +1,359 @@
1
+ import math
2
+ import random
3
+ import warnings
4
+ from functools import partial
5
+ from typing import Literal
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ from ...core import Module
11
+ from ...utils import NumberList, TensorList
12
+ from ..line_search.adaptive import adaptive_tracking
13
+
14
+ class CD(Module):
15
+ """Coordinate descent. Proposes a descent direction along a single coordinate.
16
+ You can then put a line search such as ``tz.m.ScipyMinimizeScalar``, or a fixed step size.
17
+
18
+ Args:
19
+ h (float, optional): finite difference step size. Defaults to 1e-3.
20
+ grad (bool, optional):
21
+ if True, scales direction by gradient estimate. If False, the scale is fixed to 1. Defaults to True.
22
+ adaptive (bool, optional):
23
+ whether to adapt finite difference step size, this requires an additional buffer. Defaults to True.
24
+ index (str, optional):
25
+ index selection strategy.
26
+ - "cyclic" - repeatedly cycles through each coordinate, e.g. ``1,2,3,1,2,3,...``.
27
+ - "cyclic2" - cycles forward and then backward, e.g ``1,2,3,3,2,1,1,2,3,...`` (default).
28
+ - "random" - picks coordinate randomly.
29
+ threepoint (bool, optional):
30
+ whether to use three points (three function evaluatins) to determine descent direction.
31
+ if False, uses two points, but then ``adaptive`` can't be used. Defaults to True.
32
+ """
33
+ def __init__(self, h:float=1e-3, grad:bool=True, adaptive:bool=True, index:Literal['cyclic', 'cyclic2', 'random']="cyclic2", threepoint:bool=True,):
34
+ defaults = dict(h=h, grad=grad, adaptive=adaptive, index=index, threepoint=threepoint)
35
+ super().__init__(defaults)
36
+
37
+ @torch.no_grad
38
+ def step(self, var):
39
+ closure = var.closure
40
+ if closure is None:
41
+ raise RuntimeError("CD requires closure")
42
+
43
+ params = TensorList(var.params)
44
+ ndim = params.global_numel()
45
+
46
+ grad_step_size = self.defaults['grad']
47
+ adaptive = self.defaults['adaptive']
48
+ index_strategy = self.defaults['index']
49
+ h = self.defaults['h']
50
+ threepoint = self.defaults['threepoint']
51
+
52
+ # ------------------------------ determine index ----------------------------- #
53
+ if index_strategy == 'cyclic':
54
+ idx = self.global_state.get('idx', 0) % ndim
55
+ self.global_state['idx'] = idx + 1
56
+
57
+ elif index_strategy == 'cyclic2':
58
+ idx = self.global_state.get('idx', 0)
59
+ self.global_state['idx'] = idx + 1
60
+ if idx >= ndim * 2:
61
+ idx = self.global_state['idx'] = 0
62
+ if idx >= ndim:
63
+ idx = (2*ndim - idx) - 1
64
+
65
+ elif index_strategy == 'random':
66
+ if 'generator' not in self.global_state:
67
+ self.global_state['generator'] = random.Random(0)
68
+ generator = self.global_state['generator']
69
+ idx = generator.randrange(0, ndim)
70
+
71
+ else:
72
+ raise ValueError(index_strategy)
73
+
74
+ # -------------------------- find descent direction -------------------------- #
75
+ h_vec = None
76
+ if adaptive:
77
+ if threepoint:
78
+ h_vec = self.get_state(params, 'h_vec', init=lambda x: torch.full_like(x, h), cls=TensorList)
79
+ h = float(h_vec.flat_get(idx))
80
+ else:
81
+ warnings.warn("CD adaptive=True only works with threepoint=True")
82
+
83
+ f_0 = var.get_loss(False)
84
+ params.flat_set_lambda_(idx, lambda x: x + h)
85
+ f_p = closure(False)
86
+
87
+ # -------------------------------- threepoint -------------------------------- #
88
+ if threepoint:
89
+ params.flat_set_lambda_(idx, lambda x: x - 2*h)
90
+ f_n = closure(False)
91
+ params.flat_set_lambda_(idx, lambda x: x + h)
92
+
93
+ if adaptive:
94
+ assert h_vec is not None
95
+ if f_0 <= f_p and f_0 <= f_n:
96
+ h_vec.flat_set_lambda_(idx, lambda x: max(x/2, 1e-10))
97
+ else:
98
+ if abs(f_0 - f_n) < 1e-12 or abs((f_p - f_0) / (f_0 - f_n) - 1) < 1e-2:
99
+ h_vec.flat_set_lambda_(idx, lambda x: min(x*2, 1e10))
100
+
101
+ if grad_step_size:
102
+ alpha = (f_p - f_n) / (2*h)
103
+
104
+ else:
105
+ if f_0 < f_p and f_0 < f_n: alpha = 0
106
+ elif f_p < f_n: alpha = -1
107
+ else: alpha = 1
108
+
109
+ # --------------------------------- twopoint --------------------------------- #
110
+ else:
111
+ params.flat_set_lambda_(idx, lambda x: x - h)
112
+ if grad_step_size:
113
+ alpha = (f_p - f_0) / h
114
+ else:
115
+ if f_p < f_0: alpha = -1
116
+ else: alpha = 1
117
+
118
+ # ----------------------------- create the update ---------------------------- #
119
+ update = params.zeros_like()
120
+ update.flat_set_(idx, alpha)
121
+ var.update = update
122
+ return var
123
+
124
+
125
+ def _icd_get_idx(self: Module, params: TensorList):
126
+ ndim = params.global_numel()
127
+ igrad = self.get_state(params, "igrad", cls=TensorList)
128
+
129
+ # -------------------------- 1st n steps fill igrad -------------------------- #
130
+ index = self.global_state.get('index', 0)
131
+ self.global_state['index'] = index + 1
132
+ if index < ndim:
133
+ return index, igrad
134
+
135
+ # ------------------ select randomly weighted by magnitudes ------------------ #
136
+ igrad_abs = igrad.abs()
137
+ gmin = igrad_abs.global_min()
138
+ gmax = igrad_abs.global_max()
139
+
140
+ pmin, pmax, pow = self.get_settings(params, "pmin", "pmax", "pow", cls=NumberList)
141
+
142
+ p: TensorList = ((igrad_abs - gmin) / (gmax - gmin)) ** pow # pyright:ignore[reportOperatorIssue]
143
+ p.mul_(pmax-pmin).add_(pmin)
144
+
145
+ if 'np_gen' not in self.global_state:
146
+ self.global_state['np_gen'] = np.random.default_rng(0)
147
+ np_gen = self.global_state['np_gen']
148
+
149
+ p_vec = p.to_vec()
150
+ p_sum = p_vec.sum()
151
+ if p_sum > 1e-12:
152
+ return np_gen.choice(ndim, p=p_vec.div_(p_sum).numpy(force=True)), igrad
153
+
154
+ # --------------------- sum is too small, do cycle again --------------------- #
155
+ self.global_state.clear()
156
+ self.clear_state_keys('h_vec', 'igrad', 'alphas')
157
+
158
+ if 'generator' not in self.global_state:
159
+ self.global_state['generator'] = random.Random(0)
160
+ generator = self.global_state['generator']
161
+ return generator.randrange(0, p_vec.numel()), igrad
162
+
163
+ class CCD(Module):
164
+ """Cumulative coordinate descent. This updates one gradient coordinate at a time and accumulates it
165
+ to the update direction. The coordinate updated is random weighted by magnitudes of current update direction.
166
+ As update direction ceases to be a descent direction due to old accumulated coordinates, it is decayed.
167
+
168
+ Args:
169
+ pmin (float, optional): multiplier to probability of picking the lowest magnitude gradient. Defaults to 0.1.
170
+ pmax (float, optional): multiplier to probability of picking the largest magnitude gradient. Defaults to 1.0.
171
+ pow (int, optional): power transform to probabilities. Defaults to 2.
172
+ decay (float, optional): accumulated gradient decay on failed step. Defaults to 0.5.
173
+ decay2 (float, optional): decay multiplier decay on failed step. Defaults to 0.25.
174
+ nplus (float, optional): step size increase on successful steps. Defaults to 1.5.
175
+ nminus (float, optional): step size increase on unsuccessful steps. Defaults to 0.75.
176
+ """
177
+ def __init__(self, pmin=0.1, pmax=1.0, pow=2, decay:float=0.8, decay2:float=0.2, nplus=1.5, nminus=0.75):
178
+
179
+ defaults = dict(pmin=pmin, pmax=pmax, pow=pow, decay=decay, decay2=decay2, nplus=nplus, nminus=nminus)
180
+ super().__init__(defaults)
181
+
182
+ @torch.no_grad
183
+ def step(self, var):
184
+ closure = var.closure
185
+ if closure is None:
186
+ raise RuntimeError("CD requires closure")
187
+
188
+ params = TensorList(var.params)
189
+ p_prev = self.get_state(params, "p_prev", init=params, cls=TensorList)
190
+
191
+ f_0 = var.get_loss(False)
192
+ step_size = self.global_state.get('step_size', 1)
193
+
194
+ # ------------------------ hard reset on infinite loss ----------------------- #
195
+ if not math.isfinite(f_0):
196
+ del self.global_state['f_prev']
197
+ var.update = params - p_prev
198
+ self.global_state.clear()
199
+ self.state.clear()
200
+ self.global_state["step_size"] = step_size / 10
201
+ return var
202
+
203
+ # ---------------------------- soft reset if stuck --------------------------- #
204
+ if "igrad" in self.state[params[0]]:
205
+ n_bad = self.global_state.get('n_bad', 0)
206
+
207
+ f_prev = self.global_state.get("f_prev", None)
208
+ if f_prev is not None:
209
+
210
+ decay2 = self.defaults["decay2"]
211
+ decay = self.global_state.get("decay", self.defaults["decay"])
212
+
213
+ if f_0 >= f_prev:
214
+
215
+ igrad = self.get_state(params, "igrad", cls=TensorList)
216
+ del self.global_state['f_prev']
217
+
218
+ # undo previous update
219
+ var.update = params - p_prev
220
+
221
+ # increment n_bad
222
+ self.global_state['n_bad'] = n_bad + 1
223
+
224
+ # decay step size
225
+ self.global_state['step_size'] = step_size * self.defaults["nminus"]
226
+
227
+ # soft reset
228
+ if n_bad > 0:
229
+ igrad *= decay
230
+ self.global_state["decay"] = decay*decay2
231
+ self.global_state['n_bad'] = 0
232
+
233
+ return var
234
+
235
+ else:
236
+ # increase step size and reset n_bad
237
+ self.global_state['step_size'] = step_size * self.defaults["nplus"]
238
+ self.global_state['n_bad'] = 0
239
+ self.global_state["decay"] = self.defaults["decay"]
240
+
241
+ self.global_state['f_prev'] = float(f_0)
242
+
243
+ # ------------------------------ determine index ----------------------------- #
244
+ idx, igrad = _icd_get_idx(self, params)
245
+
246
+ # -------------------------- find descent direction -------------------------- #
247
+ h_vec = self.get_state(params, 'h_vec', init=lambda x: torch.full_like(x, 1e-3), cls=TensorList)
248
+ h = float(h_vec.flat_get(idx))
249
+
250
+ params.flat_set_lambda_(idx, lambda x: x + h)
251
+ f_p = closure(False)
252
+
253
+ params.flat_set_lambda_(idx, lambda x: x - 2*h)
254
+ f_n = closure(False)
255
+ params.flat_set_lambda_(idx, lambda x: x + h)
256
+
257
+ # ---------------------------------- adapt h --------------------------------- #
258
+ if f_0 <= f_p and f_0 <= f_n:
259
+ h_vec.flat_set_lambda_(idx, lambda x: max(x/2, 1e-10))
260
+ else:
261
+ if abs(f_0 - f_n) < 1e-12 or abs((f_p - f_0) / (f_0 - f_n) - 1) < 1e-2:
262
+ h_vec.flat_set_lambda_(idx, lambda x: min(x*2, 1e10))
263
+
264
+ # ------------------------------- update igrad ------------------------------- #
265
+ if f_0 < f_p and f_0 < f_n: alpha = 0
266
+ else: alpha = (f_p - f_n) / (2*h)
267
+
268
+ igrad.flat_set_(idx, alpha)
269
+
270
+ # ----------------------------- create the update ---------------------------- #
271
+ var.update = igrad * step_size
272
+ p_prev.copy_(params)
273
+ return var
274
+
275
+
276
+ class CCDLS(Module):
277
+ """CCD with line search instead of adaptive step size.
278
+
279
+ Args:
280
+ pmin (float, optional): multiplier to probability of picking the lowest magnitude gradient. Defaults to 0.1.
281
+ pmax (float, optional): multiplier to probability of picking the largest magnitude gradient. Defaults to 1.0.
282
+ pow (int, optional): power transform to probabilities. Defaults to 2.
283
+ decay (float, optional): accumulated gradient decay on failed step. Defaults to 0.5.
284
+ decay2 (float, optional): decay multiplier decay on failed step. Defaults to 0.25.
285
+ maxiter (int, optional): max number of line search iterations.
286
+ """
287
+ def __init__(self, pmin=0.1, pmax=1.0, pow=2, decay=0.8, decay2=0.2, maxiter=10, ):
288
+ defaults = dict(pmin=pmin, pmax=pmax, pow=pow, maxiter=maxiter, decay=decay, decay2=decay2)
289
+ super().__init__(defaults)
290
+
291
+ @torch.no_grad
292
+ def step(self, var):
293
+ closure = var.closure
294
+ if closure is None:
295
+ raise RuntimeError("CD requires closure")
296
+
297
+ params = TensorList(var.params)
298
+ finfo = torch.finfo(params[0].dtype)
299
+ f_0 = var.get_loss(False)
300
+
301
+ # ------------------------------ determine index ----------------------------- #
302
+ idx, igrad = _icd_get_idx(self, params)
303
+
304
+ # -------------------------- find descent direction -------------------------- #
305
+ h_vec = self.get_state(params, 'h_vec', init=lambda x: torch.full_like(x, 1e-3), cls=TensorList)
306
+ h = float(h_vec.flat_get(idx))
307
+
308
+ params.flat_set_lambda_(idx, lambda x: x + h)
309
+ f_p = closure(False)
310
+
311
+ params.flat_set_lambda_(idx, lambda x: x - 2*h)
312
+ f_n = closure(False)
313
+ params.flat_set_lambda_(idx, lambda x: x + h)
314
+
315
+ # ---------------------------------- adapt h --------------------------------- #
316
+ if f_0 <= f_p and f_0 <= f_n:
317
+ h_vec.flat_set_lambda_(idx, lambda x: max(x/2, finfo.tiny * 2))
318
+ else:
319
+ # here eps, not tiny
320
+ if abs(f_0 - f_n) < finfo.eps or abs((f_p - f_0) / (f_0 - f_n) - 1) < 1e-2:
321
+ h_vec.flat_set_lambda_(idx, lambda x: min(x*2, finfo.max / 2))
322
+
323
+ # ------------------------------- update igrad ------------------------------- #
324
+ if f_0 < f_p and f_0 < f_n: alpha = 0
325
+ else: alpha = (f_p - f_n) / (2*h)
326
+
327
+ igrad.flat_set_(idx, alpha)
328
+
329
+ # -------------------------------- line search ------------------------------- #
330
+ x0 = params.clone()
331
+ def f(a):
332
+ params.sub_(igrad, alpha=a)
333
+ loss = closure(False)
334
+ params.copy_(x0)
335
+ return loss
336
+
337
+ a_prev = self.global_state.get('a_prev', 1)
338
+ a, f_a, niter = adaptive_tracking(f, a_prev, maxiter=self.defaults['maxiter'], f_0=f_0)
339
+ if (a is None) or (not math.isfinite(a)) or (not math.isfinite(f_a)):
340
+ a = 0
341
+
342
+ # -------------------------------- set a_prev -------------------------------- #
343
+ decay2 = self.defaults["decay2"]
344
+ decay = self.global_state.get("decay", self.defaults["decay"])
345
+
346
+ if abs(a) > finfo.tiny * 2:
347
+ assert f_a < f_0
348
+ self.global_state['a_prev'] = max(min(a, finfo.max / 2), finfo.tiny * 2)
349
+ self.global_state["decay"] = self.defaults["decay"]
350
+
351
+ # ---------------------------- soft reset on fail ---------------------------- #
352
+ else:
353
+ igrad *= decay
354
+ self.global_state["decay"] = decay*decay2
355
+ self.global_state['a_prev'] = a_prev / 2
356
+
357
+ # -------------------------------- set update -------------------------------- #
358
+ var.update = igrad * a
359
+ return var
@@ -0,0 +1,65 @@
1
+ """WIP, untested"""
2
+ from collections.abc import Callable
3
+
4
+ from abc import abstractmethod
5
+ import torch
6
+ from ..modules.higher_order.multipoint import sixth_order_im1, sixth_order_p6, _solve
7
+
8
+ def make_evaluate(f: Callable[[torch.Tensor], torch.Tensor]):
9
+ def evaluate(x, order) -> tuple[torch.Tensor, ...]:
10
+ """order=0 - returns (f,), order=1 - returns (f, J), order=2 - returns (f, J, H), etc."""
11
+ n = x.numel()
12
+
13
+ if order == 0:
14
+ f_x = f(x)
15
+ return (f_x, )
16
+
17
+ x.requires_grad_()
18
+ with torch.enable_grad():
19
+ f_x = f(x)
20
+ I = torch.eye(n, device=x.device, dtype=x.dtype),
21
+ g_x = torch.autograd.grad(f_x, x, I, create_graph=order!=1, is_grads_batched=True)[0]
22
+ ret = [f_x, g_x]
23
+ T = g_x
24
+
25
+ # get all derivative up to order
26
+ for o in range(2, order + 1):
27
+ is_last = o == order
28
+ I = torch.eye(T.numel(), device=x.device, dtype=x.dtype),
29
+ T = torch.autograd.grad(T.ravel(), x, I, create_graph=not is_last, is_grads_batched=True)[0]
30
+ ret.append(T.view(n, n, *T.shape[1:]))
31
+
32
+ return tuple(ret)
33
+
34
+ return evaluate
35
+
36
+ class RootBase:
37
+ @abstractmethod
38
+ def one_iteration(
39
+ self,
40
+ x: torch.Tensor,
41
+ evaluate: Callable[[torch.Tensor, int], tuple[torch.Tensor, ...]],
42
+ ) -> torch.Tensor:
43
+ """"""
44
+
45
+
46
+ # ---------------------------------- methods --------------------------------- #
47
+ def newton(x:torch.Tensor, f_j, lstsq:bool=False):
48
+ f_x, G_x = f_j(x)
49
+ return x - _solve(G_x, f_x, lstsq=lstsq)
50
+
51
+ class Newton(RootBase):
52
+ def __init__(self, lstsq: bool=False): self.lstsq = lstsq
53
+ def one_iteration(self, x, evaluate): return newton(x, evaluate, self.lstsq)
54
+
55
+
56
+ class SixthOrderP6(RootBase):
57
+ """sixth-order iterative method
58
+
59
+ Abro, Hameer Akhtar, and Muhammad Mujtaba Shaikh. "A new time-efficient and convergent nonlinear solver." Applied Mathematics and Computation 355 (2019): 516-536.
60
+ """
61
+ def __init__(self, lstsq: bool=False): self.lstsq = lstsq
62
+ def one_iteration(self, x, evaluate):
63
+ def f(x): return evaluate(x, 0)[0]
64
+ def f_j(x): return evaluate(x, 1)
65
+ return sixth_order_p6(x, f, f_j, self.lstsq)
@@ -11,12 +11,12 @@ class Split(torch.optim.Optimizer):
11
11
 
12
12
  Example:
13
13
 
14
- .. code:: py
15
-
16
- opt = Split(
17
- torch.optim.Adam(model.encoder.parameters(), lr=0.001),
18
- torch.optim.SGD(model.decoder.parameters(), lr=0.1)
19
- )
14
+ ```python
15
+ opt = Split(
16
+ torch.optim.Adam(model.encoder.parameters(), lr=0.001),
17
+ torch.optim.SGD(model.decoder.parameters(), lr=0.1)
18
+ )
19
+ ```
20
20
  """
21
21
  def __init__(self, *optimizers: torch.optim.Optimizer | Iterable[torch.optim.Optimizer]):
22
22
  all_params = []
@@ -25,14 +25,14 @@ class Split(torch.optim.Optimizer):
25
25
  # gather all params in case user tries to access them from this object
26
26
  for i,opt in enumerate(self.optimizers):
27
27
  for p in get_params(opt.param_groups, 'all', list):
28
- if p not in all_params: all_params.append(p)
28
+ if id(p) not in [id(pr) for pr in all_params]: all_params.append(p)
29
29
  else: warnings.warn(
30
30
  f'optimizers[{i}] {opt.__class__.__name__} has some duplicate parameters '
31
31
  'that are also in previous optimizers. They will be updated multiple times.')
32
32
 
33
33
  super().__init__(all_params, {})
34
34
 
35
- def step(self, closure: Callable | None = None):
35
+ def step(self, closure: Callable | None = None): # pyright:ignore[reportIncompatibleMethodOverride]
36
36
  loss = None
37
37
 
38
38
  # if closure provided, populate grad, otherwise each optimizer will call closure separately
@@ -7,7 +7,6 @@ import numpy as np
7
7
  import torch
8
8
  from directsearch.ds import DEFAULT_PARAMS
9
9
 
10
- from ...modules.second_order.newton import tikhonov_
11
10
  from ...utils import Optimizer, TensorList
12
11
 
13
12
 
@@ -2,11 +2,12 @@ from collections.abc import Callable
2
2
  from functools import partial
3
3
  from typing import Any, Literal
4
4
 
5
+ import numpy as np
6
+ import torch
7
+
5
8
  import fcmaes
6
9
  import fcmaes.optimizer
7
10
  import fcmaes.retry
8
- import numpy as np
9
- import torch
10
11
 
11
12
  from ...utils import Optimizer, TensorList
12
13