x-evolution 0.2.2__tar.gz → 0.2.4__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.2 → x_evolution-0.2.4}/PKG-INFO +47 -1
- {x_evolution-0.2.2 → x_evolution-0.2.4}/README.md +46 -0
- {x_evolution-0.2.2 → x_evolution-0.2.4}/pyproject.toml +1 -1
- {x_evolution-0.2.2 → x_evolution-0.2.4}/tests/test_evolution.py +127 -0
- {x_evolution-0.2.2 → x_evolution-0.2.4}/x_evolution/cma_es.py +109 -24
- {x_evolution-0.2.2 → x_evolution-0.2.4}/x_evolution/x_evolution.py +81 -2
- {x_evolution-0.2.2 → x_evolution-0.2.4}/.gitignore +0 -0
- {x_evolution-0.2.2 → x_evolution-0.2.4}/LICENSE +0 -0
- {x_evolution-0.2.2 → x_evolution-0.2.4}/x_evolution/__init__.py +0 -0
- {x_evolution-0.2.2 → x_evolution-0.2.4}/x_evolution/noisable.py +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.4
|
|
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
|
|
@@ -102,6 +102,31 @@ evo_strat()
|
|
|
102
102
|
# can also specify checkpoint_every at init and select the one with your favored fitness score for continued policy gradient learning etc
|
|
103
103
|
```
|
|
104
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
|
+
|
|
105
130
|
## CMA-ES
|
|
106
131
|
|
|
107
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`:
|
|
@@ -282,6 +307,27 @@ Special thanks to [Pollen Robotics 🤗](https://www.pollen-robotics.com/) for t
|
|
|
282
307
|
}
|
|
283
308
|
```
|
|
284
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
|
+
|
|
285
331
|
```bibtex
|
|
286
332
|
@inproceedings{anonymous2026continual,
|
|
287
333
|
title = {Continual Reinforcement Learning with Neuroevolution},
|
|
@@ -46,6 +46,31 @@ evo_strat()
|
|
|
46
46
|
# can also specify checkpoint_every at init and select the one with your favored fitness score for continued policy gradient learning etc
|
|
47
47
|
```
|
|
48
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
|
+
|
|
49
74
|
## CMA-ES
|
|
50
75
|
|
|
51
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`:
|
|
@@ -226,6 +251,27 @@ Special thanks to [Pollen Robotics 🤗](https://www.pollen-robotics.com/) for t
|
|
|
226
251
|
}
|
|
227
252
|
```
|
|
228
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
|
+
|
|
229
275
|
```bibtex
|
|
230
276
|
@inproceedings{anonymous2026continual,
|
|
231
277
|
title = {Continual Reinforcement Learning with Neuroevolution},
|
|
@@ -809,3 +809,130 @@ def test_cma_scopes():
|
|
|
809
809
|
|
|
810
810
|
fitnesses = cma(num_generations = 1)
|
|
811
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.1, '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))
|
|
@@ -9,13 +9,13 @@ from typing import Any
|
|
|
9
9
|
import torch
|
|
10
10
|
from accelerate import Accelerator
|
|
11
11
|
from beartype import beartype
|
|
12
|
+
from einops import einsum, rearrange
|
|
12
13
|
from torch import Tensor, arange, randint, tensor
|
|
13
14
|
from torch.nn import Module, ModuleList
|
|
14
15
|
from torch_einops_utils import (
|
|
15
16
|
batched_index_select,
|
|
16
17
|
cast_item,
|
|
17
18
|
dict_add,
|
|
18
|
-
safe_cat,
|
|
19
19
|
safe_stack,
|
|
20
20
|
tree_map_tensor_to_device,
|
|
21
21
|
)
|
|
@@ -50,7 +50,8 @@ class _CMAState:
|
|
|
50
50
|
population_size,
|
|
51
51
|
noise_scale,
|
|
52
52
|
noise_dtype,
|
|
53
|
-
sigma_clamp_range
|
|
53
|
+
sigma_clamp_range,
|
|
54
|
+
anchored_weight_decay_rate = 0.
|
|
54
55
|
):
|
|
55
56
|
self.strategy = strategy
|
|
56
57
|
self.param_names = sorted(param_names)
|
|
@@ -61,6 +62,7 @@ class _CMAState:
|
|
|
61
62
|
self.sep_cma = sep_cma
|
|
62
63
|
self.noise_dtype = noise_dtype
|
|
63
64
|
self.sigma_clamp_range = sigma_clamp_range
|
|
65
|
+
self.anchored_weight_decay_rate = anchored_weight_decay_rate
|
|
64
66
|
|
|
65
67
|
self.dim = 0
|
|
66
68
|
self.param_slices = dict()
|
|
@@ -78,8 +80,18 @@ class _CMAState:
|
|
|
78
80
|
for name in self.param_names
|
|
79
81
|
}
|
|
80
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
|
+
|
|
81
91
|
self.mean = torch.zeros(self.dim, device = device)
|
|
82
92
|
self.C = torch.ones(self.dim, device = device) if sep_cma else torch.eye(self.dim, device = device)
|
|
93
|
+
self.B = None if sep_cma else torch.eye(self.dim, device = device)
|
|
94
|
+
self.D = None if sep_cma else torch.ones(self.dim, device = device)
|
|
83
95
|
self.pc = torch.zeros(self.dim, device = device)
|
|
84
96
|
self.ps = torch.zeros(self.dim, device = device)
|
|
85
97
|
|
|
@@ -115,6 +127,9 @@ class _CMAState:
|
|
|
115
127
|
self.sigma = sqrt(noise_scale) if exists(lora_rank) else noise_scale
|
|
116
128
|
|
|
117
129
|
self.generation = 0
|
|
130
|
+
self._eigen_generation = 0
|
|
131
|
+
c_cov = self.c_1 + self.c_mu
|
|
132
|
+
self.eigen_interval = max(1, int(1. / (10. * dim * c_cov))) if (not sep_cma and c_cov > 0.) else 1
|
|
118
133
|
self._update = None
|
|
119
134
|
|
|
120
135
|
@property
|
|
@@ -135,11 +150,24 @@ class _CMAState:
|
|
|
135
150
|
|
|
136
151
|
def to_device_(self):
|
|
137
152
|
state = dict(mean = self.mean, C = self.C, pc = self.pc, ps = self.ps, weights = self.weights)
|
|
153
|
+
|
|
154
|
+
if not self.sep_cma:
|
|
155
|
+
state['B'] = self.B
|
|
156
|
+
state['D'] = self.D
|
|
157
|
+
|
|
138
158
|
state = tree_map_tensor_to_device(state, self.strategy.cma_device)
|
|
139
159
|
|
|
140
160
|
for name, value in state.items():
|
|
141
161
|
setattr(self, name, value)
|
|
142
162
|
|
|
163
|
+
@torch.no_grad()
|
|
164
|
+
def _update_eigensystem_(self):
|
|
165
|
+
C = 0.5 * (self.C + self.C.T)
|
|
166
|
+
eigenvalues, eigenvectors = torch.linalg.eigh(C)
|
|
167
|
+
self.D.copy_(eigenvalues.clamp(min = 1e-14).sqrt())
|
|
168
|
+
self.B.copy_(eigenvectors)
|
|
169
|
+
self._eigen_generation = self.generation
|
|
170
|
+
|
|
143
171
|
@torch.no_grad()
|
|
144
172
|
def decode_(self, vec):
|
|
145
173
|
deltas = dict()
|
|
@@ -151,11 +179,11 @@ class _CMAState:
|
|
|
151
179
|
|
|
152
180
|
if exists(self.lora_rank):
|
|
153
181
|
r = self.lora_rank
|
|
154
|
-
b = param_vec[:m * r]
|
|
155
|
-
a = param_vec[m * r:]
|
|
156
|
-
delta = (b
|
|
182
|
+
b = rearrange(param_vec[:m * r], '(m r) -> m r', m = m, r = r)
|
|
183
|
+
a = rearrange(param_vec[m * r:], '(r n) -> r n', r = r, n = n)
|
|
184
|
+
delta = einsum(b, a, 'm r, r n -> m n') / sqrt(r)
|
|
157
185
|
else:
|
|
158
|
-
delta = param_vec
|
|
186
|
+
delta = rearrange(param_vec, '(m n) -> m n', m = m, n = n)
|
|
159
187
|
|
|
160
188
|
deltas[name] = delta
|
|
161
189
|
|
|
@@ -190,19 +218,16 @@ class _CMAState:
|
|
|
190
218
|
assert (num_samples % 2) == 0
|
|
191
219
|
half = num_samples // 2
|
|
192
220
|
z_half = self.sample_noise_((half, self.dim), generator)
|
|
193
|
-
z =
|
|
221
|
+
z = rearrange([z_half, -z_half], 'two h d -> (h two) d')
|
|
194
222
|
else:
|
|
195
223
|
z = self.sample_noise_((num_samples, self.dim), generator)
|
|
196
224
|
|
|
197
225
|
if self.sep_cma:
|
|
198
226
|
y = z * self.C.sqrt()
|
|
199
227
|
else:
|
|
200
|
-
#
|
|
228
|
+
# C = B diag(D ** 2) B^T, cached and refreshed every eigen_interval generations
|
|
201
229
|
|
|
202
|
-
|
|
203
|
-
eigenvalues, eigenvectors = torch.linalg.eigh(C)
|
|
204
|
-
eigenvalues = eigenvalues.clamp(min = 1e-14)
|
|
205
|
-
y = (z * eigenvalues.sqrt()) @ eigenvectors.T
|
|
230
|
+
y = einsum(z * self.D, self.B, 'n k, d k -> n d')
|
|
206
231
|
|
|
207
232
|
x = self.mean + self.sigma * y
|
|
208
233
|
|
|
@@ -222,16 +247,17 @@ class _CMAState:
|
|
|
222
247
|
y_selected = batched_index_select(y, selected, dim = 0)
|
|
223
248
|
z_selected = batched_index_select(z, selected, dim = 0)
|
|
224
249
|
|
|
225
|
-
y_mean = (weights
|
|
226
|
-
z_mean = (weights
|
|
250
|
+
y_mean = einsum(weights, y_selected, 'p, p d -> d')
|
|
251
|
+
z_mean = einsum(weights, z_selected.to(weights.dtype), 'p, p k -> k')
|
|
227
252
|
|
|
228
253
|
# mean shift in factor space
|
|
229
254
|
|
|
230
255
|
new_mean = self.mean + self.sigma * y_mean
|
|
231
256
|
|
|
232
|
-
# sigma path
|
|
257
|
+
# sigma path: C^{-1/2} y_w = B z_w (coordinate space, invariant to eigenvector sign flips)
|
|
233
258
|
|
|
234
|
-
|
|
259
|
+
z_step = z_mean if self.sep_cma else einsum(self.B, z_mean, 'd k, k -> d')
|
|
260
|
+
ps = (1. - self.c_sigma) * self.ps + sqrt(self.c_sigma * (2. - self.c_sigma) * self.mu_eff) * z_step
|
|
235
261
|
ps_norm = cast_item(ps.norm())
|
|
236
262
|
|
|
237
263
|
self.ps.copy_(ps)
|
|
@@ -248,18 +274,21 @@ class _CMAState:
|
|
|
248
274
|
self.pc.copy_(pc)
|
|
249
275
|
|
|
250
276
|
if self.sep_cma:
|
|
277
|
+
rank_mu = einsum(weights, y_selected.square(), 'p, p d -> d')
|
|
278
|
+
|
|
251
279
|
C = (
|
|
252
280
|
(1. - self.c_1 - self.c_mu) * self.C
|
|
253
281
|
+ self.c_1 * (pc.square() + (1. - h_sigma) * self.c_c * (2. - self.c_c) * self.C)
|
|
254
|
-
+ self.c_mu *
|
|
282
|
+
+ self.c_mu * rank_mu
|
|
255
283
|
)
|
|
256
|
-
self.C.copy_(C)
|
|
284
|
+
self.C.copy_(C.clamp(min = 1e-14))
|
|
257
285
|
else:
|
|
258
|
-
|
|
286
|
+
rank_one = einsum(pc, pc, 'i, j -> i j')
|
|
287
|
+
rank_mu = einsum(weights, y_selected, y_selected, 'p, p i, p j -> i j')
|
|
259
288
|
|
|
260
289
|
C = (
|
|
261
290
|
(1. - self.c_1 - self.c_mu) * self.C
|
|
262
|
-
+ self.c_1 * (
|
|
291
|
+
+ self.c_1 * (rank_one + (1. - h_sigma) * self.c_c * (2. - self.c_c) * self.C)
|
|
263
292
|
+ self.c_mu * rank_mu
|
|
264
293
|
)
|
|
265
294
|
self.C.copy_(0.5 * (C + C.T))
|
|
@@ -282,13 +311,27 @@ class _CMAState:
|
|
|
282
311
|
|
|
283
312
|
self.generation = generation
|
|
284
313
|
|
|
314
|
+
if not self.sep_cma and (self.generation - self._eigen_generation) >= self.eigen_interval:
|
|
315
|
+
self._update_eigensystem_()
|
|
316
|
+
|
|
317
|
+
@torch.no_grad()
|
|
318
|
+
def add_to_base_(self, name, delta):
|
|
319
|
+
base = self.base_params[name]
|
|
320
|
+
|
|
321
|
+
# AWD toward the init snapshot (Schweighofer et al. 2026)
|
|
322
|
+
|
|
323
|
+
if self.anchored_weight_decay_rate > 0.:
|
|
324
|
+
base.lerp_(self.anchor_params[name].to(base.device), self.anchored_weight_decay_rate)
|
|
325
|
+
|
|
326
|
+
base.add_(delta.to(base.device))
|
|
327
|
+
|
|
285
328
|
@torch.no_grad()
|
|
286
329
|
def commit_(self):
|
|
287
330
|
if not exists(self._update):
|
|
288
331
|
return
|
|
289
332
|
|
|
290
333
|
for name, delta in self._update.items():
|
|
291
|
-
self.
|
|
334
|
+
self.add_to_base_(name, delta)
|
|
292
335
|
|
|
293
336
|
self._update = None
|
|
294
337
|
self.mean.zero_()
|
|
@@ -299,12 +342,36 @@ class _CMAState:
|
|
|
299
342
|
deltas = self.decode_(self.mean)
|
|
300
343
|
|
|
301
344
|
for name, delta in deltas.items():
|
|
302
|
-
|
|
303
|
-
base.add_(delta.to(base.device))
|
|
345
|
+
self.add_to_base_(name, delta)
|
|
304
346
|
|
|
305
347
|
self.mean.zero_()
|
|
306
348
|
self.set_model_to_(self.mean)
|
|
307
349
|
|
|
350
|
+
@torch.no_grad()
|
|
351
|
+
def set_init_anchor_(self, model_or_state = None):
|
|
352
|
+
# anchor to a module, state dict, or the current weights
|
|
353
|
+
|
|
354
|
+
if not exists(model_or_state):
|
|
355
|
+
state = self.strategy._named_parameters
|
|
356
|
+
elif isinstance(model_or_state, Module):
|
|
357
|
+
state = model_or_state.state_dict()
|
|
358
|
+
else:
|
|
359
|
+
state = model_or_state
|
|
360
|
+
|
|
361
|
+
self.anchor_params = {
|
|
362
|
+
name: state[name].detach().clone().to(self.base_params[name].device)
|
|
363
|
+
for name in self.param_names
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
@torch.no_grad()
|
|
367
|
+
def reanchor_(self):
|
|
368
|
+
self.set_init_anchor_()
|
|
369
|
+
|
|
370
|
+
for name in self.param_names:
|
|
371
|
+
self.base_params[name] = self.anchor_params[name].clone()
|
|
372
|
+
|
|
373
|
+
self.mean.zero_()
|
|
374
|
+
|
|
308
375
|
class CMAEvoStrategy(EvolutionStrategy):
|
|
309
376
|
|
|
310
377
|
@beartype
|
|
@@ -320,6 +387,7 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
320
387
|
lora_rank: int | None = 1,
|
|
321
388
|
freeze_base = True,
|
|
322
389
|
merge_every: int | None = None, # fold mean into base every n generations
|
|
390
|
+
anchored_weight_decay_rate = 0., # Anchored Weight Decay (AWD) - pulls the base toward its init snapshot
|
|
323
391
|
mirror_sampling = True,
|
|
324
392
|
sep_cma = False, # diagonal covariance: O(dim) memory, no eigendecomposition
|
|
325
393
|
params_to_optimize: dict[str, ParametersToOptimize] | ParametersToOptimize | None = None,
|
|
@@ -444,6 +512,9 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
444
512
|
assert freeze_base, 'merge_every requires freeze_base=True'
|
|
445
513
|
assert merge_every >= 1, 'merge_every must be >= 1'
|
|
446
514
|
|
|
515
|
+
if anchored_weight_decay_rate > 0.:
|
|
516
|
+
assert not freeze_base or exists(merge_every), 'AWD requires base updates: set freeze_base=False or merge_every'
|
|
517
|
+
|
|
447
518
|
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'
|
|
448
519
|
|
|
449
520
|
self._mirror_sampling = mirror_sampling
|
|
@@ -452,6 +523,9 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
452
523
|
self.cma_device = torch.device(cma_device)
|
|
453
524
|
|
|
454
525
|
assert 0. < sigma_clamp_range[0] < sigma_clamp_range[1]
|
|
526
|
+
assert anchored_weight_decay_rate >= 0.
|
|
527
|
+
|
|
528
|
+
self.anchored_weight_decay_rate = anchored_weight_decay_rate
|
|
455
529
|
|
|
456
530
|
# states are created lazily per parameter subset / scope
|
|
457
531
|
|
|
@@ -527,11 +601,22 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
527
601
|
population_size = self.population_size,
|
|
528
602
|
noise_scale = self.noise_scale,
|
|
529
603
|
noise_dtype = self.noise_dtype,
|
|
530
|
-
sigma_clamp_range = self.sigma_clamp_range
|
|
604
|
+
sigma_clamp_range = self.sigma_clamp_range,
|
|
605
|
+
anchored_weight_decay_rate = self.anchored_weight_decay_rate
|
|
531
606
|
)
|
|
532
607
|
|
|
533
608
|
return self._states[names]
|
|
534
609
|
|
|
610
|
+
@torch.no_grad()
|
|
611
|
+
def set_init_anchor_(self, model_or_state = None):
|
|
612
|
+
for state in self._states.values():
|
|
613
|
+
state.set_init_anchor_(model_or_state)
|
|
614
|
+
|
|
615
|
+
@torch.no_grad()
|
|
616
|
+
def reanchor_(self):
|
|
617
|
+
for state in self._states.values():
|
|
618
|
+
state.reanchor_()
|
|
619
|
+
|
|
535
620
|
def to_cma_device_(self):
|
|
536
621
|
for state in self._states.values():
|
|
537
622
|
state.to_device_()
|
|
@@ -181,7 +181,8 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
181
181
|
noise_scale_learning_rate = 1e-5,
|
|
182
182
|
noise_scale_clamp_range: tuple[float, float] = (1e-3, 1e-1),
|
|
183
183
|
use_optimizer = True,
|
|
184
|
-
|
|
184
|
+
anchored_weight_decay_rate = 0., # Anchored Weight Decay (AWD) - pulls parameters toward their init snapshot
|
|
185
|
+
optimizer_klass: type[Optimizer] | Callable | None = None,
|
|
185
186
|
optimizer_kwargs: dict = dict(),
|
|
186
187
|
use_sigma_optimizer = True,
|
|
187
188
|
sigma_optimizer_klass: type[Optimizer] | Callable = partial(SGD, nesterov = True, momentum = 0.1),
|
|
@@ -343,12 +344,33 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
343
344
|
|
|
344
345
|
self.rollout_fixed_seed = rollout_fixed_seed
|
|
345
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
|
+
|
|
346
361
|
# maybe use optimizer to update, allow for Adam
|
|
347
362
|
|
|
348
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)
|
|
349
371
|
|
|
350
372
|
if use_optimizer:
|
|
351
|
-
optim_params = [named_parameters_dict[name] for name in
|
|
373
|
+
optim_params = [named_parameters_dict[name] for name in self.param_names_to_optimize]
|
|
352
374
|
self.optimizer = optimizer_klass(optim_params, lr = learning_rate, **optimizer_kwargs)
|
|
353
375
|
|
|
354
376
|
self.use_sigma_optimizer = use_sigma_optimizer
|
|
@@ -384,6 +406,54 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
384
406
|
sigma_index = self.param_name_to_sigma_index[param_name]
|
|
385
407
|
return self.sigmas[sigma_index]
|
|
386
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
|
+
|
|
387
457
|
@torch.inference_mode()
|
|
388
458
|
def evolve_(
|
|
389
459
|
self,
|
|
@@ -420,6 +490,15 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
420
490
|
|
|
421
491
|
weights /= self.noise_population_size * (2. if self.mirror_sampling else 1.)
|
|
422
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
|
+
|
|
423
502
|
# update one seed at a time for enabling evolutionary strategy for large models
|
|
424
503
|
|
|
425
504
|
for individual_seed, weight in zip(seeds_for_population.tolist(), weights.tolist()):
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|