python-somax 0.0.1__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.1
2
+ Name: python-somax
3
+ Version: 0.0.1
4
+ Summary: SOMAX: Second-Order Methods for Machine Learning in JAX
5
+ Author: Nick Korbit
6
+ Platform: any
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Programming Language :: Python :: 3.8
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: jaxopt >=0.8.2
19
+
20
+ <h1 align='center'>Somax</h1>
21
+
22
+ <p align='center'>
23
+ <img src="assets/somax_logo_mini.png" alt="logo" width="250px"/>
24
+ </p>
25
+
26
+ Somax is a library of Second-Order Methods for stochastic optimization
27
+ written in [JAX](https://github.com/google/jax).
28
+ Somax is based on the [JAXopt](https://github.com/google/jaxopt) StochasticSolver API,
29
+ and can be used as a drop-in
30
+ replacement for JAXopt as well as
31
+ [Optax](https://github.com/google-deepmind/optax) solvers.
32
+
33
+ Currently supported methods:
34
+
35
+ - Diagonal Scaling:
36
+ - [AdaHessian](https://ojs.aaai.org/index.php/AAAI/article/view/17275);
37
+ - [Sophia](https://arxiv.org/abs/2305.14342);
38
+ - Hessian-free Optimization:
39
+ - [Newton-CG](https://epubs.siam.org/doi/10.1137/10079923X);
40
+ - Quasi-Newton:
41
+ - [Stochastic Quasi-Newton Framework (SQN)](https://arxiv.org/abs/1606.04838);
42
+ - Gauss-Newton:
43
+ - [Exact Gauss-Newton (EGN)](https://arxiv.org/abs/2405.14402);
44
+ - [Stochastic Gauss-Newton (SGN)](https://arxiv.org/abs/2006.02409);
45
+ - Natural Gradient:
46
+ - [Natural Gradient with Sherman-Morrison-Woodbury formula (SWM-NG)](https://arxiv.org/abs/1906.02353).
47
+
48
+ Future releases:
49
+
50
+ - Add support for separate "gradient batches"
51
+ and "curvature batches" for all solvers;
52
+ - Add support for Optax rate schedules.
53
+
54
+ ⚠️ Since JAXopt is currently being merged into Optax,
55
+ Somax at some point will switch to the Optax API as well.
56
+
57
+
58
+ *The catfish in the logo is a nod to "сом",
59
+ the Belarusian word for "catfish", also pronounced as "som".
60
+
61
+
62
+ ## Installation
63
+
64
+ ```bash
65
+ pip install python-somax
66
+ ```
67
+
68
+ Requires [JAXopt](https://github.com/google/jaxopt) 0.8.2+.
69
+
70
+ ## Quick example
71
+
72
+ ```py
73
+ from somax import EGN
74
+
75
+ # initialize the solver
76
+ solver = EGN(
77
+ predict_fun=model.apply,
78
+ loss_type='mse',
79
+ learning_rate=0.1,
80
+ regularizer=1.0,
81
+ )
82
+
83
+ # initialize the solver state
84
+ opt_state = solver.init_state(params)
85
+
86
+ # run the optimization loop
87
+ for i in range(10):
88
+ params, opt_state = solver.update(params, opt_state, batch_x, batch_y)
89
+ ```
90
+
91
+ See more in the [examples](examples) folder.
92
+
93
+ ## Citation
94
+
95
+ ```bibtex
96
+ @misc{korbit2024somax,
97
+ author = {Nick Korbit},
98
+ title = {{SOMAX}: a library of second-order methods for stochastic optimization written in {JAX}},
99
+ year = {2024},
100
+ url = {https://github.com/cor3bit/somax},
101
+ }
102
+ ```
103
+
104
+ ## See also
105
+
106
+ **Optimization with JAX**
107
+ [Optax](https://github.com/google-deepmind/optax): first-order gradient (SGD, Adam, ...) optimisers.
108
+ [JAXopt](https://github.com/google/jaxopt): deterministic second-order methods (e.g., Gauss-Newton, Levenberg
109
+ Marquardt), stochastic first-order methods PolyakSGD, ArmijoSGD.
110
+
111
+ **Awesome Projects**
112
+ [Awesome JAX](https://github.com/n2cholas/awesome-jax): a longer list of various JAX projects.
113
+ [Awesome SOMs](https://github.com/cor3bit/awesome-soms): a list
114
+ of resources for second-order optimization methods in machine learning.
115
+
116
+ ## Acknowledgements
117
+
118
+ Some of the implementation ideas are based on the following repositories:
119
+
120
+ - Line Search in JAXopt: https://github.com/google/jaxopt/blob/main/jaxopt/_src/armijo_sgd.py#L48
121
+
122
+ - L-BFGS Inverse Hessian-Gradient product in JAXopt: https://github.com/google/jaxopt/blob/main/jaxopt/_src/lbfgs.py#L44
123
+
124
+ - AdaHessian (official implementation): https://github.com/amirgholami/adahessian
125
+
126
+ - AdaHessian (Nestor Demeure's implementation): https://github.com/nestordemeure/AdaHessianJax
127
+
128
+ - Sophia (official implementation): https://github.com/Liuhong99/Sophia
129
+
130
+ - Sophia (levanter implementation): https://github.com/stanford-crfm/levanter/blob/main/src/levanter/optim/sophia.py
131
+
@@ -0,0 +1,19 @@
1
+ somax/__init__.py,sha256=aAvLcWAeV1eUf5eQEhQkOd7VtQ7mQ1zIGnnzz4hffE8,445
2
+ somax/diagonal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ somax/diagonal/adahessian.py,sha256=iYqRiayhu3x_cSiJ_zaWaVTT6Avi2cFQD9qC-LWbp2U,6530
4
+ somax/diagonal/sophia_g.py,sha256=c0kMYU8mHU8IXUKkLp3-PeP71J-P0XQJ7zzH0RuzGkw,6670
5
+ somax/diagonal/sophia_h.py,sha256=eLsyDc9pCySyEZxugu0R4hFTraH_nZmyrnJJsdtxSO4,6096
6
+ somax/gn/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ somax/gn/egn.py,sha256=qykmnvopfQdp-neOuyTU1DuAEKVqcno-MpaQPRUetlA,20880
8
+ somax/gn/sgn.py,sha256=EzoJgn0nEuo6wNbnA_uacKHlzvbc3dYLe7vUtccOb7Y,7693
9
+ somax/hf/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ somax/hf/newton_cg.py,sha256=lcvgJ9s6bHJwggKPBsRYvOYlyWxoShjV5IhdTYdYjlM,11735
11
+ somax/ng/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ somax/ng/swm_ng.py,sha256=UFagbtVU16otMgw-_8_G238omSV7zQao2Ygg9OALgnk,14287
13
+ somax/qn/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ somax/qn/sqn.py,sha256=6oKsIcZEpXtLQt1Wy2AquyIc_iy1SrBarivawO6PWVo,10261
15
+ python_somax-0.0.1.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
16
+ python_somax-0.0.1.dist-info/METADATA,sha256=SL3R5GJsrQ1GxMb1DFqUEk4MSYEkLVr7QJ7oJ-BVtS8,4237
17
+ python_somax-0.0.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
18
+ python_somax-0.0.1.dist-info/top_level.txt,sha256=MtQ05b9WUJTb2l52XYjcvmLKK3LwGORMIW5Bl1mVUq0,6
19
+ python_somax-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.43.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ somax
somax/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ # Diagonal Scaling
2
+ from somax.diagonal.adahessian import AdaHessian
3
+ from somax.diagonal.sophia_g import SophiaG
4
+ from somax.diagonal.sophia_h import SophiaH
5
+
6
+ # Hessian Free Optimization
7
+ from somax.hf.newton_cg import NewtonCG
8
+
9
+ # Quasi-Newton Methods
10
+ from somax.qn.sqn import SQN
11
+
12
+ # Gauss-Newton Methods
13
+ from somax.gn.egn import EGN
14
+ from somax.gn.sgn import SGN
15
+
16
+ # Natural Gradient Methods
17
+ from somax.ng.swm_ng import SWMNG
18
+
19
+ __version__ = '0.0.1'
File without changes
@@ -0,0 +1,192 @@
1
+ """
2
+ AdaHessian Optimizer
3
+ Paper: https://arxiv.org/abs/2006.00719
4
+ """
5
+
6
+ from typing import Any
7
+ from typing import Callable
8
+ from typing import NamedTuple, Tuple
9
+ from typing import Optional
10
+ import dataclasses
11
+ from functools import partial
12
+
13
+ import jax
14
+ import jax.numpy as jnp
15
+ from jax.flatten_util import ravel_pytree
16
+ from jaxopt._src import base
17
+
18
+
19
+ class AdaHessianState(NamedTuple):
20
+ """Named tuple containing state information."""
21
+ iter_num: int
22
+ stepsize: float
23
+ velocity_m: Any
24
+ velocity_v_tree: Any
25
+ hess_approx_rng: Any
26
+
27
+
28
+ @dataclasses.dataclass(eq=False)
29
+ class AdaHessian(base.StochasticSolver):
30
+ loss_fun: Callable
31
+
32
+ learning_rate: float = 1e-3
33
+
34
+ spatial_averaging: bool = True
35
+
36
+ # Momentum parameters
37
+ beta1: float = 0.9 # the exponential decay rate for the first moment estimates
38
+ beta2: float = 0.999 # the exponential decay rate for the squared hessian estimates
39
+
40
+ # Regularization parameters
41
+ weight_decay: float = 0.0 # L2 regularization coefficient
42
+
43
+ # Hessian parameters
44
+ hessian_power: float = 1.0 # the power of the hessian approximation, i.e. H^{-hessian_power}
45
+ eps: float = 1e-8 # term added to the denominator to improve numerical stability
46
+
47
+ hess_approx_seed: int = 1337
48
+
49
+ pre_update: Optional[Callable] = None
50
+
51
+ verbose: int = 0
52
+
53
+ jit: bool = True
54
+ unroll: base.AutoOrBoolean = "auto"
55
+
56
+ def __post_init__(self):
57
+ super().__post_init__()
58
+
59
+ self.reference_signature = self.loss_fun
60
+
61
+ self.grad_fun = jax.grad(self.loss_fun)
62
+
63
+ assert 0 <= self.hessian_power <= 1, "Hessian power must be in [0, 1]"
64
+ assert 0 <= self.weight_decay < 1, "Weight decay must be in [0, 1)"
65
+
66
+ def update(
67
+ self,
68
+ params: Any,
69
+ state: AdaHessianState,
70
+ *args,
71
+ **kwargs,
72
+ ) -> base.OptStep:
73
+ """Performs one iteration of the solver.
74
+
75
+ Args:
76
+ params: pytree containing the parameters.
77
+ state: named tuple containing the solver state.
78
+ *args: additional positional arguments to be passed to ``fun``.
79
+ **kwargs: additional keyword arguments to be passed to ``fun``.
80
+ Returns:
81
+ (params, state)
82
+ """
83
+ # ------- Step 1 -------
84
+ # compute the gradient and the Diagonal Hessian using Hutchinson's method
85
+ next_rng_key, rng_key = jax.random.split(state.hess_approx_rng)
86
+ params_flat, pack_fn = ravel_pytree(params)
87
+ p_shape = params_flat.shape
88
+ grads_tree, diag_hess_tree = self.grad_and_hess(params, rng_key, p_shape, pack_fn, *args, **kwargs)
89
+
90
+ # ------- Step 2 -------
91
+ if self.spatial_averaging:
92
+ diag_hess_tree = self.average_layers(diag_hess_tree)
93
+
94
+ # ------- Step 3 -------
95
+ # apply temporal averaging (momentum) to the first and second moments
96
+ i = state.iter_num + 1
97
+
98
+ # m_t
99
+ grads = ravel_pytree(grads_tree)[0]
100
+ velocity_m = self.beta1 * state.velocity_m + (1 - self.beta1) * grads
101
+ bias_corr_m = velocity_m / (1 - self.beta1 ** i)
102
+
103
+ # v_t
104
+ velocity_v_tree = jax.tree_map(lambda v, h: self.beta2 * v + (1 - self.beta2) * h,
105
+ state.velocity_v_tree, diag_hess_tree)
106
+
107
+ velocity_v = ravel_pytree(velocity_v_tree)[0]
108
+
109
+ bias_corr_v = jnp.pow(jnp.sqrt(velocity_v / (1 - self.beta2 ** i)), self.hessian_power)
110
+
111
+ # m_t / (v_t + eps)
112
+ direction = -bias_corr_m / (bias_corr_v + self.eps)
113
+
114
+ # update parameters
115
+ next_params_flat = params_flat + self.learning_rate * direction
116
+
117
+ # ------- Step 4 -------
118
+ # AdamW-style weight decay
119
+ if self.weight_decay > 0:
120
+ next_params_flat -= self.learning_rate * self.weight_decay * params_flat
121
+
122
+ # bookkeeping
123
+ next_params = pack_fn(next_params_flat)
124
+
125
+ next_state = AdaHessianState(
126
+ iter_num=state.iter_num + 1,
127
+ stepsize=state.stepsize,
128
+ velocity_m=velocity_m,
129
+ velocity_v_tree=velocity_v_tree,
130
+ hess_approx_rng=next_rng_key,
131
+ )
132
+
133
+ return base.OptStep(params=next_params, state=next_state)
134
+
135
+ def init_state(self,
136
+ init_params: Any,
137
+ *args,
138
+ **kwargs) -> AdaHessianState:
139
+ params_flat, pack_fn = ravel_pytree(init_params)
140
+ velocity_m = jnp.zeros_like(params_flat)
141
+ velocity_v_tree = pack_fn(jnp.zeros_like(params_flat))
142
+
143
+ return AdaHessianState(
144
+ iter_num=0,
145
+ stepsize=self.learning_rate,
146
+ velocity_m=velocity_m,
147
+ velocity_v_tree=velocity_v_tree,
148
+ hess_approx_rng=jax.random.PRNGKey(self.hess_approx_seed),
149
+ )
150
+
151
+ def optimality_fun(self, params, *args, **kwargs):
152
+ """Optimality function mapping compatible with ``@custom_root``."""
153
+ # return self._grad_fun(params, *args, **kwargs)[0]
154
+ raise NotImplementedError
155
+
156
+ def __hash__(self):
157
+ # We assume that the attribute values completely determine the solver.
158
+ return hash(self.attribute_values())
159
+
160
+ def grad_and_hess(self, params, rng_key, p_shape, pack_fn, *args, **kwargs):
161
+ # prep grad function to accept only "params"
162
+ def inner_grad_fun(params):
163
+ return self.grad_fun(params, *args, **kwargs)
164
+
165
+ # draw from Radamacher distribution
166
+ z = jax.random.rademacher(rng_key, shape=p_shape, dtype=jnp.float32)
167
+ z_tree = pack_fn(z)
168
+
169
+ grads_tree, hz_tree = jax.jvp(inner_grad_fun, (params,), (z_tree,))
170
+
171
+ diag_hess_tree = jax.tree_map(lambda x, y: x * y, grads_tree, hz_tree)
172
+
173
+ return grads_tree, diag_hess_tree
174
+
175
+ @staticmethod
176
+ def _average_layer(leaf_node):
177
+ # !! no abs() in the original implementation
178
+ # see also https://github.com/nestordemeure/AdaHessianJax/blob/main/adahessianJax/hessian_computation.py
179
+ abs_leaf_node = jnp.abs(leaf_node)
180
+
181
+ # !! no block size, just average over the layer
182
+ if leaf_node.ndim == 1:
183
+ return abs_leaf_node
184
+ elif leaf_node.ndim in [2, 3]: # Convolution layers
185
+ return jnp.mean(abs_leaf_node, axis=-1, keepdims=True)
186
+ elif leaf_node.ndim == 4: # Attention layers
187
+ return jnp.mean(abs_leaf_node, axis=[-2, -1], keepdims=True)
188
+ else:
189
+ raise ValueError("Invalid leaf node dimension")
190
+
191
+ def average_layers(self, diag_hess_tree):
192
+ return jax.tree_map(self._average_layer, diag_hess_tree)