rose-opt 1.0.2__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.
- rose_opt-1.0.2.dist-info/METADATA +297 -0
- rose_opt-1.0.2.dist-info/RECORD +6 -0
- rose_opt-1.0.2.dist-info/WHEEL +5 -0
- rose_opt-1.0.2.dist-info/licenses/LICENSE +201 -0
- rose_opt-1.0.2.dist-info/top_level.txt +1 -0
- rose_opt.py +319 -0
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rose-opt
|
|
3
|
+
Version: 1.0.2
|
|
4
|
+
Summary: Rose: Range-Of-Slice Equilibration optimizer
|
|
5
|
+
Author-email: "Matthew E. Kieren" <mkieren@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/MatthewK78/Rose
|
|
8
|
+
Project-URL: Repository, https://github.com/MatthewK78/Rose
|
|
9
|
+
Project-URL: Issues, https://github.com/MatthewK78/Rose/issues
|
|
10
|
+
Keywords: pytorch,optimizer,deep-learning,machine-learning,gradient-descent,adamw,sgd,fine-tuning,pretraining,ai,artificial-intelligence,lora,diffusion,llm,transformers
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Intended Audience :: Developers
|
|
21
|
+
Classifier: Intended Audience :: Science/Research
|
|
22
|
+
Classifier: Intended Audience :: Education
|
|
23
|
+
Classifier: Operating System :: OS Independent
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Provides-Extra: torch
|
|
28
|
+
Requires-Dist: torch>=2.0.0; extra == "torch"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
<div align="center">
|
|
32
|
+
|
|
33
|
+

