heavyball 1.7.2__py3-none-any.whl → 2.0.0__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.
- heavyball/__init__.py +276 -37
- heavyball/chainable.py +419 -206
- heavyball/helpers.py +808 -0
- heavyball/utils.py +1062 -315
- heavyball-2.0.0.dist-info/METADATA +122 -0
- heavyball-2.0.0.dist-info/RECORD +9 -0
- {heavyball-1.7.2.dist-info → heavyball-2.0.0.dist-info}/WHEEL +1 -1
- heavyball-1.7.2.dist-info/METADATA +0 -939
- heavyball-1.7.2.dist-info/RECORD +0 -8
- {heavyball-1.7.2.dist-info → heavyball-2.0.0.dist-info}/licenses/LICENSE +0 -0
- {heavyball-1.7.2.dist-info → heavyball-2.0.0.dist-info}/top_level.txt +0 -0
@@ -1,939 +0,0 @@
|
|
1
|
-
Metadata-Version: 2.4
|
2
|
-
Name: heavyball
|
3
|
-
Version: 1.7.2
|
4
|
-
Summary: Efficient Optimizers
|
5
|
-
Author-email: HeavyBall Authors <github.heavyball@nestler.sh>
|
6
|
-
Project-URL: source, https://github.com/HomebrewML/HeavyBall
|
7
|
-
Project-URL: tracker, https://github.com/HomebrewML/HeavyBall/issues
|
8
|
-
Keywords: torch,optimizer,muon,soap,psgd
|
9
|
-
Classifier: Intended Audience :: Developers
|
10
|
-
Classifier: Intended Audience :: Science/Research
|
11
|
-
Classifier: License :: OSI Approved :: BSD License
|
12
|
-
Classifier: Natural Language :: English
|
13
|
-
Classifier: Operating System :: OS Independent
|
14
|
-
Classifier: Programming Language :: Python :: 3
|
15
|
-
Requires-Python: >=3.9
|
16
|
-
Description-Content-Type: text/markdown
|
17
|
-
License-File: LICENSE
|
18
|
-
Requires-Dist: opt-einsum>=3.4.0
|
19
|
-
Requires-Dist: torch>=2.1.0
|
20
|
-
Requires-Dist: numpy
|
21
|
-
Provides-Extra: dev
|
22
|
-
Requires-Dist: pre-commit; extra == "dev"
|
23
|
-
Requires-Dist: pytest; extra == "dev"
|
24
|
-
Requires-Dist: ruff; extra == "dev"
|
25
|
-
Requires-Dist: matplotlib; extra == "dev"
|
26
|
-
Requires-Dist: seaborn; extra == "dev"
|
27
|
-
Requires-Dist: hyperopt; extra == "dev"
|
28
|
-
Requires-Dist: pandas; extra == "dev"
|
29
|
-
Requires-Dist: typer; extra == "dev"
|
30
|
-
Dynamic: license-file
|
31
|
-
|
32
|
-
# `heavyball`: Efficient Optimizers
|
33
|
-
|
34
|
-
* [Public API](#Public-API)
|
35
|
-
- [Foreach Optimizers](#Foreach-Optimizers)
|
36
|
-
- [`heavyball.utils`](#heavyball.utils)
|
37
|
-
- [Example Usage](#Example-Usage)
|
38
|
-
|
39
|
-
* [`heavyball.chainable`](##heavyball.chainable)
|
40
|
-
- [Core Concept](#Core-Concept)
|
41
|
-
- [`FunctionTransform` and Guards](#FunctionTransform-and-Guards)
|
42
|
-
- [Chaining Transformations](#Chaining-Transformations)
|
43
|
-
- [Building Optimizers](#Building-Optimizers)
|
44
|
-
- [Creating New Transformations](#Creating-New-Transformations)
|
45
|
-
|
46
|
-
* [Optimizer Recommendations](#Optimizer-Recommendations)
|
47
|
-
- [Choosing the Right Optimizer](#Choosing-the-Right-Optimizer)
|
48
|
-
|
49
|
-
---
|
50
|
-
|
51
|
-
The `heavyball` library provides a collection of efficient optimizers designed for deep learning. It leverages
|
52
|
-
techniques like preconditioning, momentum, and adaptive learning rates to accelerate training and improve convergence.
|
53
|
-
The library's core strength lies in its `chainable` API, which allows for flexible composition of optimizers, enabling
|
54
|
-
users to build custom optimization strategies.
|
55
|
-
|
56
|
-
## Public API
|
57
|
-
|
58
|
-
The `heavyball` library exposes the following optimizers through its main namespace:
|
59
|
-
|
60
|
-
### Foreach Optimizers
|
61
|
-
|
62
|
-
These optimizers are designed to be efficient by operating on batches of parameters simultaneously using `foreach`
|
63
|
-
operations whenever possible.
|
64
|
-
|
65
|
-
#### `ForeachAdamW`
|
66
|
-
|
67
|
-
```python
|
68
|
-
class ForeachAdamW(C.BaseOpt):
|
69
|
-
def __init__(self, params, lr=0.0025, betas=(0.9, 0.99), eps=1e-8, weight_decay=0, warmup_steps=0,
|
70
|
-
foreach: bool = True, storage_dtype: str = 'float32', mars: bool = False, caution: bool = False,
|
71
|
-
mars_gamma: float = 0.0025, gradient_clipping: C.str_or_fn = C.use_default,
|
72
|
-
update_clipping: C.str_or_fn = C.use_default, palm: bool = C.use_default, beta2_scale: float = 0.8):
|
73
|
-
# ...
|
74
|
-
```
|
75
|
-
|
76
|
-
A foreach implementation of the AdamW optimizer. It incorporates weight decay into the update rule and uses adaptive
|
77
|
-
learning rates based on the first and second moments of the gradients.
|
78
|
-
|
79
|
-
**Key Parameters:**
|
80
|
-
|
81
|
-
* **`lr`**: Learning rate.
|
82
|
-
* **`betas`**: Coefficients used for computing running averages of the gradient and its square.
|
83
|
-
* **`eps`**: A small constant for numerical stability.
|
84
|
-
* **`weight_decay`**: Weight decay coefficient.
|
85
|
-
* **`warmup_steps`**: Number of steps for linear learning rate warmup.
|
86
|
-
* **`foreach`**: Enables/disables the use of `foreach` operations.
|
87
|
-
* **`storage_dtype`**: The floating-point type to be used for internal state. `"float32"` or `"bfloat16"`.
|
88
|
-
* **`mars`**: Enables/disables Mars correction.
|
89
|
-
* **`caution`**: Enables/disables the use of a cautious update rule, avoiding updates that point in the opposite
|
90
|
-
direction to the gradients.
|
91
|
-
* **`mars_gamma`**: Mars correction coefficient.
|
92
|
-
* **`gradient_clipping`**: Gradient clipping function or method. See `heavyball.utils` for available options.
|
93
|
-
* **`update_clipping`**: Update clipping function or method. See `heavyball.utils` for available options.
|
94
|
-
* **`palm`**: Enables/disables PaLM's beta2 schedule.
|
95
|
-
* **`beta2_scale`**: if we're using the PaLM schedule, `beta2 = step ** -beta2_scale`
|
96
|
-
|
97
|
-
#### `ForeachRMSprop`
|
98
|
-
|
99
|
-
```python
|
100
|
-
class ForeachRMSprop(C.BaseOpt):
|
101
|
-
def __init__(self, params, lr=0.0025, betas=(0.9, 0.99), eps=1e-6, weight_decay=0, warmup_steps=0, r=0.0,
|
102
|
-
weight_lr_power=2.0, foreach: bool = True, storage_dtype: str = 'float32', mars: bool = False,
|
103
|
-
caution: bool = False, mars_gamma: float = 0.0025, gradient_clipping: C.str_or_fn = C.use_default,
|
104
|
-
update_clipping: C.str_or_fn = C.use_default, palm: bool = C.use_default, beta2_scale: float = 0.8):
|
105
|
-
# ...
|
106
|
-
```
|
107
|
-
|
108
|
-
A foreach implementation of a debiased RMSprop optimizer (Note: this is different from `torch.optim.RMSprop`). It uses
|
109
|
-
adaptive learning rates based on the second moment of the gradients.
|
110
|
-
|
111
|
-
**Key Parameters:**
|
112
|
-
|
113
|
-
* **`lr`**: Learning rate.
|
114
|
-
* **`betas`**: Coefficients used for computing running averages of the squared gradient.
|
115
|
-
* **`eps`**: A small constant for numerical stability.
|
116
|
-
* **`weight_decay`**: Weight decay coefficient.
|
117
|
-
* **`warmup_steps`**: Number of steps for linear learning rate warmup.
|
118
|
-
* **`r`**: Schedule-Free coefficient that controls dependence of the learning rate on step count.
|
119
|
-
* **`weight_lr_power`**: Schedule-Free coefficient that controls the sensitivity of `r` to the learning rate.
|
120
|
-
* **`foreach`**: Enables/disables the use of `foreach` operations.
|
121
|
-
* **`storage_dtype`**: The floating-point type to be used for internal state. `"float32"` or `"bfloat16"`.
|
122
|
-
* **`mars`**: Enables/disables Mars correction.
|
123
|
-
* **`caution`**: Enables/disables the use of a cautious update rule, avoiding updates that point in the opposite
|
124
|
-
direction to the gradients.
|
125
|
-
* **`mars_gamma`**: Mars correction coefficient.
|
126
|
-
* **`gradient_clipping`**: Gradient clipping function or method. See `heavyball.utils` for available options.
|
127
|
-
* **`update_clipping`**: Update clipping function or method. See `heavyball.utils` for available options.
|
128
|
-
* **`palm`**: Enables/disables PaLM's beta2 schedule.
|
129
|
-
* **`beta2_scale`**: if we're using the PaLM schedule, `beta2 = step ** -beta2_scale`
|
130
|
-
|
131
|
-
#### `ForeachSFAdamW`
|
132
|
-
|
133
|
-
```python
|
134
|
-
class ForeachSFAdamW(C.ScheduleFree):
|
135
|
-
def __init__(self, params, lr=0.0025, betas=(0.9, 0.99), eps=1e-6, weight_decay=0, warmup_steps=0, r=0.0,
|
136
|
-
weight_lr_power=2.0, foreach: bool = True, storage_dtype: str = 'float32', mars: bool = False,
|
137
|
-
caution: bool = False, mars_gamma: float = 0.0025, gradient_clipping: C.str_or_fn = C.use_default,
|
138
|
-
update_clipping: C.str_or_fn = C.use_default, palm: bool = C.use_default, beta2_scale: float = 0.8):
|
139
|
-
# ...
|
140
|
-
```
|
141
|
-
|
142
|
-
A foreach implementation of the Schedule-Free AdamW optimizer. It combines the benefits of AdamW with the Schedule-Free
|
143
|
-
approach, which dynamically adjusts the learning rate based on the current state of optimization.
|
144
|
-
|
145
|
-
**Key Parameters:**
|
146
|
-
|
147
|
-
* **`lr`**: Base learning rate. The effective learning rate at each step depends on `lr`, `r`, and `weight_lr_power`.
|
148
|
-
* **`betas`**: Coefficients used for computing running averages of the gradient and its square.
|
149
|
-
* **`eps`**: A small constant for numerical stability.
|
150
|
-
* **`weight_decay`**: Weight decay coefficient.
|
151
|
-
* **`warmup_steps`**: Number of steps for linear learning rate warmup.
|
152
|
-
* **`r`**: Schedule-Free coefficient that controls dependence of the learning rate on step count.
|
153
|
-
* **`weight_lr_power`**: Schedule-Free coefficient that controls the sensitivity of `r` to the learning rate.
|
154
|
-
* **`foreach`**: Enables/disables the use of `foreach` operations.
|
155
|
-
* **`storage_dtype`**: The floating-point type to be used for internal state. `"float32"` or `"bfloat16"`.
|
156
|
-
* **`mars`**: Enables/disables Mars correction.
|
157
|
-
* **`caution`**: Enables/disables the use of a cautious update rule, avoiding updates that point in the opposite
|
158
|
-
direction to the gradients.
|
159
|
-
* **`mars_gamma`**: Mars correction coefficient.
|
160
|
-
* **`gradient_clipping`**: Gradient clipping function or method. See `heavyball.utils` for available options.
|
161
|
-
* **`update_clipping`**: Update clipping function or method. See `heavyball.utils` for available options.
|
162
|
-
* **`palm`**: Enables/disables PaLM's beta2 schedule.
|
163
|
-
* **`beta2_scale`**: if we're using the PaLM schedule, `beta2 = step ** -beta2_scale`
|
164
|
-
|
165
|
-
#### `PaLMForeachSFAdamW`
|
166
|
-
|
167
|
-
```python
|
168
|
-
class PaLMForeachSFAdamW(ForeachSFAdamW):
|
169
|
-
palm: bool = True
|
170
|
-
```
|
171
|
-
|
172
|
-
A specialized version of `ForeachSFAdamW` with PaLM's beta2 schedule enabled by default.
|
173
|
-
|
174
|
-
#### `ForeachADOPT`
|
175
|
-
|
176
|
-
```python
|
177
|
-
class ForeachADOPT(C.BaseOpt):
|
178
|
-
def __init__(self, params, lr=0.0025, betas=(0.9, 0.99), eps=1e-8, weight_decay=0, warmup_steps=0,
|
179
|
-
foreach: bool = True, storage_dtype: str = 'float32', mars: bool = False, caution: bool = False,
|
180
|
-
mars_gamma: float = 0.0025, gradient_clipping: C.str_or_fn = C.use_default,
|
181
|
-
update_clipping: C.str_or_fn = C.use_default, palm: bool = C.use_default, beta2_scale: float = 0.8):
|
182
|
-
# ...
|
183
|
-
```
|
184
|
-
|
185
|
-
A foreach implementation of the ADOPT optimizer, which uses a debiased estimate of the second moment of the gradients.
|
186
|
-
|
187
|
-
**Key Parameters:**
|
188
|
-
|
189
|
-
* **`lr`**: Learning rate.
|
190
|
-
* **`betas`**: Coefficients used for computing running averages of the gradient and its square.
|
191
|
-
* **`eps`**: A small constant for numerical stability.
|
192
|
-
* **`weight_decay`**: Weight decay coefficient.
|
193
|
-
* **`warmup_steps`**: Number of steps for linear learning rate warmup.
|
194
|
-
* **`foreach`**: Enables/disables the use of `foreach` operations.
|
195
|
-
* **`storage_dtype`**: The floating-point type to be used for internal state. `"float32"` or `"bfloat16"`.
|
196
|
-
* **`mars`**: Enables/disables Mars correction.
|
197
|
-
* **`caution`**: Enables/disables the use of a cautious update rule, avoiding updates that point in the opposite
|
198
|
-
direction to the gradients.
|
199
|
-
* **`mars_gamma`**: Mars correction coefficient.
|
200
|
-
* **`gradient_clipping`**: Gradient clipping function or method. See `heavyball.utils` for available options.
|
201
|
-
* **`update_clipping`**: Update clipping function or method. See `heavyball.utils` for available options.
|
202
|
-
* **`palm`**: Enables/disables PaLM's beta2 schedule.
|
203
|
-
* **`beta2_scale`**: if we're using the PaLM schedule, `beta2 = step ** -beta2_scale`
|
204
|
-
|
205
|
-
#### `ForeachMuon`
|
206
|
-
|
207
|
-
```python
|
208
|
-
class ForeachMuon(C.BaseOpt):
|
209
|
-
def __init__(self, params, lr=0.0025, betas=(0.9, 0.99), eps=1e-8, weight_decay=0, warmup_steps=0,
|
210
|
-
foreach: bool = True, storage_dtype: str = 'float32', mars: bool = False, caution: bool = False,
|
211
|
-
mars_gamma: float = 0.0025, gradient_clipping: C.str_or_fn = C.use_default,
|
212
|
-
update_clipping: C.str_or_fn = C.use_default, palm: bool = C.use_default, beta2_scale: float = 0.8,
|
213
|
-
nesterov: bool = True):
|
214
|
-
# ...
|
215
|
-
```
|
216
|
-
|
217
|
-
A foreach implementation of the Muon optimizer, incorporating orthogonal updates via the `orthogonalize_update`
|
218
|
-
transformation.
|
219
|
-
|
220
|
-
**Key Parameters:**
|
221
|
-
|
222
|
-
* **`lr`**: Learning rate.
|
223
|
-
* **`betas`**: Coefficients used for computing running averages of the gradient and its square.
|
224
|
-
* **`eps`**: A small constant for numerical stability.
|
225
|
-
* **`weight_decay`**: Weight decay coefficient.
|
226
|
-
* **`warmup_steps`**: Number of steps for linear learning rate warmup.
|
227
|
-
* **`foreach`**: Enables/disables the use of `foreach` operations.
|
228
|
-
* **`storage_dtype`**: The floating-point type to be used for internal state. `"float32"` or `"bfloat16"`.
|
229
|
-
* **`mars`**: Enables/disables Mars correction.
|
230
|
-
* **`caution`**: Enables/disables the use of a cautious update rule, avoiding updates that point in the opposite
|
231
|
-
direction to the gradients.
|
232
|
-
* **`mars_gamma`**: Mars correction coefficient.
|
233
|
-
* **`gradient_clipping`**: Gradient clipping function or method. See `heavyball.utils` for available options.
|
234
|
-
* **`update_clipping`**: Update clipping function or method. See `heavyball.utils` for available options.
|
235
|
-
* **`palm`**: Enables/disables PaLM's beta2 schedule.
|
236
|
-
* **`beta2_scale`**: if we're using the PaLM schedule, `beta2 = step ** -beta2_scale`
|
237
|
-
* **`nesterov`**: Enables/disables Nesterov momentum.
|
238
|
-
|
239
|
-
#### `ForeachLaProp`
|
240
|
-
|
241
|
-
```python
|
242
|
-
class ForeachLaProp(C.BaseOpt):
|
243
|
-
def __init__(self, params, lr=0.0025, betas=(0.9, 0.99), eps=1e-8, weight_decay=0, warmup_steps=0,
|
244
|
-
foreach: bool = True, storage_dtype: str = 'float32', mars: bool = False, caution: bool = False,
|
245
|
-
mars_gamma: float = 0.0025, gradient_clipping: C.str_or_fn = C.use_default,
|
246
|
-
update_clipping: C.str_or_fn = C.use_default, palm: bool = C.use_default, beta2_scale: float = 0.8):
|
247
|
-
# ...
|
248
|
-
```
|
249
|
-
|
250
|
-
A foreach implementation of the LaProp optimizer.
|
251
|
-
|
252
|
-
**Key Parameters:**
|
253
|
-
|
254
|
-
* **`lr`**: Learning rate.
|
255
|
-
* **`betas`**: Coefficients used for computing running averages of the gradient and its square.
|
256
|
-
* **`eps`**: A small constant for numerical stability.
|
257
|
-
* **`weight_decay`**: Weight decay coefficient.
|
258
|
-
* **`warmup_steps`**: Number of steps for linear learning rate warmup.
|
259
|
-
* **`foreach`**: Enables/disables the use of `foreach` operations.
|
260
|
-
* **`storage_dtype`**: The floating-point type to be used for internal state. `"float32"` or `"bfloat16"`.
|
261
|
-
* **`mars`**: Enables/disables Mars correction.
|
262
|
-
* **`caution`**: Enables/disables the use of a cautious update rule, avoiding updates that point in the opposite
|
263
|
-
direction to the gradients.
|
264
|
-
* **`mars_gamma`**: Mars correction coefficient.
|
265
|
-
* **`gradient_clipping`**: Gradient clipping function or method. See `heavyball.utils` for available options.
|
266
|
-
* **`update_clipping`**: Update clipping function or method. See `heavyball.utils` for available options.
|
267
|
-
* **`palm`**: Enables/disables PaLM's beta2 schedule.
|
268
|
-
* **`beta2_scale`**: if we're using the PaLM schedule, `beta2 = step ** -beta2_scale`
|
269
|
-
|
270
|
-
#### `MuonLaProp`
|
271
|
-
|
272
|
-
```python
|
273
|
-
class MuonLaProp(C.BaseOpt):
|
274
|
-
def __init__(self, params, lr=0.0025, betas=(0.9, 0.99), eps=1e-8, weight_decay=0, warmup_steps=0,
|
275
|
-
foreach: bool = True, storage_dtype: str = 'float32', mars: bool = False, caution: bool = False,
|
276
|
-
mars_gamma: float = 0.0025, gradient_clipping: C.str_or_fn = C.use_default,
|
277
|
-
update_clipping: C.str_or_fn = C.use_default, palm: bool = C.use_default, beta2_scale: float = 0.8):
|
278
|
-
# ...
|
279
|
-
```
|
280
|
-
|
281
|
-
A variant of LaProp that incorporates orthogonal updates via the `orthogonalize_update` transformation.
|
282
|
-
|
283
|
-
**Key Parameters:**
|
284
|
-
|
285
|
-
* **`lr`**: Learning rate.
|
286
|
-
* **`betas`**: Coefficients used for computing running averages of the gradient and its square.
|
287
|
-
* **`eps`**: A small constant for numerical stability.
|
288
|
-
* **`weight_decay`**: Weight decay coefficient.
|
289
|
-
* **`warmup_steps`**: Number of steps for linear learning rate warmup.
|
290
|
-
* **`foreach`**: Enables/disables the use of `foreach` operations.
|
291
|
-
* **`storage_dtype`**: The floating-point type to be used for internal state. `"float32"` or `"bfloat16"`.
|
292
|
-
* **`mars`**: Enables/disables Mars correction.
|
293
|
-
* **`caution`**: Enables/disables the use of a cautious update rule, avoiding updates that point in the opposite
|
294
|
-
direction to the gradients.
|
295
|
-
* **`mars_gamma`**: Mars correction coefficient.
|
296
|
-
* **`gradient_clipping`**: Gradient clipping function or method. See `heavyball.utils` for available options.
|
297
|
-
* **`update_clipping`**: Update clipping function or method. See `heavyball.utils` for available options.
|
298
|
-
* **`palm`**: Enables/disables PaLM's beta2 schedule.
|
299
|
-
* **`beta2_scale`**: if we're using the PaLM schedule, `beta2 = step ** -beta2_scale`
|
300
|
-
|
301
|
-
#### `ForeachSOAP`
|
302
|
-
|
303
|
-
```python
|
304
|
-
class ForeachSOAP(C.BaseOpt):
|
305
|
-
use_precond_schedule: bool = False
|
306
|
-
|
307
|
-
def __init__(self, params, lr: float = 3e-3, betas=(0.9, 0.95), shampoo_beta: float = 0.95, eps: float = 1e-8,
|
308
|
-
weight_decay: float = 0.01, precondition_frequency: int = 2, max_precond_dim: int = 2048, #
|
309
|
-
merge_dims: bool = True, precondition_1d: bool = False, normalize_grads: bool = False,
|
310
|
-
correct_bias: bool = True, warmup_steps: int = 1,
|
311
|
-
split: bool = False, foreach: bool = True, mars: bool = False, caution: bool = False,
|
312
|
-
mars_gamma: float = 0.0025, palm: bool = C.use_default, precond_scheduler=(1 / 3, 9),
|
313
|
-
beta2_scale: float = 0.8, use_precond_schedule: bool = C.use_default,
|
314
|
-
gradient_clipping: C.str_or_fn = C.use_default, update_clipping: C.str_or_fn = C.use_default):
|
315
|
-
# ...
|
316
|
-
```
|
317
|
-
|
318
|
-
A foreach implementation of the SOAP (Second-Order Adaptive Preconditioner) optimizer. It uses a preconditioner based on
|
319
|
-
the second-order statistics of the gradients to accelerate convergence.
|
320
|
-
|
321
|
-
**Key Parameters:**
|
322
|
-
|
323
|
-
* **`lr`**: Learning rate.
|
324
|
-
* **`betas`**: Coefficients used for computing running averages of the gradient.
|
325
|
-
* **`shampoo_beta`**: Coefficient used for computing running average of the preconditioner.
|
326
|
-
* **`eps`**: A small constant for numerical stability.
|
327
|
-
* **`weight_decay`**: Weight decay coefficient.
|
328
|
-
* **`precondition_frequency`**: Frequency of preconditioner updates. If using `use_precond_schedule`, this parameter is
|
329
|
-
ignored.
|
330
|
-
* **`max_precond_dim`**: Maximum dimension of the preconditioner.
|
331
|
-
* **`merge_dims`**: Whether to merge dimensions when forming the preconditioner.
|
332
|
-
* **`precondition_1d`**: Whether to use a 1D preconditioner for 1D parameters.
|
333
|
-
* **`normalize_grads`**: Whether to normalize gradients before applying SOAP.
|
334
|
-
* **`correct_bias`**: Enables/disables bias correction for the running averages.
|
335
|
-
* **`warmup_steps`**: Number of steps for linear learning rate warmup.
|
336
|
-
* **`split`**: Whether to split large dimensions when forming the preconditioner.
|
337
|
-
* **`foreach`**: Enables/disables the use of `foreach` operations.
|
338
|
-
* **`mars`**: Enables/disables Mars correction.
|
339
|
-
* **`caution`**: Enables/disables the use of a cautious update rule, avoiding updates that point in the opposite
|
340
|
-
direction to the gradients.
|
341
|
-
* **`mars_gamma`**: Mars correction coefficient.
|
342
|
-
* **`palm`**: Enables/disables PaLM's beta2 schedule.
|
343
|
-
* **`precond_scheduler`**: A tuple `(power, log_base)` specifying the preconditioner update schedule, where the update
|
344
|
-
probability is `1 / (step ** power * log_base)`. This parameter is only used if `use_precond_schedule` is `True`.
|
345
|
-
* **`beta2_scale`**: if we're using the PaLM schedule, `beta2 = step ** -beta2_scale`
|
346
|
-
* **`use_precond_schedule`**: Whether to use a dynamic preconditioner update schedule instead of a fixed frequency.
|
347
|
-
* **`gradient_clipping`**: Gradient clipping function or method. See `heavyball.utils` for available options.
|
348
|
-
* **`update_clipping`**: Update clipping function or method. See `heavyball.utils` for available options.
|
349
|
-
|
350
|
-
#### `PaLMForeachSOAP`
|
351
|
-
|
352
|
-
```python
|
353
|
-
class PaLMForeachSOAP(ForeachSOAP):
|
354
|
-
use_precond_schedule: bool = False
|
355
|
-
palm: bool = True
|
356
|
-
```
|
357
|
-
|
358
|
-
A specialized version of `ForeachSOAP` with PaLM's beta2 schedule enabled by default.
|
359
|
-
|
360
|
-
#### `PrecondScheduleForeachSOAP`
|
361
|
-
|
362
|
-
```python
|
363
|
-
class PrecondScheduleForeachSOAP(ForeachSOAP):
|
364
|
-
use_precond_schedule: bool = True
|
365
|
-
```
|
366
|
-
|
367
|
-
A specialized version of `ForeachSOAP` that uses a dynamic preconditioner update schedule.
|
368
|
-
|
369
|
-
#### `PrecondSchedulePaLMForeachSOAP`
|
370
|
-
|
371
|
-
```python
|
372
|
-
class PrecondSchedulePaLMForeachSOAP(ForeachSOAP):
|
373
|
-
use_precond_schedule: bool = True
|
374
|
-
palm: bool = True
|
375
|
-
```
|
376
|
-
|
377
|
-
A specialized version of `ForeachSOAP` with both PaLM-specific modifications and a dynamic preconditioner update
|
378
|
-
schedule enabled by default.
|
379
|
-
|
380
|
-
#### `ForeachPSGDKron`
|
381
|
-
|
382
|
-
```python
|
383
|
-
class ForeachPSGDKron(C.BaseOpt):
|
384
|
-
delayed: bool = False
|
385
|
-
cached: bool = False
|
386
|
-
exp_avg_input: bool = True
|
387
|
-
|
388
|
-
def __init__(self, params, lr=0.001, beta=0.9, weight_decay=0.0, preconditioner_update_probability=None,
|
389
|
-
max_size_triangular=2048, min_ndim_triangular=2, memory_save_mode=None,
|
390
|
-
momentum_into_precond_update=True, warmup_steps: int = 1, merge_dims: bool = False,
|
391
|
-
split: bool = False, store_triu_as_line: bool = True, foreach: bool = True, q_dtype='float32',
|
392
|
-
stochastic_schedule: bool = True, storage_dtype: str = 'float32', mars: bool = False,
|
393
|
-
caution: bool = False, mars_gamma: float = 0.0025, delayed: Optional[bool] = C.use_default,
|
394
|
-
cached: Optional[bool] = C.use_default, exp_avg_input: Optional[bool] = C.use_default,
|
395
|
-
gradient_clipping: C.str_or_fn = C.use_default, update_clipping: C.str_or_fn = C.use_default, #
|
396
|
-
# expert parameters
|
397
|
-
precond_init_scale=1.0, precond_lr=0.1):
|
398
|
-
# ...
|
399
|
-
```
|
400
|
-
|
401
|
-
A foreach implementation of the PSGD (Preconditioned Stochastic Gradient Descent) optimizer with Kronecker-factored
|
402
|
-
preconditioners.
|
403
|
-
|
404
|
-
**Key Parameters:**
|
405
|
-
|
406
|
-
* **`lr`**: Learning rate.
|
407
|
-
* **`beta`**: Coefficient used for computing running average of the gradient.
|
408
|
-
* **`weight_decay`**: Weight decay coefficient.
|
409
|
-
* **`preconditioner_update_probability`**: Probability of updating the preconditioner at each step. If `None`, a default
|
410
|
-
schedule is used.
|
411
|
-
* **`max_size_triangular`**: Maximum size of triangular matrices used in the preconditioner.
|
412
|
-
* **`min_ndim_triangular`**: Minimum number of dimensions for a tensor to be considered for triangular preconditioner.
|
413
|
-
* **`memory_save_mode`**: Memory saving mode for the preconditioner. Can be `None`, `"one_diag"`, or `"all_diag"`.
|
414
|
-
* **`momentum_into_precond_update`**: Whether to use momentum in the preconditioner update.
|
415
|
-
* **`warmup_steps`**: Number of steps for linear learning rate warmup.
|
416
|
-
* **`merge_dims`**: Whether to merge dimensions when forming the preconditioner.
|
417
|
-
* **`split`**: Whether to split large dimensions when forming the preconditioner.
|
418
|
-
* **`store_triu_as_line`**: Whether to store the upper triangular part of the preconditioner as a 1D vector.
|
419
|
-
* **`foreach`**: Enables/disables the use of `foreach` operations.
|
420
|
-
* **`q_dtype`**: The floating-point type to be used for the preconditioner. `"float32"` or `"bfloat16"`.
|
421
|
-
* **`stochastic_schedule`**: Whether to use a stochastic schedule for updating the preconditioner.
|
422
|
-
* **`storage_dtype`**: The floating-point type to be used for internal state. `"float32"` or `"bfloat16"`.
|
423
|
-
* **`mars`**: Enables/disables Mars correction.
|
424
|
-
* **`caution`**: Enables/disables the use of a cautious update rule, avoiding updates that point in the opposite
|
425
|
-
direction to the gradients.
|
426
|
-
* **`mars_gamma`**: Mars correction coefficient.
|
427
|
-
* **`delayed`**: Enables/disables delayed preconditioner updates.
|
428
|
-
* **`cached`**: Enables/disables caching of preconditioner-related computations.
|
429
|
-
* **`exp_avg_input`**: Whether to apply `exp_avg` to the input before calculating the preconditioner.
|
430
|
-
* **`gradient_clipping`**: Gradient clipping function or method. See `heavyball.utils` for available options.
|
431
|
-
* **`update_clipping`**: Update clipping function or method. See `heavyball.utils` for available options.
|
432
|
-
* **`precond_init_scale`**: Initial scale of the preconditioner.
|
433
|
-
* **`precond_lr`**: Learning rate for preconditioner updates.
|
434
|
-
|
435
|
-
#### `ForeachPurePSGD`
|
436
|
-
|
437
|
-
```python
|
438
|
-
class ForeachPurePSGD(ForeachPSGDKron):
|
439
|
-
exp_avg_input: bool = False
|
440
|
-
```
|
441
|
-
|
442
|
-
A specialized version of `ForeachPSGDKron` that does not apply `exp_avg` to the input before calculating the
|
443
|
-
preconditioner.
|
444
|
-
|
445
|
-
#### `ForeachCachedDelayedPSGDKron`
|
446
|
-
|
447
|
-
```python
|
448
|
-
class ForeachCachedDelayedPSGDKron(ForeachPSGDKron):
|
449
|
-
delayed: bool = True
|
450
|
-
cached: bool = True
|
451
|
-
```
|
452
|
-
|
453
|
-
A specialized version of `ForeachPSGDKron` with both delayed preconditioner updates and caching enabled by default.
|
454
|
-
|
455
|
-
#### `ForeachCachedPSGDKron`
|
456
|
-
|
457
|
-
```python
|
458
|
-
class ForeachCachedPSGDKron(ForeachPSGDKron):
|
459
|
-
cached: bool = True
|
460
|
-
```
|
461
|
-
|
462
|
-
A specialized version of `ForeachPSGDKron` with caching enabled by default.
|
463
|
-
|
464
|
-
#### `ForeachDelayedPSGD`
|
465
|
-
|
466
|
-
```python
|
467
|
-
class ForeachDelayedPSGD(ForeachPSGDKron):
|
468
|
-
delayed: bool = True
|
469
|
-
```
|
470
|
-
|
471
|
-
A specialized version of `ForeachPSGDKron` with delayed preconditioner updates enabled by default.
|
472
|
-
|
473
|
-
## `heavyball.utils`
|
474
|
-
|
475
|
-
The `heavyball.utils` module provides several important functions and settings that users may find useful:
|
476
|
-
|
477
|
-
### Settings
|
478
|
-
|
479
|
-
* **`compile_mode`**: (defaults to `"max-autotune-no-cudagraphs"`) Controls the compilation mode used by
|
480
|
-
`torch.compile`. Setting this to `"default"` or `"max-autotune-no-cudagraphs"` improves performance at the cost of
|
481
|
-
increasd compile time. Setting it to `None` disables compilation.
|
482
|
-
* **`dynamic`**: (defaults to `False`) Enables/disables dynamic shapes during compilation. Enabling this reduces
|
483
|
-
compilation time but may lead to slower execution.
|
484
|
-
* **`zeroth_power_mode`**: (defaults to `"qr"`) Controls the method used for computing the zeroth power of a matrix (
|
485
|
-
orthogonalization) in certain preconditioners. Options include:
|
486
|
-
* `"qr"`: Uses QR decomposition.
|
487
|
-
* `"svd"`: Uses singular value decomposition.
|
488
|
-
* `"newtonschulz"`: Uses Newton-Schulz iteration.
|
489
|
-
|
490
|
-
### Gradient/Update Clipping
|
491
|
-
|
492
|
-
The following functions are used for gradient and update clipping. They can be passed to the `gradient_clipping` or
|
493
|
-
`update_clipping` arguments of the optimizers:
|
494
|
-
|
495
|
-
* **`l2_clip_`**: Clips the gradient/update by its L2 norm.
|
496
|
-
* **`rmsnorm_clip_`**: Clips the gradient/update by its RMS norm.
|
497
|
-
* **`trust_region_clip_`**: Clips the gradient/update using a trust region method.
|
498
|
-
* **`mu_law_compress`**: Compresses the gradient/update using the µ-law algorithm.
|
499
|
-
* **`a_law_compress`**: Compresses the gradient/update using the A-law algorithm.
|
500
|
-
* **`identity`**: Does not modify the gradient/update (no clipping).
|
501
|
-
|
502
|
-
### Other Utilities
|
503
|
-
|
504
|
-
* **`set_torch`**: Sets recommended PyTorch settings for performance, including enabling cuDNN benchmark mode, disabling
|
505
|
-
deterministic algorithms, setting the precision of float32 matrix multiplications, and enabling opt-einsum with the "
|
506
|
-
auto-hq" strategy.
|
507
|
-
* **`clean`**: Clears the CUDA cache.
|
508
|
-
* **`hook_optimizer_into_model`**: Hooks an optimizer into a model's `post_accumulate_grad_hook`.
|
509
|
-
* **`fused_hook`**: Hooks an optimizer into a model's `post_accumulate_grad_hook`, fusing multiple parameter updates
|
510
|
-
into a single step.
|
511
|
-
* **`disable_caution_scaling`**: Disables the scaling factor applied when `caution` is enabled in optimizers.
|
512
|
-
|
513
|
-
## Example Usage
|
514
|
-
|
515
|
-
```python
|
516
|
-
import torch
|
517
|
-
from torch import nn
|
518
|
-
import heavyball
|
519
|
-
|
520
|
-
# Define a simple model
|
521
|
-
model = nn.Linear(10, 2)
|
522
|
-
|
523
|
-
# Create an optimizer
|
524
|
-
optimizer = heavyball.ForeachAdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)
|
525
|
-
# alternative:
|
526
|
-
optimizer = heavyball.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)
|
527
|
-
|
528
|
-
# Generate some dummy data
|
529
|
-
input = torch.randn(1, 10)
|
530
|
-
target = torch.randn(1, 2)
|
531
|
-
|
532
|
-
# Training loop
|
533
|
-
for _ in range(100):
|
534
|
-
# Forward pass
|
535
|
-
output = model(input)
|
536
|
-
loss = (output - target).sum()
|
537
|
-
|
538
|
-
# Backward pass
|
539
|
-
loss.backward()
|
540
|
-
|
541
|
-
# Optimizer step
|
542
|
-
optimizer.step()
|
543
|
-
|
544
|
-
# optional: zero gradients; optimizer.step() already does this, which is different from torch.optim
|
545
|
-
optimizer.zero_grad()
|
546
|
-
```
|
547
|
-
|
548
|
-
This example demonstrates how to create an `AdamW` optimizer and use it to train a simple linear model. You can easily
|
549
|
-
replace `AdamW` with any other optimizer from the `heavyball` library and customize its behavior using the various
|
550
|
-
available parameters and settings.
|
551
|
-
|
552
|
-
By using `heavyball`'s optimizers and understanding the options in `heavyball.utils`, users can achieve better
|
553
|
-
performance, control over training, and easier experimentation with advanced optimization techniques.
|
554
|
-
|
555
|
-
|
556
|
-
---
|
557
|
-
|
558
|
-
# `heavyball.chainable`: A Composable Optimizer API
|
559
|
-
|
560
|
-
The `heavyball.chainable` module provides a powerful and flexible way to build optimizers through function composition,
|
561
|
-
similar to Optax. It allows you to chain together a sequence of transformations to create custom optimization algorithms
|
562
|
-
tailored to your specific needs. This modular approach makes it easy to experiment with different optimization
|
563
|
-
strategies and build complex optimizers from simple, reusable components.
|
564
|
-
|
565
|
-
## Core Concept
|
566
|
-
|
567
|
-
At the heart of `heavyball.chainable` lies the concept of gradient transformations. A gradient transformation is simply
|
568
|
-
a function that takes a state dictionary, a group dictionary, an update tensor, a gradient tensor, and a parameter
|
569
|
-
tensor as input, and returns a new (or modified) update tensor. These transformations can be chained together to form an
|
570
|
-
optimization algorithm.
|
571
|
-
|
572
|
-
The state dictionary stores any persistent state needed by the transformation, such as momentum buffers or
|
573
|
-
preconditioners. The group dictionary contains hyperparameters specific to a group of parameters. The update tensor is
|
574
|
-
the current update being processed, the gradient tensor is the gradient of the loss with respect to the parameter, and
|
575
|
-
the parameter tensor is the parameter itself.
|
576
|
-
|
577
|
-
### Function Signature
|
578
|
-
|
579
|
-
A typical gradient transformation function has the following signature:
|
580
|
-
|
581
|
-
```python
|
582
|
-
|
583
|
-
def my_transformation(state: dict, group: dict, update: List[torch.Tensor], grad: List[torch.Tensor],
|
584
|
-
param: List[torch.Tensor]) -> torch.Tensor:
|
585
|
-
# ... transformation logic ...
|
586
|
-
return update
|
587
|
-
```
|
588
|
-
|
589
|
-
or
|
590
|
-
|
591
|
-
```python
|
592
|
-
@C.no_state_no_foreach
|
593
|
-
def my_transformation(group: dict, update: torch.Tensor, grad: torch.Tensor, param: torch.Tensor, *args,
|
594
|
-
**kwargs) -> torch.Tensor:
|
595
|
-
# ... transformation logic ...
|
596
|
-
return update
|
597
|
-
```
|
598
|
-
|
599
|
-
Note that the second version has no state and processes updates one by one, while the first version processes updates
|
600
|
-
in parallel.
|
601
|
-
|
602
|
-
These functions modify the `update` in place or return a new tensor.
|
603
|
-
|
604
|
-
### Example: Scaling by the learning rate
|
605
|
-
|
606
|
-
```python
|
607
|
-
from heavyball import chainable as C
|
608
|
-
|
609
|
-
|
610
|
-
@C.no_state_no_foreach
|
611
|
-
def scale_by_learning_rate(group: dict, update: torch.Tensor, grad: torch.Tensor, param: torch.Tensor) -> torch.Tensor:
|
612
|
-
return update * group["lr"]
|
613
|
-
```
|
614
|
-
|
615
|
-
## `FunctionTransform` and Guards
|
616
|
-
|
617
|
-
To make it easier to create gradient transformations, `heavyball.chainable` provides the `FunctionTransform` class and a
|
618
|
-
set of "guard" decorators.
|
619
|
-
|
620
|
-
### `FunctionTransform`
|
621
|
-
|
622
|
-
`FunctionTransform` is a base class for gradient transformations that provides a common interface and helper methods. It
|
623
|
-
takes a function `fn` as input and stores it along with its name.
|
624
|
-
|
625
|
-
```python
|
626
|
-
class FunctionTransform:
|
627
|
-
def __init__(self, fn):
|
628
|
-
self.fn = fn
|
629
|
-
self.fn_name = self.get_fn().__name__
|
630
|
-
|
631
|
-
def __call__(self, state, group, update, grad, param, *args, **kwargs):
|
632
|
-
raise NotImplementedError
|
633
|
-
|
634
|
-
def get_fn(self):
|
635
|
-
if hasattr(self.fn, 'get_fn'):
|
636
|
-
return self.fn.get_fn()
|
637
|
-
return self.fn
|
638
|
-
|
639
|
-
def val_name(self, name):
|
640
|
-
return f"{self.fn_name}_{name}"
|
641
|
-
```
|
642
|
-
|
643
|
-
### Guards
|
644
|
-
|
645
|
-
Guards are decorators that help manage the state dictionary and ensure that transformations are applied correctly. They
|
646
|
-
handle common tasks like initializing state variables and preventing redundant computations.
|
647
|
-
|
648
|
-
#### `zero_guard`
|
649
|
-
|
650
|
-
The `zero_guard` decorator ensures that a specific variable in the state dictionary is initialized to zero if it doesn't
|
651
|
-
exist.
|
652
|
-
|
653
|
-
```python
|
654
|
-
@C.zero_guard("momentum")
|
655
|
-
def my_transformation(state, group, update, grad, param, momentum):
|
656
|
-
# ... momentum will be initialized to zero if it doesn't exist in state ...
|
657
|
-
return update
|
658
|
-
```
|
659
|
-
|
660
|
-
#### `copy_guard`
|
661
|
-
|
662
|
-
The `copy_guard` decorator creates a copy of a specified input (update, grad, or param) and stores it in the state
|
663
|
-
dictionary.
|
664
|
-
|
665
|
-
```python
|
666
|
-
@C.copy_guard(0, "update_copy") # 0 refers to the 'update' argument
|
667
|
-
def my_transformation(state, group, update, grad, param, update_copy):
|
668
|
-
# ... update_copy will be a copy of the update tensor ...
|
669
|
-
return update
|
670
|
-
```
|
671
|
-
|
672
|
-
#### `general_guard`
|
673
|
-
|
674
|
-
The `general_guard` decorator provides a more flexible way to manage state. It allows you to specify a custom
|
675
|
-
initialization function that is called if a specific variable is not found in the state.
|
676
|
-
|
677
|
-
```python
|
678
|
-
def init_preconditioner(state, group, update, grad, param, **kwargs):
|
679
|
-
|
680
|
-
|
681
|
-
# ... initialize preconditioner ...
|
682
|
-
|
683
|
-
@C.general_guard("precond", init_fn=init_preconditioner)
|
684
|
-
def my_transformation(state, group, update, grad, param, precond):
|
685
|
-
# ... precond will be initialized using init_preconditioner if it doesn't exist ...
|
686
|
-
return update
|
687
|
-
```
|
688
|
-
|
689
|
-
#### `no_state`
|
690
|
-
|
691
|
-
The `no_state` decorator indicates that a transformation does not use or modify any state.
|
692
|
-
|
693
|
-
#### `no_state_no_foreach`
|
694
|
-
|
695
|
-
The `no_state_no_foreach` decorator indicates that a transformation does not use or modify any state and also does not
|
696
|
-
support `foreach` implementations.
|
697
|
-
|
698
|
-
## Chaining Transformations
|
699
|
-
|
700
|
-
The power of `heavyball.chainable` comes from its ability to chain transformations together. This is achieved through
|
701
|
-
the `chain` function.
|
702
|
-
|
703
|
-
```python
|
704
|
-
def chain(state: Union[callable, dict], group, grad, param, *fns):
|
705
|
-
update = [torch.clone(g, memory_format=torch.preserve_format) for g in grad]
|
706
|
-
skip_update = False
|
707
|
-
for fn in fns:
|
708
|
-
try:
|
709
|
-
update = fn(state, group, update, grad, param)
|
710
|
-
except SkipUpdate:
|
711
|
-
skip_update = True
|
712
|
-
continue
|
713
|
-
if update is None:
|
714
|
-
break
|
715
|
-
if not skip_update and update is not None:
|
716
|
-
utils.update_param_(param, update, group['lr'], group['weight_decay'], caution=group['caution'], grad=grad)
|
717
|
-
```
|
718
|
-
|
719
|
-
The `chain` function takes a state dictionary, a group dictionary, a gradient tensor, a parameter tensor, and a sequence
|
720
|
-
of gradient transformations as input. It applies each transformation in order, passing the output of one transformation
|
721
|
-
as the input to the next.
|
722
|
-
|
723
|
-
## Building Optimizers
|
724
|
-
|
725
|
-
The `ChainOpt` class provides a convenient way to build optimizers from chained transformations.
|
726
|
-
|
727
|
-
```python
|
728
|
-
class ChainOpt(utils.StatefulOptimizer):
|
729
|
-
# ...
|
730
|
-
def __init__(self, params, defaults, foreach: bool, *fns):
|
731
|
-
# ...
|
732
|
-
self.fns = tuple(fns)
|
733
|
-
|
734
|
-
def _step(self, group):
|
735
|
-
# ...
|
736
|
-
if not group['foreach'] or len(p) == 1:
|
737
|
-
for param, grad in zip(p, g):
|
738
|
-
chain(self.state_, group, [grad], [param], *self.fns)
|
739
|
-
else:
|
740
|
-
chain(self.state_, group, g, p, *self.fns)
|
741
|
-
# ...
|
742
|
-
```
|
743
|
-
|
744
|
-
### BaseOpt
|
745
|
-
|
746
|
-
The `BaseOpt` class extends `ChainOpt` and provides additional features like gradient clipping, update clipping, and
|
747
|
-
optional PaLM beta2 schedule.
|
748
|
-
|
749
|
-
```python
|
750
|
-
class BaseOpt(ChainOpt):
|
751
|
-
# ...
|
752
|
-
def __init__(self, params, defaults, foreach: bool, gradient_clipping: str_or_fn, update_clipping: str_or_fn,
|
753
|
-
palm: bool = use_default, *fns, compile_step: bool = use_default, promote: bool = use_default):
|
754
|
-
# ...
|
755
|
-
```
|
756
|
-
|
757
|
-
### `ScheduleFree`
|
758
|
-
|
759
|
-
The `ScheduleFree` class provides a convenient interface for using the `update_by_schedule_free` transformation.
|
760
|
-
|
761
|
-
### Predefined Transformations
|
762
|
-
|
763
|
-
`heavyball.chainable` provides a number of predefined gradient transformations, including:
|
764
|
-
|
765
|
-
* `exp_avg`: Calculates the exponential moving average of the gradients.
|
766
|
-
* `scale_by_exp_avg_sq`: Scales the updates by the inverse square root of the exponential moving average of squared
|
767
|
-
gradients.
|
768
|
-
* `scale_by_adam`: Scales the updates using the Adam algorithm.
|
769
|
-
* `update_by_adam`: Updates the parameters using the Adam algorithm.
|
770
|
-
* `scale_by_laprop`: Scales the updates using the LaProp algorithm.
|
771
|
-
* `update_by_laprop`: Updates the parameters using the LaProp algorithm.
|
772
|
-
* `update_by_schedule_free`: Updates the parameters using the Schedule-Free algorithm.
|
773
|
-
* `update_by_adopt`: Updates the parameters using the ADOPT algorithm.
|
774
|
-
* `scale_by_adopt`: Scales the updates using the ADOPT algorithm.
|
775
|
-
* `orthogonalize_update`: Orthogonalizes the update tensor.
|
776
|
-
* `nesterov_momentum`: Applies Nesterov momentum to the updates.
|
777
|
-
* `heavyball_momentum`: Applies heavy-ball momentum to the updates.
|
778
|
-
* `scale_by_soap`: Scales the updates using the SOAP preconditioner.
|
779
|
-
* `scale_by_psgd`: Scales the updates using the PSGD preconditioner.
|
780
|
-
* `scale_by_delayed_psgd`: Scales the updates using the delayed PSGD preconditioner.
|
781
|
-
* `update_by_psgd`: Updates the parameters using the PSGD preconditioner.
|
782
|
-
* `update_by_delayed_psgd`: Updates the parameters using the delayed PSGD preconditioner.
|
783
|
-
* `palm_beta2`: Modifies the beta2 parameter for PaLM optimizers.
|
784
|
-
|
785
|
-
## Creating New Transformations
|
786
|
-
|
787
|
-
You can easily create new gradient transformations by following the function signature and using the provided guards and
|
788
|
-
`FunctionTransform` class.
|
789
|
-
|
790
|
-
### Example: Clipping gradients by norm
|
791
|
-
|
792
|
-
```python
|
793
|
-
from heavyball import chainable as C
|
794
|
-
from heavyball import utils
|
795
|
-
|
796
|
-
|
797
|
-
@C.no_state
|
798
|
-
def clip_by_global_norm(group: dict, update: torch.Tensor, grad: torch.Tensor, param: torch.Tensor,
|
799
|
-
max_norm: float) -> torch.Tensor:
|
800
|
-
"""Clips the gradient by its global norm."""
|
801
|
-
total_norm = torch.norm(torch.stack([torch.norm(g) for g in grad]))
|
802
|
-
clip_coef = max_norm / (total_norm + 1e-6)
|
803
|
-
if clip_coef < 1:
|
804
|
-
return [u * clip_coef for u in update]
|
805
|
-
return update
|
806
|
-
```
|
807
|
-
|
808
|
-
### Example: L2-Normalization of updates
|
809
|
-
|
810
|
-
```python
|
811
|
-
from heavyball import chainable as C
|
812
|
-
from heavyball import utils
|
813
|
-
|
814
|
-
|
815
|
-
@C.no_state_no_foreach
|
816
|
-
def l2_normalize_updates(group: dict, update: torch.Tensor, grad: torch.Tensor, param: torch.Tensor) -> torch.Tensor:
|
817
|
-
"""L2-normalizes the updates."""
|
818
|
-
norm = update.norm()
|
819
|
-
if norm > 0:
|
820
|
-
return update / norm
|
821
|
-
return update
|
822
|
-
```
|
823
|
-
|
824
|
-
---
|
825
|
-
|
826
|
-
## Optimizer Recommendations
|
827
|
-
|
828
|
-
This hierarchy ranks optimizers from most recommended (top) to least recommended (bottom) for general deep learning
|
829
|
-
tasks. However, the best choice always depends on your specific model, dataset, and computational resources.
|
830
|
-
|
831
|
-
**1. Preconditioned Optimizers (SOAP and PSGD):**
|
832
|
-
|
833
|
-
- **Recommendation:** **Start here.** These are generally the most powerful and efficient optimizers in `heavyball`.
|
834
|
-
- **`ForeachSOAP`** (and its variants: `PaLMForeachSOAP`, `PrecondScheduleForeachSOAP`,
|
835
|
-
`PrecondSchedulePaLMForeachSOAP`):
|
836
|
-
- **Strengths:**
|
837
|
-
- **Adaptive Preconditioning:** SOAP dynamically adapts to the curvature of the loss landscape using
|
838
|
-
second-order information, leading to faster convergence, especially in ill-conditioned problems.
|
839
|
-
- **Robustness:** Less sensitive to hyperparameter choices compared to Adam.
|
840
|
-
- **Strong Empirical Performance:** Often outperforms other optimizers across various tasks and architectures.
|
841
|
-
- **Weaknesses:**
|
842
|
-
- **Computational Cost:** Higher per-step cost due to preconditioner computation and updates.
|
843
|
-
- **Memory Usage:** Can use more memory than simpler optimizers, particularly for large models.
|
844
|
-
- **`precondition_frequency` or `precond_scheduler`:** Needs to be tuned, though the default schedule usually
|
845
|
-
works well.
|
846
|
-
- **When to use:**
|
847
|
-
- **Complex models and datasets:** Where optimization is challenging.
|
848
|
-
- **When training stability is crucial.**
|
849
|
-
- **When you can't retune hyperparameters.**
|
850
|
-
- **Variants:**
|
851
|
-
- `PaLMForeachSOAP`: Enables PaLM's beta2 schedule by default.
|
852
|
-
- `PrecondScheduleForeachSOAP`: Uses a dynamic schedule for preconditioner updates.
|
853
|
-
- `PrecondSchedulePaLMForeachSOAP`: Combines the PaLM schedule with a dynamic preconditioner schedule.
|
854
|
-
|
855
|
-
- **`ForeachPSGDKron`** (and its variants: `ForeachPurePSGD`, `ForeachCachedDelayedPSGDKron`, `ForeachCachedPSGDKron`,
|
856
|
-
`ForeachDelayedPSGD`):
|
857
|
-
- **Strengths:**
|
858
|
-
- **Preconditioning:** Uses Kronecker-factored approximations to capture curvature information, providing many
|
859
|
-
of the benefits of second-order methods at a lower cost than full curvature methods.
|
860
|
-
- **Efficiency:** Relatively efficient in terms of computation.
|
861
|
-
- **Tunability:** Offers many options for customization.
|
862
|
-
- **Convergence:** Tends to converge faster than SOAP.
|
863
|
-
- **Weaknesses:**
|
864
|
-
- **No baseline:** SOAP can copy Adam's hyperparameters - PSGD requires more tuning.
|
865
|
-
- **Complexity:** Has many hyperparameters to tune.
|
866
|
-
- **When to use:**
|
867
|
-
- **Large models:** Where memory is a constraint.
|
868
|
-
- **When `ForeachSOAP` is too computationally expensive.**
|
869
|
-
- **When you want potentially the best performance regardless of computational cost.**
|
870
|
-
- **Variants:**
|
871
|
-
- `ForeachPurePSGD`: Disables exponential averaging of the input when calculating the preconditioner.
|
872
|
-
- `ForeachCachedDelayedPSGDKron`: Caches preconditioner-related computations and uses delayed preconditioner
|
873
|
-
updates.
|
874
|
-
- `ForeachCachedPSGDKron`: Caches preconditioner-related computations.
|
875
|
-
- `ForeachDelayedPSGD`: Uses delayed preconditioner updates.
|
876
|
-
|
877
|
-
**2. Muon:**
|
878
|
-
|
879
|
-
- **`ForeachMuon`** (and `MuonLaProp`):
|
880
|
-
- **Strengths:**
|
881
|
-
- **Momentum with Orthogonal Updates:** Combines momentum with orthogonalized updates, which can
|
882
|
-
improve stability and exploration.
|
883
|
-
- **Good Generalization:** Often leads to better generalization performance compared to Adam.
|
884
|
-
- **Weaknesses:**
|
885
|
-
- **Performance:** Generally outperformed by SOAP and PSGD.
|
886
|
-
- **Computational Cost:** Higher overheads than SOAP and PSGD.
|
887
|
-
- **When to use:**
|
888
|
-
- **When generalization is a primary concern.**
|
889
|
-
- **When you want an optimizer less prone to finding sharp minima.**
|
890
|
-
|
891
|
-
**3. Adam-Based Optimizers:**
|
892
|
-
|
893
|
-
- **`ForeachLaProp`**:
|
894
|
-
- **Strengths:**
|
895
|
-
- **Backward Compatibility:** Can use Adam's hyperparameters, but allows a larger range of betas.
|
896
|
-
- **Stability:** More stable than Adam.
|
897
|
-
- **Weaknesses:**
|
898
|
-
- **Performance:** Generally outperformed by SOAP, PSGD, and Muon.
|
899
|
-
- **When to use:**
|
900
|
-
- **When you want less risk or better losses than Adam, but can't run advanced methods.**
|
901
|
-
|
902
|
-
- **`ForeachAdamW`** (and `ForeachSFAdamW`, `PaLMForeachSFAdamW`):
|
903
|
-
- **Strengths:**
|
904
|
-
- **Widely Used:** A popular and well-established optimizer.
|
905
|
-
- **Weaknesses:**
|
906
|
-
- **Performance:** Often outperformed by preconditioned optimizers (SOAP, PSGD) and Muon.
|
907
|
-
- **Sensitivity to Hyperparameters:** Can be sensitive to the choice of learning rate and beta parameters.
|
908
|
-
- **When to use:**
|
909
|
-
- **As a strong baseline.**
|
910
|
-
- **When you are familiar with Adam and want a robust starting point.**
|
911
|
-
- **When computational cost is a major concern (compared to second-order methods).**
|
912
|
-
- **Variants:**
|
913
|
-
- `ForeachSFAdamW`: A Schedule-Free version of AdamW that dynamically adjusts the learning rate.
|
914
|
-
- `PaLMForeachSFAdamW`: A PaLM version of Schedule-Free AdamW.
|
915
|
-
|
916
|
-
## Choosing the Right Optimizer
|
917
|
-
|
918
|
-
1. **Start with Preconditioning:** Begin with either `ForeachSOAP` or `ForeachPSGDKron`. If computational resources are
|
919
|
-
a major constraint, lean towards `ForeachPSGDKron`. If performance is paramount, try `ForeachSOAP` first.
|
920
|
-
|
921
|
-
2. **Consider Muon:** If preconditioned optimizers are not feasible or if you want to explore alternatives that
|
922
|
-
incorporate momentum and orthogonal updates, try `ForeachMuon`.
|
923
|
-
|
924
|
-
3. **Use LaProp or Adam as Baselines:** `ForeachLaProp` can serve as a simple adaptive baseline. `ForeachAdamW` is a
|
925
|
-
strong and widely used baseline that you should always compare against.
|
926
|
-
|
927
|
-
4. **Experiment and Tune:** The best optimizer ultimately depends on your specific problem. It's crucial to experiment
|
928
|
-
with different optimizers and carefully tune their hyperparameters (especially the learning rate).
|
929
|
-
|
930
|
-
## Important Notes
|
931
|
-
|
932
|
-
* **Learning Rate:** The learning rate is the most important hyperparameter. You'll likely need to adjust it when
|
933
|
-
switching between optimizers.
|
934
|
-
* **Warmup:** Consider using a learning rate warmup, especially for more complex optimizers like SOAP and PSGD.
|
935
|
-
* **Weight Decay:** Weight decay can improve generalization for many optimizers, especially AdamW.
|
936
|
-
* **`foreach`:** Use `foreach` versions of the optimizers when possible for better performance.
|
937
|
-
* **`heavyball.utils`:** Remember to utilize the settings and functions in `heavyball.utils` (e.g., `set_torch`,
|
938
|
-
`compile_mode`, `zeroth_power_mode`, clipping functions) to optimize performance and experiment with different
|
939
|
-
configurations.
|