x-evolution 0.2.1__tar.gz → 0.2.3__tar.gz
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.
- {x_evolution-0.2.1 → x_evolution-0.2.3}/PKG-INFO +73 -3
- {x_evolution-0.2.1 → x_evolution-0.2.3}/README.md +72 -2
- {x_evolution-0.2.1 → x_evolution-0.2.3}/pyproject.toml +1 -1
- {x_evolution-0.2.1 → x_evolution-0.2.3}/tests/test_evolution.py +296 -0
- {x_evolution-0.2.1 → x_evolution-0.2.3}/x_evolution/__init__.py +3 -1
- {x_evolution-0.2.1 → x_evolution-0.2.3}/x_evolution/cma_es.py +101 -31
- x_evolution-0.2.3/x_evolution/noisable.py +255 -0
- {x_evolution-0.2.1 → x_evolution-0.2.3}/x_evolution/x_evolution.py +109 -31
- {x_evolution-0.2.1 → x_evolution-0.2.3}/.gitignore +0 -0
- {x_evolution-0.2.1 → x_evolution-0.2.3}/LICENSE +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: x-evolution
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.3
|
|
4
4
|
Summary: x-evolution
|
|
5
5
|
Project-URL: Homepage, https://pypi.org/project/x-evolution/
|
|
6
6
|
Project-URL: Repository, https://github.com/lucidrains/x-evolution
|
|
@@ -90,7 +90,8 @@ evo_strat = EvoStrategy(
|
|
|
90
90
|
noise_scale = 1e-2, # the scale of the perturbation noise, also the initial noise scale (sigma) if `learned_noise_scale` = True
|
|
91
91
|
num_generations = 100, # number of generations / training steps
|
|
92
92
|
learning_rate = 1e-3, # scale on update derived by fitness and perturb noises
|
|
93
|
-
params_to_optimize = None # defaults to all parameters, but can be [str {param name}] or [Parameter]
|
|
93
|
+
params_to_optimize = None, # defaults to all parameters, but can be [str {param name}] or [Parameter]
|
|
94
|
+
noise_dtype = None # torch.float16 / torch.bfloat16 / torch.int8 for quantized noise - https://arxiv.org/abs/2602.03120
|
|
94
95
|
)
|
|
95
96
|
|
|
96
97
|
# do evolution with your desired fitness function for so many generations
|
|
@@ -101,6 +102,31 @@ evo_strat()
|
|
|
101
102
|
# can also specify checkpoint_every at init and select the one with your favored fitness score for continued policy gradient learning etc
|
|
102
103
|
```
|
|
103
104
|
|
|
105
|
+
## Preventing Catastrophic Forgetting (Anchored Weight Decay)
|
|
106
|
+
|
|
107
|
+
Continuing from a pretrained checkpoint, ES random-walks in directions the new task barely constrains, which can erode prior capabilities. [Anchored Weight Decay (AWD)](https://arxiv.org/abs/2605.30148) from Schweighofer et al. (2026) pulls weights toward their init snapshot without changing the optimizer. This is the L2 form, equivalent to L2 Init (Kumar et al., 2023). Weights are snapshotted at construction:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
evo_strat = EvoStrategy(
|
|
111
|
+
pretrained_model,
|
|
112
|
+
environment = environment,
|
|
113
|
+
num_generations = 100,
|
|
114
|
+
noise_population_size = 32,
|
|
115
|
+
learning_rate = 3e-3,
|
|
116
|
+
anchored_weight_decay_rate = 10. # L2 AWD penalty factor (paper's lambda); lr * rate is pulled toward the anchor each generation
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
evo_strat()
|
|
120
|
+
|
|
121
|
+
# after interleaving with gradient-based training (e.g. PPO -> ES -> PPO -> ES), re-anchor to the latest weights
|
|
122
|
+
evo_strat.reanchor_()
|
|
123
|
+
|
|
124
|
+
# or anchor to an explicit checkpoint / module
|
|
125
|
+
evo_strat.set_init_anchor_(torch.load('earlier.pt'))
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`anchored_weight_decay_rate` is optimizer agnostic and also works with `use_optimizer = False` and custom optimizers. In `EvoStrategy` the pull per step is `learning_rate * anchored_weight_decay_rate`; `CMAEvoStrategy` applies the rate directly once per base update, so it requires `freeze_base = False` or `merge_every`. When using the default SGD optimizer, a positive rate turns off zero-targeting weight decay.
|
|
129
|
+
|
|
104
130
|
## CMA-ES
|
|
105
131
|
|
|
106
132
|
`CMAEvoStrategy` implements full-covariance CMA-ES over a low-rank adapter, so an `(m, n)` weight costs `r * (m + n)` dimensions instead of `m * n`:
|
|
@@ -114,7 +140,8 @@ cma = CMAEvoStrategy(
|
|
|
114
140
|
num_generations = 100,
|
|
115
141
|
lora_rank = 1, # None for the full weight update
|
|
116
142
|
freeze_base = True, # False recenters the base every generation
|
|
117
|
-
noise_scale = 1e-2
|
|
143
|
+
noise_scale = 1e-2, # std of the induced weight delta
|
|
144
|
+
noise_dtype = None # torch.float16 / torch.bfloat16 / torch.int8 for quantized noise - https://arxiv.org/abs/2602.03120
|
|
118
145
|
)
|
|
119
146
|
|
|
120
147
|
cma()
|
|
@@ -178,6 +205,17 @@ Special thanks to [Pollen Robotics 🤗](https://www.pollen-robotics.com/) for t
|
|
|
178
205
|
|
|
179
206
|
## Citations
|
|
180
207
|
|
|
208
|
+
```bibtex
|
|
209
|
+
@article{xu2026quantized,
|
|
210
|
+
title = {Quantized Evolution Strategies: High-precision Fine-tuning of Quantized LLMs at Low-precision Cost},
|
|
211
|
+
author = {Yinggan Xu and Kajetan Schweighofer and Risto Miikkulainen and Xin Qiu},
|
|
212
|
+
journal = {ArXiv},
|
|
213
|
+
year = {2026},
|
|
214
|
+
volume = {abs/2602.03120},
|
|
215
|
+
url = {https://arxiv.org/abs/2602.03120}
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
181
219
|
```bibtex
|
|
182
220
|
@article{Qiu2025EvolutionSA,
|
|
183
221
|
title = {Evolution Strategies at Scale: LLM Fine-Tuning Beyond Reinforcement Learning},
|
|
@@ -269,4 +307,36 @@ Special thanks to [Pollen Robotics 🤗](https://www.pollen-robotics.com/) for t
|
|
|
269
307
|
}
|
|
270
308
|
```
|
|
271
309
|
|
|
310
|
+
```bibtex
|
|
311
|
+
@article{schweighofer2026overcoming,
|
|
312
|
+
title = {Overcoming Forgetting in LLM Fine-Tuning with Evolution Strategies},
|
|
313
|
+
author = {Kajetan Schweighofer and Conor F. Hayes and Roberto Dailey and Risto Miikkulainen and Xin Qiu},
|
|
314
|
+
journal = {ArXiv},
|
|
315
|
+
year = {2026},
|
|
316
|
+
volume = {abs/2605.30148},
|
|
317
|
+
url = {https://arxiv.org/abs/2605.30148}
|
|
318
|
+
}
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
```bibtex
|
|
322
|
+
@article{kumar2023maintaining,
|
|
323
|
+
title = {Maintaining Plasticity in Continual Learning via Regenerative Regularization},
|
|
324
|
+
author = {Saurabh Kumar and Henrik Marklund and Benjamin Van Roy},
|
|
325
|
+
journal = {ArXiv},
|
|
326
|
+
year = {2023},
|
|
327
|
+
url = {https://arxiv.org/abs/2308.11958}
|
|
328
|
+
}
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
```bibtex
|
|
332
|
+
@inproceedings{anonymous2026continual,
|
|
333
|
+
title = {Continual Reinforcement Learning with Neuroevolution},
|
|
334
|
+
author = {Anonymous},
|
|
335
|
+
booktitle = {Submitted to The Fifteenth International Conference on Learning Representations},
|
|
336
|
+
year = {2026},
|
|
337
|
+
url = {https://openreview.net/forum?id=UxsGk4on0e},
|
|
338
|
+
note = {under review}
|
|
339
|
+
}
|
|
340
|
+
```
|
|
341
|
+
|
|
272
342
|
*Nothing makes sense except in the light of evolution* - Theodosius Dobzhansky
|
|
@@ -34,7 +34,8 @@ evo_strat = EvoStrategy(
|
|
|
34
34
|
noise_scale = 1e-2, # the scale of the perturbation noise, also the initial noise scale (sigma) if `learned_noise_scale` = True
|
|
35
35
|
num_generations = 100, # number of generations / training steps
|
|
36
36
|
learning_rate = 1e-3, # scale on update derived by fitness and perturb noises
|
|
37
|
-
params_to_optimize = None # defaults to all parameters, but can be [str {param name}] or [Parameter]
|
|
37
|
+
params_to_optimize = None, # defaults to all parameters, but can be [str {param name}] or [Parameter]
|
|
38
|
+
noise_dtype = None # torch.float16 / torch.bfloat16 / torch.int8 for quantized noise - https://arxiv.org/abs/2602.03120
|
|
38
39
|
)
|
|
39
40
|
|
|
40
41
|
# do evolution with your desired fitness function for so many generations
|
|
@@ -45,6 +46,31 @@ evo_strat()
|
|
|
45
46
|
# can also specify checkpoint_every at init and select the one with your favored fitness score for continued policy gradient learning etc
|
|
46
47
|
```
|
|
47
48
|
|
|
49
|
+
## Preventing Catastrophic Forgetting (Anchored Weight Decay)
|
|
50
|
+
|
|
51
|
+
Continuing from a pretrained checkpoint, ES random-walks in directions the new task barely constrains, which can erode prior capabilities. [Anchored Weight Decay (AWD)](https://arxiv.org/abs/2605.30148) from Schweighofer et al. (2026) pulls weights toward their init snapshot without changing the optimizer. This is the L2 form, equivalent to L2 Init (Kumar et al., 2023). Weights are snapshotted at construction:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
evo_strat = EvoStrategy(
|
|
55
|
+
pretrained_model,
|
|
56
|
+
environment = environment,
|
|
57
|
+
num_generations = 100,
|
|
58
|
+
noise_population_size = 32,
|
|
59
|
+
learning_rate = 3e-3,
|
|
60
|
+
anchored_weight_decay_rate = 10. # L2 AWD penalty factor (paper's lambda); lr * rate is pulled toward the anchor each generation
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
evo_strat()
|
|
64
|
+
|
|
65
|
+
# after interleaving with gradient-based training (e.g. PPO -> ES -> PPO -> ES), re-anchor to the latest weights
|
|
66
|
+
evo_strat.reanchor_()
|
|
67
|
+
|
|
68
|
+
# or anchor to an explicit checkpoint / module
|
|
69
|
+
evo_strat.set_init_anchor_(torch.load('earlier.pt'))
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`anchored_weight_decay_rate` is optimizer agnostic and also works with `use_optimizer = False` and custom optimizers. In `EvoStrategy` the pull per step is `learning_rate * anchored_weight_decay_rate`; `CMAEvoStrategy` applies the rate directly once per base update, so it requires `freeze_base = False` or `merge_every`. When using the default SGD optimizer, a positive rate turns off zero-targeting weight decay.
|
|
73
|
+
|
|
48
74
|
## CMA-ES
|
|
49
75
|
|
|
50
76
|
`CMAEvoStrategy` implements full-covariance CMA-ES over a low-rank adapter, so an `(m, n)` weight costs `r * (m + n)` dimensions instead of `m * n`:
|
|
@@ -58,7 +84,8 @@ cma = CMAEvoStrategy(
|
|
|
58
84
|
num_generations = 100,
|
|
59
85
|
lora_rank = 1, # None for the full weight update
|
|
60
86
|
freeze_base = True, # False recenters the base every generation
|
|
61
|
-
noise_scale = 1e-2
|
|
87
|
+
noise_scale = 1e-2, # std of the induced weight delta
|
|
88
|
+
noise_dtype = None # torch.float16 / torch.bfloat16 / torch.int8 for quantized noise - https://arxiv.org/abs/2602.03120
|
|
62
89
|
)
|
|
63
90
|
|
|
64
91
|
cma()
|
|
@@ -122,6 +149,17 @@ Special thanks to [Pollen Robotics 🤗](https://www.pollen-robotics.com/) for t
|
|
|
122
149
|
|
|
123
150
|
## Citations
|
|
124
151
|
|
|
152
|
+
```bibtex
|
|
153
|
+
@article{xu2026quantized,
|
|
154
|
+
title = {Quantized Evolution Strategies: High-precision Fine-tuning of Quantized LLMs at Low-precision Cost},
|
|
155
|
+
author = {Yinggan Xu and Kajetan Schweighofer and Risto Miikkulainen and Xin Qiu},
|
|
156
|
+
journal = {ArXiv},
|
|
157
|
+
year = {2026},
|
|
158
|
+
volume = {abs/2602.03120},
|
|
159
|
+
url = {https://arxiv.org/abs/2602.03120}
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
125
163
|
```bibtex
|
|
126
164
|
@article{Qiu2025EvolutionSA,
|
|
127
165
|
title = {Evolution Strategies at Scale: LLM Fine-Tuning Beyond Reinforcement Learning},
|
|
@@ -213,4 +251,36 @@ Special thanks to [Pollen Robotics 🤗](https://www.pollen-robotics.com/) for t
|
|
|
213
251
|
}
|
|
214
252
|
```
|
|
215
253
|
|
|
254
|
+
```bibtex
|
|
255
|
+
@article{schweighofer2026overcoming,
|
|
256
|
+
title = {Overcoming Forgetting in LLM Fine-Tuning with Evolution Strategies},
|
|
257
|
+
author = {Kajetan Schweighofer and Conor F. Hayes and Roberto Dailey and Risto Miikkulainen and Xin Qiu},
|
|
258
|
+
journal = {ArXiv},
|
|
259
|
+
year = {2026},
|
|
260
|
+
volume = {abs/2605.30148},
|
|
261
|
+
url = {https://arxiv.org/abs/2605.30148}
|
|
262
|
+
}
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
```bibtex
|
|
266
|
+
@article{kumar2023maintaining,
|
|
267
|
+
title = {Maintaining Plasticity in Continual Learning via Regenerative Regularization},
|
|
268
|
+
author = {Saurabh Kumar and Henrik Marklund and Benjamin Van Roy},
|
|
269
|
+
journal = {ArXiv},
|
|
270
|
+
year = {2023},
|
|
271
|
+
url = {https://arxiv.org/abs/2308.11958}
|
|
272
|
+
}
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
```bibtex
|
|
276
|
+
@inproceedings{anonymous2026continual,
|
|
277
|
+
title = {Continual Reinforcement Learning with Neuroevolution},
|
|
278
|
+
author = {Anonymous},
|
|
279
|
+
booktitle = {Submitted to The Fifteenth International Conference on Learning Representations},
|
|
280
|
+
year = {2026},
|
|
281
|
+
url = {https://openreview.net/forum?id=UxsGk4on0e},
|
|
282
|
+
note = {under review}
|
|
283
|
+
}
|
|
284
|
+
```
|
|
285
|
+
|
|
216
286
|
*Nothing makes sense except in the light of evolution* - Theodosius Dobzhansky
|
|
@@ -68,6 +68,136 @@ def test_evo_strat_vectorized_environment(vector_size):
|
|
|
68
68
|
|
|
69
69
|
evo_strat()
|
|
70
70
|
|
|
71
|
+
@param('noise_dtype', (torch.float16, torch.bfloat16, torch.int8))
|
|
72
|
+
def test_quantized_noise(noise_dtype, tmp_path):
|
|
73
|
+
from x_evolution.x_evolution import EvoStrategy
|
|
74
|
+
|
|
75
|
+
torch.manual_seed(0)
|
|
76
|
+
|
|
77
|
+
model = nn.Linear(1, 1, bias = False)
|
|
78
|
+
|
|
79
|
+
def environment(m):
|
|
80
|
+
return -((m.model.weight - 1.) ** 2).mean().item()
|
|
81
|
+
|
|
82
|
+
evo_strat = EvoStrategy(
|
|
83
|
+
model,
|
|
84
|
+
environment = environment,
|
|
85
|
+
num_generations = 30,
|
|
86
|
+
noise_population_size = 16,
|
|
87
|
+
learning_rate = 1e-1,
|
|
88
|
+
noise_scale = 1e-1,
|
|
89
|
+
noise_dtype = noise_dtype,
|
|
90
|
+
fitness_to_weighted_factor = 'centered_rank',
|
|
91
|
+
cpu = True,
|
|
92
|
+
verbose = False,
|
|
93
|
+
checkpoint_path = str(tmp_path)
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
initial_loss = ((model.weight - 1.) ** 2).mean().item()
|
|
97
|
+
evo_strat()
|
|
98
|
+
|
|
99
|
+
final_loss = ((model.weight - 1.) ** 2).mean().item()
|
|
100
|
+
|
|
101
|
+
assert final_loss < initial_loss * 5e-2
|
|
102
|
+
|
|
103
|
+
noise = evo_strat.noisable_model.create_noise_((4, 4))
|
|
104
|
+
|
|
105
|
+
assert noise.dtype == noise_dtype
|
|
106
|
+
|
|
107
|
+
if noise_dtype == torch.int8:
|
|
108
|
+
assert torch.equal(noise, noise.round())
|
|
109
|
+
|
|
110
|
+
def test_evo_strategy_rollback_is_in_memory(tmp_path):
|
|
111
|
+
from x_evolution.x_evolution import EvoStrategy
|
|
112
|
+
|
|
113
|
+
model = nn.Linear(2, 1, bias = False)
|
|
114
|
+
before = {name: value.clone() for name, value in model.state_dict().items()}
|
|
115
|
+
|
|
116
|
+
def environment(m):
|
|
117
|
+
return -((m.model.weight - 1.) ** 2).mean().item()
|
|
118
|
+
|
|
119
|
+
evo_strat = EvoStrategy(
|
|
120
|
+
model,
|
|
121
|
+
environment = environment,
|
|
122
|
+
num_generations = 1,
|
|
123
|
+
noise_population_size = 2,
|
|
124
|
+
cpu = True,
|
|
125
|
+
verbose = False,
|
|
126
|
+
checkpoint_path = str(tmp_path)
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
evo_strat(rollback_model_at_end = True)
|
|
130
|
+
|
|
131
|
+
for name, value in model.state_dict().items():
|
|
132
|
+
assert torch.equal(value, before[name])
|
|
133
|
+
|
|
134
|
+
# rollback stays in memory
|
|
135
|
+
|
|
136
|
+
assert not (tmp_path / 'initial.model.pt').exists()
|
|
137
|
+
|
|
138
|
+
def test_nested_es_meta(tmp_path):
|
|
139
|
+
depth = 3
|
|
140
|
+
torch.manual_seed(0)
|
|
141
|
+
|
|
142
|
+
model = nn.Linear(1, 1, bias = False)
|
|
143
|
+
x = torch.ones(1, 1)
|
|
144
|
+
y = torch.ones(1, 1)
|
|
145
|
+
|
|
146
|
+
def loss(m):
|
|
147
|
+
with torch.no_grad():
|
|
148
|
+
return ((m(x) - y) ** 2).mean().item()
|
|
149
|
+
|
|
150
|
+
records = {level: [] for level in range(depth + 1)}
|
|
151
|
+
|
|
152
|
+
def make_level(module, level):
|
|
153
|
+
def on_generation(_, __, m):
|
|
154
|
+
records[level].append(loss(m))
|
|
155
|
+
|
|
156
|
+
def environment(m):
|
|
157
|
+
if level == 0:
|
|
158
|
+
return -loss(m)
|
|
159
|
+
|
|
160
|
+
inner = make_level(m, level - 1)
|
|
161
|
+
inner(rollback_model_at_end = True)
|
|
162
|
+
|
|
163
|
+
# selection sees inner endpoint, rollback keeps innate weights
|
|
164
|
+
return -records[level - 1][-1]
|
|
165
|
+
|
|
166
|
+
return CMAEvoStrategy(
|
|
167
|
+
module,
|
|
168
|
+
environment = environment,
|
|
169
|
+
num_generations = 4,
|
|
170
|
+
population_size = 2,
|
|
171
|
+
noise_scale = 1e-1,
|
|
172
|
+
lora_rank = None,
|
|
173
|
+
freeze_base = False,
|
|
174
|
+
mirror_sampling = False,
|
|
175
|
+
on_generation = on_generation,
|
|
176
|
+
cpu = True,
|
|
177
|
+
verbose = False,
|
|
178
|
+
checkpoint_path = str(tmp_path / f'level-{level}')
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
initial_loss = loss(model)
|
|
182
|
+
outer = make_level(model, depth)
|
|
183
|
+
outer()
|
|
184
|
+
final_loss = loss(model)
|
|
185
|
+
|
|
186
|
+
assert final_loss < initial_loss
|
|
187
|
+
|
|
188
|
+
# each level improves over its own run
|
|
189
|
+
|
|
190
|
+
for level in range(depth + 1):
|
|
191
|
+
assert records[level]
|
|
192
|
+
assert records[level][-1] < records[level][0]
|
|
193
|
+
|
|
194
|
+
# calls per level
|
|
195
|
+
|
|
196
|
+
assert len(records[0]) == 2048
|
|
197
|
+
assert len(records[1]) == 256
|
|
198
|
+
assert len(records[2]) == 32
|
|
199
|
+
assert len(records[3]) == 4
|
|
200
|
+
|
|
71
201
|
def test_evo_strat_rejected_generation_advances():
|
|
72
202
|
from x_evolution.x_evolution import EvoStrategy
|
|
73
203
|
|
|
@@ -373,6 +503,45 @@ def test_cma_merge_every_requires_freeze_base():
|
|
|
373
503
|
)
|
|
374
504
|
|
|
375
505
|
|
|
506
|
+
@param('noise_dtype', (torch.float16, torch.bfloat16, torch.int8))
|
|
507
|
+
def test_cma_quantized_noise(noise_dtype, tmp_path):
|
|
508
|
+
torch.manual_seed(0)
|
|
509
|
+
|
|
510
|
+
model = nn.Linear(4, 3, bias = False)
|
|
511
|
+
base = model.weight.detach().clone()
|
|
512
|
+
teacher = base + torch.randn(3, 1) @ torch.randn(1, 4)
|
|
513
|
+
|
|
514
|
+
def environment(m):
|
|
515
|
+
return -((m.weight - teacher) ** 2).mean()
|
|
516
|
+
|
|
517
|
+
cma = CMAEvoStrategy(
|
|
518
|
+
model,
|
|
519
|
+
environment = environment,
|
|
520
|
+
num_generations = 60,
|
|
521
|
+
population_size = 8,
|
|
522
|
+
noise_scale = 1e-1,
|
|
523
|
+
noise_dtype = noise_dtype,
|
|
524
|
+
lora_rank = 1,
|
|
525
|
+
cpu = True,
|
|
526
|
+
verbose = False,
|
|
527
|
+
checkpoint_path = str(tmp_path)
|
|
528
|
+
)
|
|
529
|
+
|
|
530
|
+
_, z, _ = cma.sample_(8, torch.Generator().manual_seed(0))
|
|
531
|
+
|
|
532
|
+
assert z.dtype == noise_dtype
|
|
533
|
+
|
|
534
|
+
if noise_dtype == torch.int8:
|
|
535
|
+
assert torch.equal(z, z.round())
|
|
536
|
+
|
|
537
|
+
initial_distance = (model.weight - teacher).norm().item()
|
|
538
|
+
|
|
539
|
+
cma()
|
|
540
|
+
|
|
541
|
+
final_distance = (model.weight - teacher).norm().item()
|
|
542
|
+
|
|
543
|
+
assert final_distance < initial_distance * 5e-2
|
|
544
|
+
|
|
376
545
|
def test_cma_noise_scale_is_weight_space_std():
|
|
377
546
|
model = nn.Linear(16, 12, bias = False)
|
|
378
547
|
|
|
@@ -640,3 +809,130 @@ def test_cma_scopes():
|
|
|
640
809
|
|
|
641
810
|
fitnesses = cma(num_generations = 1)
|
|
642
811
|
assert fitnesses.shape[-1] == 2
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
@param('use_optimizer', (True, False))
|
|
815
|
+
def test_evo_strat_awd_prevents_nullspace_drift(use_optimizer, tmp_path):
|
|
816
|
+
from functools import partial
|
|
817
|
+
|
|
818
|
+
from torch.optim import SGD
|
|
819
|
+
|
|
820
|
+
from x_evolution.x_evolution import EvoStrategy
|
|
821
|
+
|
|
822
|
+
# w_null is unused by the reward, so any drift is pure forgetting
|
|
823
|
+
|
|
824
|
+
class PretrainedNullspaceModel(nn.Module):
|
|
825
|
+
def __init__(self):
|
|
826
|
+
super().__init__()
|
|
827
|
+
self.w_signal = nn.Parameter(torch.zeros(4))
|
|
828
|
+
self.w_null = nn.Parameter(torch.full((32,), 5.0))
|
|
829
|
+
|
|
830
|
+
def forward(self):
|
|
831
|
+
return -((self.w_signal - 1.0) ** 2).mean()
|
|
832
|
+
|
|
833
|
+
def train(awd_rate, name):
|
|
834
|
+
torch.manual_seed(42)
|
|
835
|
+
model = PretrainedNullspaceModel()
|
|
836
|
+
|
|
837
|
+
evo_strat = EvoStrategy(
|
|
838
|
+
model,
|
|
839
|
+
environment = lambda m: m(),
|
|
840
|
+
num_generations = 40,
|
|
841
|
+
noise_population_size = 16,
|
|
842
|
+
learning_rate = 5e-3,
|
|
843
|
+
noise_scale = 5e-2,
|
|
844
|
+
use_optimizer = use_optimizer,
|
|
845
|
+
anchored_weight_decay_rate = awd_rate,
|
|
846
|
+
optimizer_klass = partial(SGD, nesterov = True, momentum = 0.1),
|
|
847
|
+
cpu = True,
|
|
848
|
+
verbose = False,
|
|
849
|
+
checkpoint_path = str(tmp_path / name)
|
|
850
|
+
)
|
|
851
|
+
evo_strat()
|
|
852
|
+
return model, evo_strat
|
|
853
|
+
|
|
854
|
+
unanchored, _ = train(0., 'unanchored')
|
|
855
|
+
anchored, evo_strat = train(5., 'anchored')
|
|
856
|
+
|
|
857
|
+
assert set(evo_strat.anchor_params) == {'w_signal', 'w_null'}
|
|
858
|
+
assert torch.allclose(evo_strat.anchor_params['w_null'], torch.full((32,), 5.0))
|
|
859
|
+
|
|
860
|
+
# signal improves while the anchored nullspace stays near the checkpoint
|
|
861
|
+
|
|
862
|
+
assert (anchored.w_signal - 1.0).norm().item() < 0.85
|
|
863
|
+
assert (anchored.w_null - 5.0).norm().item() < (unanchored.w_null - 5.0).norm().item() * 0.7
|
|
864
|
+
|
|
865
|
+
# after an external update, reanchor adopts the new weights
|
|
866
|
+
|
|
867
|
+
with torch.no_grad():
|
|
868
|
+
anchored.w_null.fill_(-3.0)
|
|
869
|
+
|
|
870
|
+
evo_strat.reanchor_()
|
|
871
|
+
evo_strat(num_generations = 10)
|
|
872
|
+
assert (anchored.w_null - (-3.0)).norm().item() < 1.0
|
|
873
|
+
|
|
874
|
+
# set_init_anchor_ accepts an explicit state dict or module
|
|
875
|
+
|
|
876
|
+
evo_strat.set_init_anchor_({'w_signal': torch.zeros(4), 'w_null': torch.full((32,), 1.0)})
|
|
877
|
+
assert torch.allclose(evo_strat.anchor_params['w_null'], torch.full((32,), 1.0))
|
|
878
|
+
|
|
879
|
+
anchor_model = PretrainedNullspaceModel()
|
|
880
|
+
|
|
881
|
+
with torch.no_grad():
|
|
882
|
+
anchor_model.w_null.fill_(2.0)
|
|
883
|
+
|
|
884
|
+
evo_strat.set_init_anchor_(anchor_model)
|
|
885
|
+
assert torch.allclose(evo_strat.anchor_params['w_null'], torch.full((32,), 2.0))
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def test_cma_awd_and_reanchor(tmp_path):
|
|
889
|
+
torch.manual_seed(0)
|
|
890
|
+
|
|
891
|
+
class TwoMatrixModel(nn.Module):
|
|
892
|
+
def __init__(self):
|
|
893
|
+
super().__init__()
|
|
894
|
+
self.w_signal = nn.Parameter(torch.zeros(3, 3))
|
|
895
|
+
self.w_null = nn.Parameter(torch.full((4, 4), 3.0))
|
|
896
|
+
|
|
897
|
+
def train(awd_rate, name):
|
|
898
|
+
model = TwoMatrixModel()
|
|
899
|
+
|
|
900
|
+
cma = CMAEvoStrategy(
|
|
901
|
+
model,
|
|
902
|
+
environment = lambda m: -((m.w_signal - 0.5) ** 2).mean(),
|
|
903
|
+
num_generations = 25,
|
|
904
|
+
population_size = 12,
|
|
905
|
+
noise_scale = 1e-1,
|
|
906
|
+
lora_rank = None,
|
|
907
|
+
freeze_base = False,
|
|
908
|
+
mirror_sampling = False,
|
|
909
|
+
anchored_weight_decay_rate = awd_rate,
|
|
910
|
+
cpu = True,
|
|
911
|
+
verbose = False,
|
|
912
|
+
checkpoint_path = str(tmp_path / name)
|
|
913
|
+
)
|
|
914
|
+
cma()
|
|
915
|
+
return model, cma
|
|
916
|
+
|
|
917
|
+
model_unanchored, _ = train(0., 'unanchored')
|
|
918
|
+
model_anchored, cma = train(0.25, 'anchored')
|
|
919
|
+
|
|
920
|
+
assert torch.allclose(cma.default_state.anchor_params['w_null'], torch.full((4, 4), 3.0))
|
|
921
|
+
assert (model_anchored.w_signal - 0.5).norm().item() < (torch.zeros(3, 3) - 0.5).norm().item() * 0.5
|
|
922
|
+
assert (model_anchored.w_null - 3.0).norm().item() < (model_unanchored.w_null - 3.0).norm().item()
|
|
923
|
+
|
|
924
|
+
# after an external update, reanchor adopts the new weights
|
|
925
|
+
|
|
926
|
+
with torch.no_grad():
|
|
927
|
+
model_anchored.w_null.fill_(-2.0)
|
|
928
|
+
|
|
929
|
+
cma.reanchor_()
|
|
930
|
+
assert torch.allclose(cma.default_state.anchor_params['w_null'], torch.full((4, 4), -2.0))
|
|
931
|
+
|
|
932
|
+
cma(num_generations = 5)
|
|
933
|
+
assert (model_anchored.w_null - (-2.0)).norm().item() < 1.0
|
|
934
|
+
|
|
935
|
+
# set a new init anchor explicitly from a state dict
|
|
936
|
+
|
|
937
|
+
cma.set_init_anchor_({'w_signal': torch.zeros(3, 3), 'w_null': torch.full((4, 4), 1.0)})
|
|
938
|
+
assert torch.allclose(cma.default_state.anchor_params['w_null'], torch.full((4, 4), 1.0))
|
|
@@ -1,32 +1,27 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
|
-
from typing import Any
|
|
3
|
-
from collections.abc import Callable
|
|
4
2
|
|
|
3
|
+
from collections.abc import Callable
|
|
5
4
|
from functools import reduce
|
|
6
5
|
from math import ceil, exp, log, sqrt
|
|
7
6
|
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
8
|
|
|
9
9
|
import torch
|
|
10
|
-
from torch import Tensor, tensor, arange, randint
|
|
11
|
-
from torch.nn import Module, ModuleList
|
|
12
|
-
|
|
13
|
-
from tqdm import tqdm
|
|
14
|
-
|
|
15
|
-
from beartype import beartype
|
|
16
|
-
|
|
17
10
|
from accelerate import Accelerator
|
|
18
|
-
|
|
19
|
-
from
|
|
20
|
-
|
|
11
|
+
from beartype import beartype
|
|
12
|
+
from torch import Tensor, arange, randint, tensor
|
|
13
|
+
from torch.nn import Module, ModuleList
|
|
21
14
|
from torch_einops_utils import (
|
|
22
15
|
batched_index_select,
|
|
23
16
|
cast_item,
|
|
24
17
|
dict_add,
|
|
25
18
|
safe_cat,
|
|
26
19
|
safe_stack,
|
|
27
|
-
tree_map_tensor_to_device
|
|
20
|
+
tree_map_tensor_to_device,
|
|
28
21
|
)
|
|
22
|
+
from tqdm import tqdm
|
|
29
23
|
|
|
24
|
+
from x_evolution.noisable import quantize_noise_, validate_noise_dtype, with_seed
|
|
30
25
|
from x_evolution.x_evolution import (
|
|
31
26
|
MAX_SEED_VALUE,
|
|
32
27
|
EvolutionStrategy,
|
|
@@ -35,7 +30,7 @@ from x_evolution.x_evolution import (
|
|
|
35
30
|
divisible_by,
|
|
36
31
|
exists,
|
|
37
32
|
identity,
|
|
38
|
-
resolve_rewards
|
|
33
|
+
resolve_rewards,
|
|
39
34
|
)
|
|
40
35
|
|
|
41
36
|
# full covariance cma-es over rank r adapters
|
|
@@ -54,7 +49,9 @@ class _CMAState:
|
|
|
54
49
|
mirror_sampling,
|
|
55
50
|
population_size,
|
|
56
51
|
noise_scale,
|
|
57
|
-
|
|
52
|
+
noise_dtype,
|
|
53
|
+
sigma_clamp_range,
|
|
54
|
+
anchored_weight_decay_rate = 0.
|
|
58
55
|
):
|
|
59
56
|
self.strategy = strategy
|
|
60
57
|
self.param_names = sorted(param_names)
|
|
@@ -63,7 +60,9 @@ class _CMAState:
|
|
|
63
60
|
self.lora_rank = lora_rank
|
|
64
61
|
self.freeze_base = freeze_base
|
|
65
62
|
self.sep_cma = sep_cma
|
|
63
|
+
self.noise_dtype = noise_dtype
|
|
66
64
|
self.sigma_clamp_range = sigma_clamp_range
|
|
65
|
+
self.anchored_weight_decay_rate = anchored_weight_decay_rate
|
|
67
66
|
|
|
68
67
|
self.dim = 0
|
|
69
68
|
self.param_slices = dict()
|
|
@@ -81,6 +80,14 @@ class _CMAState:
|
|
|
81
80
|
for name in self.param_names
|
|
82
81
|
}
|
|
83
82
|
|
|
83
|
+
self.anchor_params = None
|
|
84
|
+
|
|
85
|
+
if anchored_weight_decay_rate > 0.:
|
|
86
|
+
self.anchor_params = {
|
|
87
|
+
name: param.clone()
|
|
88
|
+
for name, param in self.base_params.items()
|
|
89
|
+
}
|
|
90
|
+
|
|
84
91
|
self.mean = torch.zeros(self.dim, device = device)
|
|
85
92
|
self.C = torch.ones(self.dim, device = device) if sep_cma else torch.eye(self.dim, device = device)
|
|
86
93
|
self.pc = torch.zeros(self.dim, device = device)
|
|
@@ -173,6 +180,18 @@ class _CMAState:
|
|
|
173
180
|
base = self.base_params[name]
|
|
174
181
|
param.data.copy_(base + delta.to(base.device))
|
|
175
182
|
|
|
183
|
+
@torch.no_grad()
|
|
184
|
+
def sample_noise_(self, shape, generator):
|
|
185
|
+
noise_dtype = self.noise_dtype
|
|
186
|
+
|
|
187
|
+
if exists(noise_dtype) and not noise_dtype.is_floating_point:
|
|
188
|
+
noise = torch.randn(shape, generator = generator)
|
|
189
|
+
noise = quantize_noise_(noise, bits = torch.iinfo(noise_dtype).bits, generator = generator)
|
|
190
|
+
else:
|
|
191
|
+
noise = torch.randn(shape, generator = generator, dtype = default(noise_dtype, torch.float32))
|
|
192
|
+
|
|
193
|
+
return noise.to(self.strategy.cma_device)
|
|
194
|
+
|
|
176
195
|
@torch.no_grad()
|
|
177
196
|
def sample_(self, num_samples, generator, mirror_sampling = None):
|
|
178
197
|
mirror_sampling = default(mirror_sampling, self.mirror_sampling)
|
|
@@ -180,10 +199,10 @@ class _CMAState:
|
|
|
180
199
|
if mirror_sampling:
|
|
181
200
|
assert (num_samples % 2) == 0
|
|
182
201
|
half = num_samples // 2
|
|
183
|
-
z_half =
|
|
202
|
+
z_half = self.sample_noise_((half, self.dim), generator)
|
|
184
203
|
z = safe_cat((z_half, -z_half), dim = 0)
|
|
185
204
|
else:
|
|
186
|
-
z =
|
|
205
|
+
z = self.sample_noise_((num_samples, self.dim), generator)
|
|
187
206
|
|
|
188
207
|
if self.sep_cma:
|
|
189
208
|
y = z * self.C.sqrt()
|
|
@@ -273,13 +292,24 @@ class _CMAState:
|
|
|
273
292
|
|
|
274
293
|
self.generation = generation
|
|
275
294
|
|
|
295
|
+
@torch.no_grad()
|
|
296
|
+
def add_to_base_(self, name, delta):
|
|
297
|
+
base = self.base_params[name]
|
|
298
|
+
|
|
299
|
+
# AWD toward the init snapshot (Schweighofer et al. 2026)
|
|
300
|
+
|
|
301
|
+
if self.anchored_weight_decay_rate > 0.:
|
|
302
|
+
base.lerp_(self.anchor_params[name].to(base.device), self.anchored_weight_decay_rate)
|
|
303
|
+
|
|
304
|
+
base.add_(delta.to(base.device))
|
|
305
|
+
|
|
276
306
|
@torch.no_grad()
|
|
277
307
|
def commit_(self):
|
|
278
308
|
if not exists(self._update):
|
|
279
309
|
return
|
|
280
310
|
|
|
281
311
|
for name, delta in self._update.items():
|
|
282
|
-
self.
|
|
312
|
+
self.add_to_base_(name, delta)
|
|
283
313
|
|
|
284
314
|
self._update = None
|
|
285
315
|
self.mean.zero_()
|
|
@@ -290,12 +320,36 @@ class _CMAState:
|
|
|
290
320
|
deltas = self.decode_(self.mean)
|
|
291
321
|
|
|
292
322
|
for name, delta in deltas.items():
|
|
293
|
-
|
|
294
|
-
base.add_(delta.to(base.device))
|
|
323
|
+
self.add_to_base_(name, delta)
|
|
295
324
|
|
|
296
325
|
self.mean.zero_()
|
|
297
326
|
self.set_model_to_(self.mean)
|
|
298
327
|
|
|
328
|
+
@torch.no_grad()
|
|
329
|
+
def set_init_anchor_(self, model_or_state = None):
|
|
330
|
+
# anchor to a module, state dict, or the current weights
|
|
331
|
+
|
|
332
|
+
if not exists(model_or_state):
|
|
333
|
+
state = self.strategy._named_parameters
|
|
334
|
+
elif isinstance(model_or_state, Module):
|
|
335
|
+
state = model_or_state.state_dict()
|
|
336
|
+
else:
|
|
337
|
+
state = model_or_state
|
|
338
|
+
|
|
339
|
+
self.anchor_params = {
|
|
340
|
+
name: state[name].detach().clone().to(self.base_params[name].device)
|
|
341
|
+
for name in self.param_names
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
@torch.no_grad()
|
|
345
|
+
def reanchor_(self):
|
|
346
|
+
self.set_init_anchor_()
|
|
347
|
+
|
|
348
|
+
for name in self.param_names:
|
|
349
|
+
self.base_params[name] = self.anchor_params[name].clone()
|
|
350
|
+
|
|
351
|
+
self.mean.zero_()
|
|
352
|
+
|
|
299
353
|
class CMAEvoStrategy(EvolutionStrategy):
|
|
300
354
|
|
|
301
355
|
@beartype
|
|
@@ -307,9 +361,11 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
307
361
|
num_generations,
|
|
308
362
|
population_size: int | None = None,
|
|
309
363
|
noise_scale = 1e-2,
|
|
364
|
+
noise_dtype: torch.dtype | None = None, # float16 / bfloat16 / int8 - int8 stochastically rounds the sampled noise
|
|
310
365
|
lora_rank: int | None = 1,
|
|
311
366
|
freeze_base = True,
|
|
312
367
|
merge_every: int | None = None, # fold mean into base every n generations
|
|
368
|
+
anchored_weight_decay_rate = 0., # Anchored Weight Decay (AWD) - pulls the base toward its init snapshot
|
|
313
369
|
mirror_sampling = True,
|
|
314
370
|
sep_cma = False, # diagonal covariance: O(dim) memory, no eigendecomposition
|
|
315
371
|
params_to_optimize: dict[str, ParametersToOptimize] | ParametersToOptimize | None = None,
|
|
@@ -423,6 +479,8 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
423
479
|
|
|
424
480
|
self.population_size = population_size
|
|
425
481
|
self.noise_scale = noise_scale
|
|
482
|
+
validate_noise_dtype(noise_dtype)
|
|
483
|
+
self.noise_dtype = noise_dtype
|
|
426
484
|
self.lora_rank = lora_rank
|
|
427
485
|
self.freeze_base = freeze_base
|
|
428
486
|
self.merge_every = merge_every
|
|
@@ -432,6 +490,9 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
432
490
|
assert freeze_base, 'merge_every requires freeze_base=True'
|
|
433
491
|
assert merge_every >= 1, 'merge_every must be >= 1'
|
|
434
492
|
|
|
493
|
+
if anchored_weight_decay_rate > 0.:
|
|
494
|
+
assert not freeze_base or exists(merge_every), 'AWD requires base updates: set freeze_base=False or merge_every'
|
|
495
|
+
|
|
435
496
|
assert not (mirror_sampling and not freeze_base and exists(lora_rank)), 'mirror sampling is incompatible with freeze_base=False and a low-rank adapter; pass mirror_sampling=False or freeze_base=True'
|
|
436
497
|
|
|
437
498
|
self._mirror_sampling = mirror_sampling
|
|
@@ -440,6 +501,9 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
440
501
|
self.cma_device = torch.device(cma_device)
|
|
441
502
|
|
|
442
503
|
assert 0. < sigma_clamp_range[0] < sigma_clamp_range[1]
|
|
504
|
+
assert anchored_weight_decay_rate >= 0.
|
|
505
|
+
|
|
506
|
+
self.anchored_weight_decay_rate = anchored_weight_decay_rate
|
|
443
507
|
|
|
444
508
|
# states are created lazily per parameter subset / scope
|
|
445
509
|
|
|
@@ -514,11 +578,23 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
514
578
|
mirror_sampling = self._mirror_sampling,
|
|
515
579
|
population_size = self.population_size,
|
|
516
580
|
noise_scale = self.noise_scale,
|
|
517
|
-
|
|
581
|
+
noise_dtype = self.noise_dtype,
|
|
582
|
+
sigma_clamp_range = self.sigma_clamp_range,
|
|
583
|
+
anchored_weight_decay_rate = self.anchored_weight_decay_rate
|
|
518
584
|
)
|
|
519
585
|
|
|
520
586
|
return self._states[names]
|
|
521
587
|
|
|
588
|
+
@torch.no_grad()
|
|
589
|
+
def set_init_anchor_(self, model_or_state = None):
|
|
590
|
+
for state in self._states.values():
|
|
591
|
+
state.set_init_anchor_(model_or_state)
|
|
592
|
+
|
|
593
|
+
@torch.no_grad()
|
|
594
|
+
def reanchor_(self):
|
|
595
|
+
for state in self._states.values():
|
|
596
|
+
state.reanchor_()
|
|
597
|
+
|
|
522
598
|
def to_cma_device_(self):
|
|
523
599
|
for state in self._states.values():
|
|
524
600
|
state.to_device_()
|
|
@@ -679,15 +755,9 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
679
755
|
):
|
|
680
756
|
verbose = default(verbose, self.verbose)
|
|
681
757
|
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
original_state = None
|
|
758
|
+
self.model.to(self.device)
|
|
685
759
|
|
|
686
|
-
if rollback_model_at_end
|
|
687
|
-
original_state = {
|
|
688
|
-
name: value.detach().clone()
|
|
689
|
-
for name, value in model.state_dict().items()
|
|
690
|
-
}
|
|
760
|
+
original_state = self.snapshot_model_() if rollback_model_at_end else None
|
|
691
761
|
|
|
692
762
|
self.to_cma_device_()
|
|
693
763
|
|
|
@@ -727,8 +797,8 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
727
797
|
)
|
|
728
798
|
all_fitnesses.append(fitnesses)
|
|
729
799
|
|
|
730
|
-
if
|
|
731
|
-
self.
|
|
800
|
+
if exists(original_state):
|
|
801
|
+
self.restore_model_(original_state)
|
|
732
802
|
|
|
733
803
|
if len(all_fitnesses) == 1:
|
|
734
804
|
return all_fitnesses[0]
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
from functools import partial, wraps
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
from torch import Tensor, randn
|
|
8
|
+
from torch.func import functional_call
|
|
9
|
+
from torch.nn import Module
|
|
10
|
+
|
|
11
|
+
# helpers
|
|
12
|
+
|
|
13
|
+
def exists(v):
|
|
14
|
+
return v is not None
|
|
15
|
+
|
|
16
|
+
def default(v, d):
|
|
17
|
+
return v if exists(v) else d
|
|
18
|
+
|
|
19
|
+
def identity(t):
|
|
20
|
+
return t
|
|
21
|
+
|
|
22
|
+
def is_empty(arr):
|
|
23
|
+
return len(arr) == 0
|
|
24
|
+
|
|
25
|
+
# noise
|
|
26
|
+
|
|
27
|
+
def randn_low_rank(shape, *, k = None, dtype = None):
|
|
28
|
+
if not exists(k) or len(shape) != 2 or min(shape) <= k:
|
|
29
|
+
return randn(shape, dtype = dtype)
|
|
30
|
+
|
|
31
|
+
out, inp = shape
|
|
32
|
+
|
|
33
|
+
a = randn((out, k), dtype = dtype)
|
|
34
|
+
b = randn((k, inp), dtype = dtype)
|
|
35
|
+
|
|
36
|
+
return (a @ b) * (k ** -0.5)
|
|
37
|
+
|
|
38
|
+
def validate_noise_dtype(noise_dtype):
|
|
39
|
+
if not exists(noise_dtype):
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
assert isinstance(noise_dtype, torch.dtype)
|
|
43
|
+
assert noise_dtype.is_floating_point or noise_dtype in (torch.int8, torch.int16), 'noise_dtype must be a float dtype, torch.int8, or torch.int16'
|
|
44
|
+
|
|
45
|
+
def quantize_noise_(noise, bits = 8, generator = None):
|
|
46
|
+
# QES eq. 3 - floor + Bernoulli(frac), then clamp to a signed integer lattice
|
|
47
|
+
|
|
48
|
+
floor = noise.floor()
|
|
49
|
+
noise = floor + torch.bernoulli(noise - floor, generator = generator)
|
|
50
|
+
|
|
51
|
+
bound = (1 << (bits - 1)) - 1
|
|
52
|
+
noise.clamp_(-bound, bound)
|
|
53
|
+
|
|
54
|
+
return noise.to(torch.int8 if bits <= 8 else torch.int16)
|
|
55
|
+
|
|
56
|
+
# temporary seed
|
|
57
|
+
|
|
58
|
+
def with_seed(seed):
|
|
59
|
+
if not exists(seed):
|
|
60
|
+
return identity
|
|
61
|
+
|
|
62
|
+
def decorator(fn):
|
|
63
|
+
@wraps(fn)
|
|
64
|
+
def inner(*args, **kwargs):
|
|
65
|
+
orig_torch_state = torch.get_rng_state()
|
|
66
|
+
|
|
67
|
+
has_cuda = torch.cuda.is_available()
|
|
68
|
+
orig_cuda_states = torch.cuda.get_rng_state_all() if has_cuda else None
|
|
69
|
+
|
|
70
|
+
torch.manual_seed(seed)
|
|
71
|
+
|
|
72
|
+
if has_cuda:
|
|
73
|
+
torch.cuda.manual_seed_all(seed)
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
out = fn(*args, **kwargs)
|
|
77
|
+
finally:
|
|
78
|
+
torch.set_rng_state(orig_torch_state)
|
|
79
|
+
|
|
80
|
+
if has_cuda:
|
|
81
|
+
torch.cuda.set_rng_state_all(orig_cuda_states)
|
|
82
|
+
|
|
83
|
+
return out
|
|
84
|
+
return inner
|
|
85
|
+
|
|
86
|
+
return decorator
|
|
87
|
+
|
|
88
|
+
# wrapper
|
|
89
|
+
|
|
90
|
+
class Noisable(Module):
|
|
91
|
+
def __init__(
|
|
92
|
+
self,
|
|
93
|
+
model: Module,
|
|
94
|
+
noise_scale = 1.,
|
|
95
|
+
overridable_noise_scale = True,
|
|
96
|
+
low_rank = None,
|
|
97
|
+
noise_dtype: torch.dtype | None = None
|
|
98
|
+
):
|
|
99
|
+
super().__init__()
|
|
100
|
+
assert not is_empty(list(model.parameters()))
|
|
101
|
+
|
|
102
|
+
validate_noise_dtype(noise_dtype)
|
|
103
|
+
|
|
104
|
+
self.model = model
|
|
105
|
+
self.noise_scale = noise_scale
|
|
106
|
+
self.noise_dtype = noise_dtype
|
|
107
|
+
|
|
108
|
+
self.overridable_noise_scale = overridable_noise_scale # if set to True, if a noise scale is given alongside a seed in a tuple (int, float), that value replaces the noise scale rather than scales it again
|
|
109
|
+
|
|
110
|
+
# low rank noise (a la lora)
|
|
111
|
+
self.create_noise_fn = randn if not low_rank else partial(randn_low_rank, k = low_rank)
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def device(self):
|
|
115
|
+
return next(self.model.parameters()).device
|
|
116
|
+
|
|
117
|
+
@torch.no_grad()
|
|
118
|
+
def create_noise_(self, shape, dtype = None):
|
|
119
|
+
noise_dtype = default(self.noise_dtype, dtype)
|
|
120
|
+
|
|
121
|
+
# int noise - QES stochastic rounding, stored compactly
|
|
122
|
+
|
|
123
|
+
if exists(noise_dtype) and not noise_dtype.is_floating_point:
|
|
124
|
+
bits = torch.iinfo(noise_dtype).bits
|
|
125
|
+
noise = self.create_noise_fn(shape, dtype = torch.float32)
|
|
126
|
+
return quantize_noise_(noise, bits = bits)
|
|
127
|
+
|
|
128
|
+
return self.create_noise_fn(shape, dtype = noise_dtype)
|
|
129
|
+
|
|
130
|
+
@contextmanager
|
|
131
|
+
def temp_add_noise_(
|
|
132
|
+
self,
|
|
133
|
+
noise_for_params = None,
|
|
134
|
+
noise_scale_for_params = None,
|
|
135
|
+
noise_scale = None,
|
|
136
|
+
negate = False
|
|
137
|
+
):
|
|
138
|
+
self.get_noised_params(noise_for_params, noise_scale_for_params = noise_scale_for_params, noise_scale = noise_scale, inplace = True, negate = negate)
|
|
139
|
+
|
|
140
|
+
yield
|
|
141
|
+
|
|
142
|
+
self.get_noised_params(noise_for_params, noise_scale_for_params = noise_scale_for_params, noise_scale = noise_scale, inplace = True, negate = not negate)
|
|
143
|
+
|
|
144
|
+
def add_noise_(
|
|
145
|
+
self,
|
|
146
|
+
noise_for_params = None,
|
|
147
|
+
noise_scale_for_params = None,
|
|
148
|
+
noise_scale = None,
|
|
149
|
+
add_to_grad = False,
|
|
150
|
+
negate = False
|
|
151
|
+
):
|
|
152
|
+
self.get_noised_params(noise_for_params, noise_scale_for_params = noise_scale_for_params, noise_scale = noise_scale, inplace = True, add_to_grad = add_to_grad, negate = negate)
|
|
153
|
+
|
|
154
|
+
@torch.no_grad()
|
|
155
|
+
def _add_scaled_noise_(self, name, param, noise, scale, inplace, add_to_grad, return_params):
|
|
156
|
+
is_tensor_scale = isinstance(scale, Tensor)
|
|
157
|
+
|
|
158
|
+
if inplace and not add_to_grad:
|
|
159
|
+
if is_tensor_scale:
|
|
160
|
+
param.data.add_(noise * scale)
|
|
161
|
+
else:
|
|
162
|
+
param.data.add_(noise, alpha = scale)
|
|
163
|
+
|
|
164
|
+
elif inplace and add_to_grad:
|
|
165
|
+
if not exists(param.grad):
|
|
166
|
+
grad = noise * scale if is_tensor_scale else noise.to(param.dtype) * scale
|
|
167
|
+
param.grad = grad.to(param.dtype)
|
|
168
|
+
elif is_tensor_scale:
|
|
169
|
+
param.grad.add_(noise * scale)
|
|
170
|
+
else:
|
|
171
|
+
param.grad.add_(noise, alpha = scale)
|
|
172
|
+
|
|
173
|
+
else:
|
|
174
|
+
return_params[name] = param + noise * scale
|
|
175
|
+
|
|
176
|
+
def get_noised_params(
|
|
177
|
+
self,
|
|
178
|
+
noise_for_params = None,
|
|
179
|
+
noise_scale_for_params = None,
|
|
180
|
+
inplace = False,
|
|
181
|
+
noise_scale = None,
|
|
182
|
+
negate = False,
|
|
183
|
+
add_to_grad = False
|
|
184
|
+
):
|
|
185
|
+
noise_for_params = default(noise_for_params, {})
|
|
186
|
+
noise_scale_for_params = default(noise_scale_for_params, {})
|
|
187
|
+
|
|
188
|
+
named_params = dict(self.model.named_parameters())
|
|
189
|
+
return_params = named_params if inplace else dict(named_params)
|
|
190
|
+
|
|
191
|
+
for name, param in named_params.items():
|
|
192
|
+
noise_or_seed = noise_for_params.get(name, None)
|
|
193
|
+
|
|
194
|
+
if not exists(noise_or_seed):
|
|
195
|
+
continue
|
|
196
|
+
|
|
197
|
+
param_noise_scale = default(noise_scale, self.noise_scale)
|
|
198
|
+
|
|
199
|
+
# determine the noise
|
|
200
|
+
|
|
201
|
+
if isinstance(noise_or_seed, int):
|
|
202
|
+
noise = with_seed(noise_or_seed)(self.create_noise_)(param.shape, dtype = param.dtype)
|
|
203
|
+
|
|
204
|
+
elif isinstance(noise_or_seed, tuple) and len(noise_or_seed) == 2:
|
|
205
|
+
seed_or_noise, noise_scale_with_seed = noise_or_seed
|
|
206
|
+
|
|
207
|
+
# could be seed or tensor
|
|
208
|
+
|
|
209
|
+
if isinstance(seed_or_noise, Tensor):
|
|
210
|
+
noise = seed_or_noise
|
|
211
|
+
else:
|
|
212
|
+
noise = with_seed(seed_or_noise)(self.create_noise_)(param.shape, dtype = param.dtype)
|
|
213
|
+
|
|
214
|
+
# maybe overriding noise scale per param
|
|
215
|
+
|
|
216
|
+
if self.overridable_noise_scale:
|
|
217
|
+
param_noise_scale = noise_scale_with_seed
|
|
218
|
+
else:
|
|
219
|
+
param_noise_scale = param_noise_scale * noise_scale_with_seed
|
|
220
|
+
|
|
221
|
+
elif isinstance(noise_or_seed, Tensor):
|
|
222
|
+
noise = noise_or_seed
|
|
223
|
+
else:
|
|
224
|
+
raise ValueError('invalid type, noise must be float tensor or int')
|
|
225
|
+
|
|
226
|
+
# maybe scale noise by tensor
|
|
227
|
+
|
|
228
|
+
maybe_noise_scale = noise_scale_for_params.get(name, None)
|
|
229
|
+
|
|
230
|
+
if exists(maybe_noise_scale):
|
|
231
|
+
param_noise_scale = param_noise_scale * maybe_noise_scale
|
|
232
|
+
|
|
233
|
+
if negate:
|
|
234
|
+
param_noise_scale = -param_noise_scale
|
|
235
|
+
|
|
236
|
+
noise = noise.to(self.device)
|
|
237
|
+
|
|
238
|
+
self._add_scaled_noise_(name, param, noise, param_noise_scale, inplace, add_to_grad, return_params)
|
|
239
|
+
|
|
240
|
+
return return_params
|
|
241
|
+
|
|
242
|
+
def forward(
|
|
243
|
+
self,
|
|
244
|
+
*args,
|
|
245
|
+
noise_for_params = None,
|
|
246
|
+
noise_scale_for_params = None,
|
|
247
|
+
noise_scale = None,
|
|
248
|
+
**kwargs
|
|
249
|
+
):
|
|
250
|
+
if not exists(noise_for_params) or is_empty(noise_for_params):
|
|
251
|
+
return self.model(*args, **kwargs)
|
|
252
|
+
|
|
253
|
+
noised_params = self.get_noised_params(noise_for_params, noise_scale_for_params = noise_scale_for_params, noise_scale = noise_scale)
|
|
254
|
+
|
|
255
|
+
return functional_call(self.model, noised_params, args, kwargs)
|
|
@@ -1,34 +1,26 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
|
-
from typing import Literal, Any
|
|
3
|
-
from collections.abc import Callable
|
|
4
2
|
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from functools import partial
|
|
5
5
|
from math import ceil
|
|
6
6
|
from pathlib import Path
|
|
7
|
-
from
|
|
7
|
+
from typing import Any, Literal
|
|
8
8
|
|
|
9
9
|
import torch
|
|
10
|
-
from torch import tensor, Tensor, stack, arange, randint
|
|
11
|
-
from torch.nn import Module, ModuleList, Parameter, ParameterList
|
|
12
|
-
from torch.optim import SGD, Optimizer
|
|
13
|
-
from torch.optim.lr_scheduler import LRScheduler
|
|
14
|
-
|
|
15
10
|
import torch.distributed as dist
|
|
16
11
|
import torch.nn.functional as F
|
|
17
|
-
|
|
18
|
-
from tqdm import tqdm
|
|
19
|
-
|
|
12
|
+
from accelerate import Accelerator
|
|
20
13
|
from beartype import beartype
|
|
21
14
|
from beartype.door import is_bearable
|
|
22
|
-
|
|
23
|
-
from accelerate import Accelerator
|
|
24
|
-
|
|
25
|
-
from x_mlps_pytorch.noisable import (
|
|
26
|
-
Noisable,
|
|
27
|
-
with_seed
|
|
28
|
-
)
|
|
29
|
-
|
|
30
15
|
from einops import pack
|
|
16
|
+
from torch import Tensor, arange, randint, stack, tensor
|
|
17
|
+
from torch.nn import Module, ModuleList, Parameter, ParameterList
|
|
18
|
+
from torch.optim import SGD, Optimizer
|
|
19
|
+
from torch.optim.lr_scheduler import LRScheduler
|
|
31
20
|
from torch_einops_utils import pack_with_inverse
|
|
21
|
+
from tqdm import tqdm
|
|
22
|
+
|
|
23
|
+
from x_evolution.noisable import Noisable, with_seed
|
|
32
24
|
|
|
33
25
|
# constants
|
|
34
26
|
|
|
@@ -152,11 +144,20 @@ class EvolutionStrategy(Module):
|
|
|
152
144
|
|
|
153
145
|
def checkpoint(self, filename = 'evolved.model'):
|
|
154
146
|
if self.accelerate.is_main_process:
|
|
147
|
+
self.checkpoint_folder.mkdir(parents = True, exist_ok = True)
|
|
155
148
|
filepath = self.checkpoint_folder / f'{filename}.pt'
|
|
156
149
|
torch.save(self.model.state_dict(), str(filepath))
|
|
157
150
|
|
|
158
151
|
self.wait_for_everyone()
|
|
159
152
|
|
|
153
|
+
@torch.no_grad()
|
|
154
|
+
def snapshot_model_(self):
|
|
155
|
+
return {name: value.detach().clone() for name, value in self.model.state_dict().items()}
|
|
156
|
+
|
|
157
|
+
@torch.no_grad()
|
|
158
|
+
def restore_model_(self, state):
|
|
159
|
+
self.model.load_state_dict(state)
|
|
160
|
+
|
|
160
161
|
# class
|
|
161
162
|
|
|
162
163
|
class EvoStrategy(EvolutionStrategy):
|
|
@@ -173,13 +174,15 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
173
174
|
mirror_sampling = True,
|
|
174
175
|
params_to_optimize: dict[str, ParametersToOptimize] | ParametersToOptimize | None = None,
|
|
175
176
|
noise_low_rank: int | None = None,
|
|
177
|
+
noise_dtype: torch.dtype | None = None, # float16 / bfloat16 / int8 - int8 stochastically rounds the noise
|
|
176
178
|
rollout_fixed_seed = True,
|
|
177
179
|
noise_scale = 1e-2, # the noise scaling during rollouts with environment, todo - figure out right value and make sure it can also be customized per parameter name through a dict
|
|
178
180
|
learned_noise_scale = False,
|
|
179
181
|
noise_scale_learning_rate = 1e-5,
|
|
180
182
|
noise_scale_clamp_range: tuple[float, float] = (1e-3, 1e-1),
|
|
181
183
|
use_optimizer = True,
|
|
182
|
-
|
|
184
|
+
anchored_weight_decay_rate = 0., # Anchored Weight Decay (AWD) - pulls parameters toward their init snapshot
|
|
185
|
+
optimizer_klass: type[Optimizer] | Callable | None = None,
|
|
183
186
|
optimizer_kwargs: dict = dict(),
|
|
184
187
|
use_sigma_optimizer = True,
|
|
185
188
|
sigma_optimizer_klass: type[Optimizer] | Callable = partial(SGD, nesterov = True, momentum = 0.1),
|
|
@@ -237,7 +240,7 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
237
240
|
model = ModuleList(model)
|
|
238
241
|
|
|
239
242
|
self.model = model
|
|
240
|
-
self.noisable_model = Noisable(model, low_rank = noise_low_rank)
|
|
243
|
+
self.noisable_model = Noisable(model, low_rank = noise_low_rank, noise_dtype = noise_dtype)
|
|
241
244
|
|
|
242
245
|
# maybe sync model params and buffers
|
|
243
246
|
|
|
@@ -341,12 +344,33 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
341
344
|
|
|
342
345
|
self.rollout_fixed_seed = rollout_fixed_seed
|
|
343
346
|
|
|
347
|
+
# anchored weight decay (AWD, Schweighofer et al. 2026)
|
|
348
|
+
|
|
349
|
+
assert anchored_weight_decay_rate >= 0.
|
|
350
|
+
|
|
351
|
+
self.anchored_weight_decay_rate = anchored_weight_decay_rate
|
|
352
|
+
|
|
353
|
+
self.anchor_params = None
|
|
354
|
+
|
|
355
|
+
if anchored_weight_decay_rate > 0.:
|
|
356
|
+
self.anchor_params = {
|
|
357
|
+
name: named_parameters_dict[name].detach().clone()
|
|
358
|
+
for name in self.param_names_to_optimize
|
|
359
|
+
}
|
|
360
|
+
|
|
344
361
|
# maybe use optimizer to update, allow for Adam
|
|
345
362
|
|
|
346
363
|
self.use_optimizer = use_optimizer
|
|
364
|
+
self.optimizer = None
|
|
365
|
+
|
|
366
|
+
if not exists(optimizer_klass):
|
|
367
|
+
# AWD replaces weight decay toward zero, which erodes the checkpoint
|
|
368
|
+
|
|
369
|
+
weight_decay = 0. if anchored_weight_decay_rate > 0. else 1e-2
|
|
370
|
+
optimizer_klass = partial(SGD, nesterov = True, momentum = 0.1, weight_decay = weight_decay)
|
|
347
371
|
|
|
348
372
|
if use_optimizer:
|
|
349
|
-
optim_params = [named_parameters_dict[name] for name in
|
|
373
|
+
optim_params = [named_parameters_dict[name] for name in self.param_names_to_optimize]
|
|
350
374
|
self.optimizer = optimizer_klass(optim_params, lr = learning_rate, **optimizer_kwargs)
|
|
351
375
|
|
|
352
376
|
self.use_sigma_optimizer = use_sigma_optimizer
|
|
@@ -382,6 +406,54 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
382
406
|
sigma_index = self.param_name_to_sigma_index[param_name]
|
|
383
407
|
return self.sigmas[sigma_index]
|
|
384
408
|
|
|
409
|
+
@torch.no_grad()
|
|
410
|
+
def anchored_weight_decay_(self, param_names):
|
|
411
|
+
if not exists(self.anchor_params) or self.anchored_weight_decay_rate <= 0.:
|
|
412
|
+
return
|
|
413
|
+
|
|
414
|
+
named_params = dict(self.model.named_parameters())
|
|
415
|
+
lr = self.optimizer.param_groups[0]['lr'] if exists(self.optimizer) else self.learning_rate
|
|
416
|
+
decay_rate = lr * self.anchored_weight_decay_rate
|
|
417
|
+
|
|
418
|
+
for name in param_names:
|
|
419
|
+
param = named_params[name]
|
|
420
|
+
anchor = self.anchor_params.get(name)
|
|
421
|
+
|
|
422
|
+
if not exists(anchor):
|
|
423
|
+
self.anchor_params[name] = param.detach().clone()
|
|
424
|
+
continue
|
|
425
|
+
|
|
426
|
+
if anchor.device != param.device:
|
|
427
|
+
anchor = anchor.to(param.device)
|
|
428
|
+
self.anchor_params[name] = anchor
|
|
429
|
+
|
|
430
|
+
param.lerp_(anchor, decay_rate)
|
|
431
|
+
|
|
432
|
+
@torch.no_grad()
|
|
433
|
+
def set_init_anchor_(self, model_or_state = None):
|
|
434
|
+
# anchor to a module, state dict, or the current weights
|
|
435
|
+
|
|
436
|
+
named_params = dict(self.model.named_parameters())
|
|
437
|
+
|
|
438
|
+
if not exists(model_or_state):
|
|
439
|
+
state = named_params
|
|
440
|
+
elif isinstance(model_or_state, Module):
|
|
441
|
+
state = model_or_state.state_dict()
|
|
442
|
+
else:
|
|
443
|
+
state = model_or_state
|
|
444
|
+
|
|
445
|
+
names = self.param_names_to_optimize if not exists(self.anchor_params) else self.anchor_params
|
|
446
|
+
|
|
447
|
+
self.anchor_params = {
|
|
448
|
+
name: state[name].detach().clone().to(named_params[name].device)
|
|
449
|
+
for name in names
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
def reanchor_(self):
|
|
453
|
+
# adopt current weights as anchor after interleaving with policy gradient training
|
|
454
|
+
|
|
455
|
+
self.set_init_anchor_()
|
|
456
|
+
|
|
385
457
|
@torch.inference_mode()
|
|
386
458
|
def evolve_(
|
|
387
459
|
self,
|
|
@@ -418,6 +490,15 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
418
490
|
|
|
419
491
|
weights /= self.noise_population_size * (2. if self.mirror_sampling else 1.)
|
|
420
492
|
|
|
493
|
+
# anchored weight decay, before the optimizer / weight update
|
|
494
|
+
|
|
495
|
+
active_names = self.param_names_to_optimize
|
|
496
|
+
|
|
497
|
+
if exists(scoped_names):
|
|
498
|
+
active_names = [name for name in active_names if name in scoped_names]
|
|
499
|
+
|
|
500
|
+
self.anchored_weight_decay_(active_names)
|
|
501
|
+
|
|
421
502
|
# update one seed at a time for enabling evolutionary strategy for large models
|
|
422
503
|
|
|
423
504
|
for individual_seed, weight in zip(seeds_for_population.tolist(), weights.tolist()):
|
|
@@ -442,7 +523,7 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
442
523
|
|
|
443
524
|
# reproduce the noise from the seed
|
|
444
525
|
|
|
445
|
-
noise = with_seed(seed)(model.
|
|
526
|
+
noise = with_seed(seed)(model.create_noise_)(shape, dtype = dtype)
|
|
446
527
|
noise = noise.to(self.device)
|
|
447
528
|
|
|
448
529
|
# scale the weight
|
|
@@ -461,7 +542,7 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
461
542
|
# maybe learned sigma
|
|
462
543
|
|
|
463
544
|
if self.learned_noise_scale:
|
|
464
|
-
one_grad_sigma = weight * (noise ** 2 - 1) / noise_scale
|
|
545
|
+
one_grad_sigma = weight * (noise.float() ** 2 - 1) / noise_scale
|
|
465
546
|
|
|
466
547
|
sigma_index = self.param_name_to_sigma_index[param_name]
|
|
467
548
|
sigma = self.sigmas[sigma_index]
|
|
@@ -524,8 +605,7 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
524
605
|
|
|
525
606
|
# maybe save model for rolling back (for meta-evo)
|
|
526
607
|
|
|
527
|
-
if rollback_model_at_end
|
|
528
|
-
self.checkpoint('initial.model')
|
|
608
|
+
original_state = self.snapshot_model_() if rollback_model_at_end else None
|
|
529
609
|
|
|
530
610
|
# maybe sigmas
|
|
531
611
|
|
|
@@ -600,7 +680,7 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
600
680
|
fitnesses.append(None)
|
|
601
681
|
continue
|
|
602
682
|
|
|
603
|
-
def get_fitness(negate = False):
|
|
683
|
+
def get_fitness(negate = False, individual_seed = individual_seed, maybe_rollout_seed = maybe_rollout_seed):
|
|
604
684
|
nonlocal rewards_by_scope
|
|
605
685
|
|
|
606
686
|
individual_param_seeds = with_seed(individual_seed.item())(randint)(0, MAX_SEED_VALUE, (self.num_params,))
|
|
@@ -750,10 +830,8 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
750
830
|
|
|
751
831
|
# maybe rollback
|
|
752
832
|
|
|
753
|
-
if
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
self.model.load_state_dict(orig_state_dict)
|
|
833
|
+
if exists(original_state):
|
|
834
|
+
self.restore_model_(original_state)
|
|
757
835
|
|
|
758
836
|
# return fitnesses across generations
|
|
759
837
|
# for meta-evolutionary (nesting EvoStrategy within the environment of another and optimizing some meta-network)
|
|
File without changes
|
|
File without changes
|