|
|
34
|
+
|
|
35
|
+
_**R**ange-**O**f-**S**lice **E**quilibration_
|
|
36
|
+
<br>PyTorch Optimizer
|
|
37
|
+
|
|
38
|
+
Stateless optimization through range-normalized gradient updates.
|
|
39
|
+
|
|
40
|
+
*In loving memory of my mother, **Rose Kieren**.*
|
|
41
|
+
|
|
42
|
+
[](https://pypi.org/project/rose-opt/) [](https://www.python.org/) [](LICENSE)<br>
|
|
43
|
+
[](https://github.com/sponsors/MatthewK78) [](https://www.paypal.com/donate/?hosted_button_id=VHLPWXMWHJ4C8)
|
|
44
|
+
|
|
45
|
+
</div>
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## ๐ฐ News
|
|
50
|
+
|
|
51
|
+
> 2026-04-26 [v1.0.2] โ PyPI support, change to `from rose_opt import Rose`<br>
|
|
52
|
+
> 2026-04-19 [v1.0.1] โ Misc refinements to algorithm and docs<br>
|
|
53
|
+
> 2026-04-17 [v1.0.0] โ Initial public release
|
|
54
|
+
|
|
55
|
+
## ๐น Introduction
|
|
56
|
+
|
|
57
|
+
Most adaptive optimizers (such as Adam, RMSprop, and their many variants) accumulate running statistics for every parameter: first-moment estimates, second-moment estimates, and sometimes more. These buffers can double or triple the memory footprint of a model's parameters and introduce temporal entanglements (bias correction, momentum decay, sensitivity to $\beta$ schedules) that make training dynamics harder to reason about.
|
|
58
|
+
|
|
59
|
+
**Rose** asks a simple question: *how much can you accomplish with just the gradient you have right now?*
|
|
60
|
+
|
|
61
|
+
At each step, Rose normalizes every gradient tensor by a **per-slice range** yielding one adaptive scale factor per output unit. An optional **coefficient-of-variation trust gate** blends per-slice ranges with their global mean when the ranges are noisy, and optional **gradient centralization** removes shared directional bias before scaling.
|
|
62
|
+
|
|
63
|
+
## ๐ฆ Installation
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install rose-opt
|
|
67
|
+
```
|
|
68
|
+
or
|
|
69
|
+
```bash
|
|
70
|
+
pip install git+https://github.com/MatthewK78/Rose
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Usage:
|
|
74
|
+
```python
|
|
75
|
+
from rose_opt import Rose
|
|
76
|
+
|
|
77
|
+
optimizer = Rose(params, lr=1e-3)
|
|
78
|
+
```
|
|
79
|
+
> **Requires** Python โฅ 3.10 and PyTorch โฅ 2.0
|
|
80
|
+
|
|
81
|
+
## โจ Features
|
|
82
|
+
|
|
83
|
+
| Feature | Detail |
|
|
84
|
+
|:--- |:--- |
|
|
85
|
+
| **Zero optimizer state** | No momentum, variance estimates, or even step counters. Memory cost is parameters + gradients + working memory, nothing else. |
|
|
86
|
+
| **Gradient centralization** | Removes the per-slice mean from gradients of rank โฅ 2, reducing internal covariate shift in the gradient signal and often improving stability and generalization. |
|
|
87
|
+
| **CV trust gating** | Automatically detects when per-slice ranges are noisy and gracefully falls back to a robust global estimate. |
|
|
88
|
+
| **Decoupled weight decay** | Standard or schedule-coupled weight decay, preventing late-training decay from overpowering vanishing learning rates. |
|
|
89
|
+
| **BF16 stochastic rounding** | Unbiased rounding for BFloat16 parameters eliminates systematic truncation drift, meaningfully improving low-precision training fidelity. |
|
|
90
|
+
| **Configurable compute precision** | Promotes intermediates to FP64 by default (FP32, BF16, FP16, or native dtype also supported) so that range and division arithmetic stays precise. |
|
|
91
|
+
|
|
92
|
+
## ๐ฌ Method
|
|
93
|
+
|
|
94
|
+
Consider a linear layer with weight matrix $W \in \mathbb{R}^{m \times n}$. Its gradient $G$ has the same shape: $m$ rows, one per output neuron. Rose computes the range ($|\max| - \min$) across the $n$ input-facing elements of each row independently, producing $m$ per-neuron scale factors. Zero-dimensional parameters receive a plain signSGD update.
|
|
95
|
+
|
|
96
|
+
This is analogous to how Adam assigns each *scalar* parameter its own adaptive denominator via a running variance estimate. Rose instead assigns each *output slice* a denominator based on the instantaneous spread of its gradient, requiring no history at all.
|
|
97
|
+
|
|
98
|
+
The **trust gate** addresses a practical concern: when per-slice ranges vary wildly (high coefficient of variation), the individual ranges may become unreliable. The trust factor $\tau = \mu / (\mu + \sigma)$ is close to 1 when ranges are self-consistent and close to 0 when they are noisy. The denominator smoothly interpolates between the local range (full detail) and the global mean range (maximum noise resistance).
|
|
99
|
+
|
|
100
|
+
**Why range instead of variance?** Range is cheaper to compute and maps cleanly to the idea of *scale equilibration*: it answers "how wide is this gradient slice?" rather than "how energetic is it?" In practice, for the shapes common in deep learning, the two carry similar information, but range has the advantage of depending only on two order statistics and producing a scale factor that directly normalizes the gradient's dynamic range.
|
|
101
|
+
|
|
102
|
+
## ๐๏ธ Hyperparameters
|
|
103
|
+
|
|
104
|
+
### `lr`: Learning Rate
|
|
105
|
+
|
|
106
|
+
The global step size. Because this optimizer uses range-based normalization rather than Adam's RMS-based normalization, the same `lr` value can correspond to very different effective update sizes. Tune `lr` independently rather than relying on Adam defaults.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
Rose(params, lr=1e-3)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
### `weight_decay`: Decoupled Weight Decay
|
|
115
|
+
|
|
116
|
+
| | |
|
|
117
|
+
|:--- |:--- |
|
|
118
|
+
| **Default** | `1e-4` |
|
|
119
|
+
| **Disable** | `0` or `None` |
|
|
120
|
+
|
|
121
|
+
A decoupled multiplicative coefficient applied independently of the gradient step, shrinking weights toward zero each step. This is the same formulation used by AdamW.
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
Rose(params, lr=1e-3, weight_decay=1e-4) # default
|
|
125
|
+
Rose(params, lr=1e-3, weight_decay=0) # disabled
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
### `wd_schedule`: Schedule-Coupled Weight Decay
|
|
131
|
+
|
|
132
|
+
| | |
|
|
133
|
+
|:--- |:--- |
|
|
134
|
+
| **Default** | `False` |
|
|
135
|
+
|
|
136
|
+
Scales weight decay proportionally with a learning-rate schedule so that decay weakens as the learning rate drops. This prevents weight decay from dominating the update in the late phase of training when the learning rate is small. The per-step multiplicative factor becomes:
|
|
137
|
+
|
|
138
|
+
$1 - \frac{\eta_t}{\eta_{\text{ref}}} \cdot \lambda$
|
|
139
|
+
|
|
140
|
+
| Value | Behavior |
|
|
141
|
+
|:--- |:--- |
|
|
142
|
+
| `False` | Standard decoupled weight decay. |
|
|
143
|
+
| `True` | $\eta_{\text{ref}}$ is resolved from `max_lr` โ `initial_lr` โ constructor `lr`. |
|
|
144
|
+
| `float` | The provided value is used directly as $\eta_{\text{ref}}$. |
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
Rose(params, lr=1e-3, weight_decay=1e-4, wd_schedule=True) # auto reference
|
|
148
|
+
Rose(params, lr=1e-3, weight_decay=1e-4, wd_schedule=1e-3) # explicit reference
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
### `centralize`: Gradient Centralization
|
|
154
|
+
|
|
155
|
+
| | |
|
|
156
|
+
|:--- |:--- |
|
|
157
|
+
| **Default** | `True` |
|
|
158
|
+
|
|
159
|
+
Subtracts the mean of each gradient slice along the non-leading axes before the range computation. Only applies to parameters with rank โฅ 2, biases and other 1-D parameters are never centralized.
|
|
160
|
+
|
|
161
|
+
Gradient centralization constrains updates in the subspace orthogonal to the slice mean, which can act as a mild regularizer and improve training stability.
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
Rose(params, lr=1e-3, centralize=True) # default
|
|
165
|
+
Rose(params, lr=1e-3, centralize=False) # disabled
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
---
|
|
169
|
+
|
|
170
|
+
### `stabilize`: Coefficient-of-Variation Trust Gating
|
|
171
|
+
|
|
172
|
+
| | |
|
|
173
|
+
|:--- |:--- |
|
|
174
|
+
| **Default** | `True` |
|
|
175
|
+
|
|
176
|
+
Computes a trust factor from the coefficient of variation of the per-slice range tensor and interpolates between the local per-slice range and the global mean range. This can smooth noisy range estimates. Some models perform better with it enabled, others disabled; try both.
|
|
177
|
+
|
|
178
|
+
- **Trust โ 1** (consistent ranges) โ local detail preserved.
|
|
179
|
+
- **Trust โ 0** (noisy ranges) โ smooth global fallback.
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
Rose(params, lr=1e-3, stabilize=True) # default
|
|
183
|
+
Rose(params, lr=1e-3, stabilize=False) # raw per-slice ranges only
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
### `bf16_sr`: BFloat16 Stochastic Rounding
|
|
189
|
+
|
|
190
|
+
| | |
|
|
191
|
+
|:--- |:--- |
|
|
192
|
+
| **Default** | `True` |
|
|
193
|
+
|
|
194
|
+
When a parameter is stored in BFloat16, promotes it to higher precision for the update, then stochastically rounds on write-back. This produces statistically unbiased rounding, correcting for the systematic truncation drift that BF16's limited mantissa otherwise introduces. Has no effect on parameters with any other dtype.
|
|
195
|
+
|
|
196
|
+
| Value | Effect |
|
|
197
|
+
|:--- |:--- |
|
|
198
|
+
| `False` | BF16 stochastic rounding is disabled. |
|
|
199
|
+
| `True` | Uses the default random-number generator. |
|
|
200
|
+
| `torch.Generator` | Treats `bf16_sr` as enabled and forwards the generator to `random_`. Useful for deterministic output. |
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
Rose(params, lr=1e-3, bf16_sr=True) # default
|
|
204
|
+
Rose(params, lr=1e-3, bf16_sr=False) # plain truncation
|
|
205
|
+
|
|
206
|
+
sr_gen = torch.Generator(device="cuda").manual_seed(0xd1ce)
|
|
207
|
+
Rose(params, lr=1e-3, bf16_sr=sr_gen)
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
---
|
|
211
|
+
|
|
212
|
+
### `compute_dtype`: Internal Compute Precision
|
|
213
|
+
|
|
214
|
+
| | |
|
|
215
|
+
|:--- |:--- |
|
|
216
|
+
| **Default** | `"fp64"` |
|
|
217
|
+
|
|
218
|
+
The dtype to which parameters and gradients are promoted for the update step. FP64 is recommended; the intermediate range computation and division benefit from the extra mantissa bits, especially for parameters with large fan-in or near-zero gradient spread.
|
|
219
|
+
|
|
220
|
+
| Value | Effect |
|
|
221
|
+
|:--- |:--- |
|
|
222
|
+
| `torch.float64` / `"fp64"` | Full FP64 precision for all intermediates. |
|
|
223
|
+
| `torch.float32` / `"fp32"` | Reasonable fallback when FP64 is too costly. |
|
|
224
|
+
| `torch.float16` / `"fp16"` | Not generally recommended; listed for completeness. |
|
|
225
|
+
| `torch.bfloat16` / `"bf16"` | Not generally recommended; listed for completeness. |
|
|
226
|
+
| `None` / `"none"` | No promotion; compute in native dtype _(however, BF16 params still use FP32 if `bf16_sr=True`)._ |
|
|
227
|
+
|
|
228
|
+
```python
|
|
229
|
+
Rose(params, lr=1e-3, compute_dtype="fp64") # default
|
|
230
|
+
Rose(params, lr=1e-3, compute_dtype=torch.float32) # lighter
|
|
231
|
+
Rose(params, lr=1e-3, compute_dtype=None) # native
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
## ๐ Acknowledgements
|
|
235
|
+
|
|
236
|
+
This optimizer is named in loving memory of my mother, Rose Kieren, who always listened intently with genuine interest as I rambled about AI and computers, and whose unconditional love and presence through both the best and hardest of times made all of this possible.
|
|
237
|
+
|
|
238
|
+
I am deeply grateful to my late father for always taking an interest in my exploration of technology, and for the encouragement and warmth he brought to every conversation.
|
|
239
|
+
|
|
240
|
+
To my wife, for her extraordinary patience through the countless days and nights I've spent absorbed in programming and research, and for her unwavering intellectual and emotional support.
|
|
241
|
+
|
|
242
|
+
To my son, a source of joy, perspective, and inspiration, whose curiosity and bright spirit remind me why building for the future matters.
|
|
243
|
+
|
|
244
|
+
As an independent researcher, I am grateful for the love and support of all of my family and friends. This work would not have been possible without them.
|
|
245
|
+
|
|
246
|
+
## ๐ A Kind Request
|
|
247
|
+
|
|
248
|
+
If you use Rose in your research, project, or product, I would be grateful if you would **mention it by name** and credit its author, **Matthew E. Kieren**. A citation (see below), a footnote, a line in your README; any acknowledgment, however small, helps motivate me to do more. And if you have a moment, I would love to hear your story.
|
|
249
|
+
|
|
250
|
+
If you'd like to support my ongoing development efforts of this project and others, you can send a donation here on [**GitHub**](https://github.com/sponsors/MatthewK78), or through [**PayPal**](https://www.paypal.com/donate/?hosted_button_id=VHLPWXMWHJ4C8).
|
|
251
|
+
|
|
252
|
+
Your support and acknowledgment are sincerely appreciated! ๐
|
|
253
|
+
|
|
254
|
+
## ๐ Citation
|
|
255
|
+
|
|
256
|
+
```bibtex
|
|
257
|
+
@software{kieren2026rose,
|
|
258
|
+
author = {Kieren, Matthew E.},
|
|
259
|
+
title = {Rose: Range-Of-Slice Equilibration optimizer},
|
|
260
|
+
year = {2026},
|
|
261
|
+
publisher = {Zenodo},
|
|
262
|
+
doi = {10.5281/zenodo.19589764},
|
|
263
|
+
url = {https://doi.org/10.5281/zenodo.19589764}
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## ๐ References
|
|
268
|
+
|
|
269
|
+
<sup>1</sup> Kingma, D. P. & Ba, J. (2014), *Adam: A Method for Stochastic Optimization.* arXiv:[1412.6980](https://arxiv.org/abs/1412.6980)
|
|
270
|
+
|
|
271
|
+
<sup>2</sup> Loshchilov, I. & Hutter, F. (2017), *Decoupled Weight Decay Regularization.* arXiv:[1711.05101](https://arxiv.org/abs/1711.05101)
|
|
272
|
+
|
|
273
|
+
<sup>3</sup> Hazan, E., Levy, K. Y., & Shalev-Shwartz, S. (2015), *Beyond Convexity: Stochastic Quasi-Convex Optimization*. arXiv:[1507.02030](https://arxiv.org/abs/1507.02030)
|
|
274
|
+
|
|
275
|
+
<sup>4</sup> You, Y., Gitman, I., & Ginsburg, B. (2017), *Large Batch Training of Convolutional Networks*. arXiv:[1708.03888](https://arxiv.org/abs/1708.03888)
|
|
276
|
+
|
|
277
|
+
<sup>5</sup> Yu, A. W., Huang, L., Lin, Q., Salakhutdinov, R., & Carbonell, J. (2017), *Block-Normalized Gradient Method: An Empirical Study for Training Deep Neural Network*. arXiv:[1707.04822](https://arxiv.org/abs/1707.04822)
|
|
278
|
+
|
|
279
|
+
<sup>6</sup> Bernstein, J., Wang, Y. X., Azizzadenesheli, K., & Anandkumar, A. (2018), *signSGD: Compressed Optimisation for Non-Convex Problems*. arXiv:[1802.04434](https://arxiv.org/abs/1802.04434)
|
|
280
|
+
|
|
281
|
+
<sup>7</sup> Yong, H., Huang, J., Hua, X. & Zhang, L. (2020). *Gradient Centralization: A New Optimization Technique for Deep Neural Networks.* arXiv:[2004.01461](https://arxiv.org/abs/2004.01461)
|
|
282
|
+
|
|
283
|
+
<sup>8</sup> Zamirai, P., Zhang, J., Aberger, C. R. & De Sa, C. (2020). *Revisiting BFloat16 Training.* arXiv:[2010.06192](https://arxiv.org/abs/2010.06192)
|
|
284
|
+
|
|
285
|
+
## โ๏ธ License
|
|
286
|
+
|
|
287
|
+
Copyright <sup>ยฉ</sup> 2026 Matthew Everet Kieren
|
|
288
|
+
|
|
289
|
+
Licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0). You may use, modify, and distribute this software in accordance with the license. See [`LICENSE`](LICENSE) for the full text.
|
|
290
|
+
|
|
291
|
+
---
|
|
292
|
+
|
|
293
|
+
<div align="center">
|
|
294
|
+
|
|
295
|
+
https://github.com/MatthewK78/Rose
|
|
296
|
+
|
|
297
|
+
</div>
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
rose_opt.py,sha256=EfND7GyjCRVyP2B99BNzmbOpw4RcJdi5clee1x54x2I,14664
|
|
2
|
+
rose_opt-1.0.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
3
|
+
rose_opt-1.0.2.dist-info/METADATA,sha256=57aMdoXqyLmL1R10Q_DwTParRdvvb0Gj3efZDTXFzSc,15138
|
|
4
|
+
rose_opt-1.0.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
5
|
+
rose_opt-1.0.2.dist-info/top_level.txt,sha256=S6ng7BQUmgFOO-SQ9Kec4NLKfY-KWFczHKTxmBJtzfc,9
|
|
6
|
+
rose_opt-1.0.2.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
rose_opt
|
rose_opt.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
# Copyright 2026 Matthew Everet Kieren. All Rights Reserved.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
import torch
|
|
17
|
+
|
|
18
|
+
class Rose(torch.optim.Optimizer):
|
|
19
|
+
"""Rose: Range-Of-Slice Equilibration optimizer.
|
|
20
|
+
In loving memory of my mother, Rose Kieren.
|
|
21
|
+
|
|
22
|
+
Copyright 2026 Matthew Everet Kieren. All Rights Reserved.
|
|
23
|
+
Licensed under the Apache License, Version 2.0.
|
|
24
|
+
|
|
25
|
+
Rose rescales gradients using a per-slice `|max| - min` range
|
|
26
|
+
computed by reducing all dimensions beyond the leading axis.
|
|
27
|
+
Unlike Adam and other stateful optimizers, Rose maintains no
|
|
28
|
+
per-parameter state between steps: no momentum buffers,
|
|
29
|
+
variance estimates, or even step counters. Memory cost is
|
|
30
|
+
parameters + gradients + working memory, nothing else.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
params (iterable):
|
|
34
|
+
Iterable of model parameters or parameter-group dictionaries.
|
|
35
|
+
|
|
36
|
+
lr (float):
|
|
37
|
+
--- Learning Rate ---
|
|
38
|
+
|
|
39
|
+
The global step size. Because this optimizer uses range-based
|
|
40
|
+
normalization rather than Adam's RMS-based normalization, the
|
|
41
|
+
same `lr` value can correspond to very different effective
|
|
42
|
+
update sizes. Tune `lr` independently rather than relying on
|
|
43
|
+
Adam defaults.
|
|
44
|
+
|
|
45
|
+
weight_decay (float or None, optional) [1e-4]:
|
|
46
|
+
--- Decoupled Weight Decay ---
|
|
47
|
+
|
|
48
|
+
A decoupled multiplicative weight-decay coefficient applied
|
|
49
|
+
separately from the adaptive gradient step. It gently
|
|
50
|
+
shrinks weights toward zero at each step and can help reduce
|
|
51
|
+
overfitting. Set to `0` or `None` to disable it.
|
|
52
|
+
|
|
53
|
+
wd_schedule (bool or float, optional) [False]:
|
|
54
|
+
--- Schedule-Coupled Weight Decay ---
|
|
55
|
+
|
|
56
|
+
Scales weight decay proportionally with the learning-rate
|
|
57
|
+
schedule so that decay weakens as the learning rate drops,
|
|
58
|
+
preventing it from overpowering small updates. The per-step
|
|
59
|
+
factor becomes `1 - (lr / lr_ref) * weight_decay`.
|
|
60
|
+
|
|
61
|
+
If `False`, standard decoupled weight decay is used.
|
|
62
|
+
If `True`, `lr_ref` is the first available among
|
|
63
|
+
`group["max_lr"]`, `group["initial_lr"]`, and the
|
|
64
|
+
learning-rate passed at construction time.
|
|
65
|
+
If a float is provided, it is used directly as `lr_ref`.
|
|
66
|
+
|
|
67
|
+
centralize (bool, optional) [True]:
|
|
68
|
+
--- Gradient Centralization ---
|
|
69
|
+
|
|
70
|
+
Removes shared offsets from gradient slices before the range
|
|
71
|
+
computation. This can improve generalization and training
|
|
72
|
+
stability. Biases and other 1D parameters are not
|
|
73
|
+
centralized.
|
|
74
|
+
|
|
75
|
+
stabilize (bool, optional) [True]:
|
|
76
|
+
--- Coefficient-of-Variation Trust Gating ---
|
|
77
|
+
|
|
78
|
+
Computes a trust factor from the coefficient of variation of
|
|
79
|
+
the per-slice range tensor, and then interpolates between the
|
|
80
|
+
local range and a smoother global mean denominator. This can
|
|
81
|
+
smooth noisy range estimates. Some models perform better with
|
|
82
|
+
it enabled, others disabled; try both.
|
|
83
|
+
|
|
84
|
+
bf16_sr (bool or torch.Generator, optional) [True]:
|
|
85
|
+
--- Stochastic Rounding for BFloat16 ---
|
|
86
|
+
|
|
87
|
+
Improves BF16 training by using stochastic rounding instead
|
|
88
|
+
of plain truncation when writing parameters back. This has
|
|
89
|
+
no effect on non-BF16 parameters.
|
|
90
|
+
|
|
91
|
+
BF16 parameters are promoted to `compute_dtype` (or to FP32
|
|
92
|
+
if `compute_dtype` is `None`) for the update and then
|
|
93
|
+
cast to FP32 for write-back. The result is stochastically
|
|
94
|
+
rounded by adding uniform noise to the lower 16 bits of the
|
|
95
|
+
FP32 representation before truncation to BF16.
|
|
96
|
+
|
|
97
|
+
If `False`, BF16 stochastic rounding is disabled.
|
|
98
|
+
If `True`, uses the default random-number generator.
|
|
99
|
+
If a `torch.Generator` is provided instead of a boolean,
|
|
100
|
+
treats `bf16_sr` as enabled and forwards that generator
|
|
101
|
+
to `random_`. This is useful when you want reproducible
|
|
102
|
+
stochastic rounding noise.
|
|
103
|
+
|
|
104
|
+
compute_dtype (torch.dtype, str, or None, optional) [fp64]:
|
|
105
|
+
--- Internal Compute Precision ---
|
|
106
|
+
|
|
107
|
+
Promotes parameters and gradients to this dtype for the
|
|
108
|
+
update step, then casts them back on write-back. Setting this
|
|
109
|
+
to `None` disables promotion and computes in each parameter's
|
|
110
|
+
native dtype, except that BF16 parameters still use FP32 when
|
|
111
|
+
`bf16_sr` is enabled.
|
|
112
|
+
|
|
113
|
+
FP64 is recommended because the intermediate range and
|
|
114
|
+
division arithmetic benefits from the extra precision.
|
|
115
|
+
|
|
116
|
+
In addition to passing a `torch.dtype` or `None`, the
|
|
117
|
+
following strings are also valid: `float16`, `fp16`,
|
|
118
|
+
`bfloat16`, `bf16`, `float32`, `fp32`, `float64`, `fp64`,
|
|
119
|
+
`none`, and `null`.
|
|
120
|
+
|
|
121
|
+
References:
|
|
122
|
+
- Kingma, D. P. & Ba, J. (2014), Adam: A Method for
|
|
123
|
+
Stochastic Optimization. arXiv:1412.6980
|
|
124
|
+
- Loshchilov, I. & Hutter, F. (2017), Decoupled Weight Decay
|
|
125
|
+
Regularization. arXiv:1711.05101
|
|
126
|
+
- Hazan, E., Levy, K. Y., & Shalev-Shwartz, S. (2015),
|
|
127
|
+
Beyond Convexity: Stochastic Quasi-Convex Optimization.
|
|
128
|
+
arXiv:1507.02030
|
|
129
|
+
- You, Y., Gitman, I., & Ginsburg, B. (2017), Large Batch
|
|
130
|
+
Training of Convolutional Networks. arXiv:1708.03888
|
|
131
|
+
- Yu, A. W., Huang, L., Lin, Q., Salakhutdinov, R., &
|
|
132
|
+
Carbonell, J. (2017), Block-Normalized Gradient Method: An
|
|
133
|
+
Empirical Study for Training Deep Neural Network.
|
|
134
|
+
arXiv:1707.04822
|
|
135
|
+
- Bernstein, J., Wang, Y. X., Azizzadenesheli, K., &
|
|
136
|
+
Anandkumar, A. (2018), signSGD: Compressed Optimisation for
|
|
137
|
+
Non-Convex Problems. arXiv:1802.04434
|
|
138
|
+
- Yong, H., Huang, J., Hua, X. & Zhang, L. (2020), Gradient
|
|
139
|
+
Centralization: A New Optimization Technique for Deep Neural
|
|
140
|
+
Networks. arXiv:2004.01461
|
|
141
|
+
- Zamirai, P., Zhang, J., Aberger, C. R. & De Sa, C. (2020),
|
|
142
|
+
Revisiting BFloat16 Training. arXiv:2010.06192
|
|
143
|
+
"""
|
|
144
|
+
def __init__(
|
|
145
|
+
self,
|
|
146
|
+
params,
|
|
147
|
+
lr: float,
|
|
148
|
+
*,
|
|
149
|
+
weight_decay: float | None = 1e-4,
|
|
150
|
+
wd_schedule: bool | float = False,
|
|
151
|
+
centralize: bool = True,
|
|
152
|
+
stabilize: bool = True,
|
|
153
|
+
bf16_sr: bool | torch.Generator = True,
|
|
154
|
+
compute_dtype: torch.dtype | str | None = "fp64"
|
|
155
|
+
):
|
|
156
|
+
if lr < 0.0:
|
|
157
|
+
raise ValueError(f"\nInvalid learning rate: {lr}") from None
|
|
158
|
+
if weight_decay is not None and weight_decay < 0.0:
|
|
159
|
+
raise ValueError(f"\nInvalid weight_decay: {weight_decay}") from None
|
|
160
|
+
|
|
161
|
+
if isinstance(bf16_sr, torch.Generator):
|
|
162
|
+
self.bf16_sr_gen = bf16_sr
|
|
163
|
+
bf16_sr = True
|
|
164
|
+
else:
|
|
165
|
+
self.bf16_sr_gen = None
|
|
166
|
+
|
|
167
|
+
if isinstance(compute_dtype, str):
|
|
168
|
+
dtype_lookup: dict[str, torch.dtype | None] = {
|
|
169
|
+
"float16": torch.float16, "fp16": torch.float16,
|
|
170
|
+
"float32": torch.float32, "fp32": torch.float32,
|
|
171
|
+
"float64": torch.float64, "fp64": torch.float64,
|
|
172
|
+
"bfloat16": torch.bfloat16, "bf16": torch.bfloat16,
|
|
173
|
+
"none": None, "null": None
|
|
174
|
+
}
|
|
175
|
+
try:
|
|
176
|
+
compute_dtype = dtype_lookup[compute_dtype.strip().lower()]
|
|
177
|
+
except KeyError:
|
|
178
|
+
raise ValueError(
|
|
179
|
+
f"\nInvalid compute_dtype string: {compute_dtype!r}.\n"
|
|
180
|
+
f"Valid options: {sorted(dtype_lookup)}"
|
|
181
|
+
) from None
|
|
182
|
+
|
|
183
|
+
if bf16_sr and compute_dtype not in (torch.float32, torch.float64, None):
|
|
184
|
+
raise ValueError(
|
|
185
|
+
f"\nbf16_sr=True has no useful effect when compute_dtype is {compute_dtype}.\n"
|
|
186
|
+
f"Use torch.float32, torch.float64, or None (same as fp32) instead."
|
|
187
|
+
) from None
|
|
188
|
+
|
|
189
|
+
defaults = dict(
|
|
190
|
+
lr=lr,
|
|
191
|
+
centralize=centralize,
|
|
192
|
+
stabilize=stabilize,
|
|
193
|
+
weight_decay=weight_decay,
|
|
194
|
+
wd_schedule=wd_schedule,
|
|
195
|
+
bf16_sr=bf16_sr,
|
|
196
|
+
compute_dtype=compute_dtype
|
|
197
|
+
)
|
|
198
|
+
super().__init__(params, defaults)
|
|
199
|
+
|
|
200
|
+
@torch.no_grad()
|
|
201
|
+
def step(self, closure=None) -> torch.Tensor | None:
|
|
202
|
+
"""Perform a single Rose optimization step."""
|
|
203
|
+
loss = None
|
|
204
|
+
if closure is not None:
|
|
205
|
+
with torch.enable_grad():
|
|
206
|
+
loss = closure()
|
|
207
|
+
|
|
208
|
+
for group in self.param_groups:
|
|
209
|
+
lr = group["lr"]
|
|
210
|
+
use_stabilize = group["stabilize"]
|
|
211
|
+
use_centralize = group["centralize"]
|
|
212
|
+
bf16_sr = group["bf16_sr"]
|
|
213
|
+
compute_dtype = group["compute_dtype"]
|
|
214
|
+
|
|
215
|
+
# --- Decoupled Weight Decay Factor ---
|
|
216
|
+
weight_decay = group["weight_decay"]
|
|
217
|
+
wd_schedule = group["wd_schedule"]
|
|
218
|
+
group.setdefault("initial_lr", lr)
|
|
219
|
+
|
|
220
|
+
# `wd_schedule` adapted from optimi's "Fully Decoupled Weight Decay":
|
|
221
|
+
# https://optimi.benjaminwarner.dev/fully_decoupled_weight_decay/
|
|
222
|
+
if weight_decay and wd_schedule:
|
|
223
|
+
wd_lr = lr / (
|
|
224
|
+
wd_schedule if isinstance(wd_schedule, float)
|
|
225
|
+
else group.get("max_lr", group.get("initial_lr"))
|
|
226
|
+
)
|
|
227
|
+
else:
|
|
228
|
+
wd_lr = lr
|
|
229
|
+
|
|
230
|
+
wd_factor = None if not weight_decay else max(0.0, 1.0 - wd_lr * weight_decay)
|
|
231
|
+
|
|
232
|
+
for p in group["params"]:
|
|
233
|
+
if p.grad is None:
|
|
234
|
+
continue
|
|
235
|
+
if p.grad.is_sparse:
|
|
236
|
+
raise RuntimeError("Rose does not support sparse gradients")
|
|
237
|
+
|
|
238
|
+
# --- Precision Handling ---
|
|
239
|
+
use_bf16_sr = bf16_sr and p.dtype == torch.bfloat16
|
|
240
|
+
fp32 = use_bf16_sr and compute_dtype is None
|
|
241
|
+
grad = p.grad.to(dtype=torch.float32 if fp32 else compute_dtype)
|
|
242
|
+
param = p.to(dtype=torch.float32 if fp32 else compute_dtype)
|
|
243
|
+
|
|
244
|
+
# --- Decoupled Multiplicative Weight Decay ---
|
|
245
|
+
if wd_factor is not None:
|
|
246
|
+
param.mul_(wd_factor)
|
|
247
|
+
|
|
248
|
+
if grad.ndim == 0:
|
|
249
|
+
# --- 0D Scalar ---
|
|
250
|
+
# Plain signSGD update for single-value parameters.
|
|
251
|
+
param.add_(grad.sign(), alpha=-lr)
|
|
252
|
+
|
|
253
|
+
elif grad.ndim == 1:
|
|
254
|
+
# --- Vectors / Degenerate Slices ---
|
|
255
|
+
g_min, g_max = grad.aminmax()
|
|
256
|
+
denom = g_max.abs_().sub_(g_min)
|
|
257
|
+
denom.masked_fill_(denom == 0.0, 1.0)
|
|
258
|
+
param.addcdiv_(grad, denom, value=-lr)
|
|
259
|
+
|
|
260
|
+
else:
|
|
261
|
+
# --- Active Axes: all axes except the first ---
|
|
262
|
+
# Preserve the leading axis so that each
|
|
263
|
+
# slice receives its own scale.
|
|
264
|
+
active_axes = tuple(range(1, grad.ndim))
|
|
265
|
+
|
|
266
|
+
# --- Gradient Centralization ---
|
|
267
|
+
if use_centralize:
|
|
268
|
+
if grad is not p.grad:
|
|
269
|
+
grad.sub_(grad.mean(dim=active_axes, keepdim=True))
|
|
270
|
+
else:
|
|
271
|
+
grad = grad.sub(grad.mean(dim=active_axes, keepdim=True))
|
|
272
|
+
|
|
273
|
+
# --- Per-slice Range: `R = |max(g)| - min(g)` ---
|
|
274
|
+
# Reducing all non-leading dimensions at once
|
|
275
|
+
# yields one range value per leading-axis slice.
|
|
276
|
+
raw_scale = (
|
|
277
|
+
grad.amax(dim=active_axes, keepdim=True).abs_()
|
|
278
|
+
.sub_(grad.amin(dim=active_axes, keepdim=True))
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
if use_stabilize:
|
|
282
|
+
# --- Coefficient-of-Variation Trust Gating ---
|
|
283
|
+
# Measures the self-consistency of per-slice ranges:
|
|
284
|
+
# Stable ranges preserve local detail.
|
|
285
|
+
# Noisy ranges use global mean for noise resistance.
|
|
286
|
+
std, mean = torch.std_mean(raw_scale, correction=0)
|
|
287
|
+
|
|
288
|
+
# Trust factor:
|
|
289
|
+
# Higher when ranges are self-consistent.
|
|
290
|
+
# Lower when ranges are heterogeneous.
|
|
291
|
+
trust = mean.div(std.add_(mean).masked_fill_(mean == 0.0, 1.0))
|
|
292
|
+
|
|
293
|
+
# Blend each local range with the smoother mean estimate.
|
|
294
|
+
denom = mean.lerp(raw_scale, trust)
|
|
295
|
+
else:
|
|
296
|
+
denom = raw_scale
|
|
297
|
+
|
|
298
|
+
# --- Update: ฮธ -= lr ยท g / D(g) ---
|
|
299
|
+
denom.masked_fill_(denom == 0.0, 1.0) # SGD fallback
|
|
300
|
+
param.addcdiv_(grad, denom, value=-lr)
|
|
301
|
+
|
|
302
|
+
if use_bf16_sr:
|
|
303
|
+
# --- BF16 stochastic rounding ---
|
|
304
|
+
# Inspired by Nerogar's code snippet: https://github.com/pytorch/pytorch/issues/120376#issuecomment-1974828905
|
|
305
|
+
|
|
306
|
+
# P(round up) โ fractional distance โ unbiased expectation
|
|
307
|
+
param = param.to(dtype=torch.float32)
|
|
308
|
+
p.copy_(
|
|
309
|
+
torch.empty_like(p, dtype=torch.int32)
|
|
310
|
+
.random_(0, 0x10000, generator=self.bf16_sr_gen)
|
|
311
|
+
.add_(param.view(dtype=torch.int32))
|
|
312
|
+
.bitwise_and_(-0x10000)
|
|
313
|
+
.view(dtype=torch.float32)
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
elif param is not p:
|
|
317
|
+
p.copy_(param)
|
|
318
|
+
|
|
319
|
+
return loss
|