x-evolution 0.2.0__tar.gz → 0.2.2__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.0 → x_evolution-0.2.2}/PKG-INFO +27 -3
- {x_evolution-0.2.0 → x_evolution-0.2.2}/README.md +26 -2
- {x_evolution-0.2.0 → x_evolution-0.2.2}/pyproject.toml +1 -1
- {x_evolution-0.2.0 → x_evolution-0.2.2}/tests/test_evolution.py +169 -0
- {x_evolution-0.2.0 → x_evolution-0.2.2}/x_evolution/__init__.py +3 -1
- {x_evolution-0.2.0 → x_evolution-0.2.2}/x_evolution/cma_es.py +33 -26
- x_evolution-0.2.2/x_evolution/noisable.py +255 -0
- {x_evolution-0.2.0 → x_evolution-0.2.2}/x_evolution/x_evolution.py +28 -29
- {x_evolution-0.2.0 → x_evolution-0.2.2}/.gitignore +0 -0
- {x_evolution-0.2.0 → x_evolution-0.2.2}/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.2
|
|
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
|
|
@@ -114,7 +115,8 @@ cma = CMAEvoStrategy(
|
|
|
114
115
|
num_generations = 100,
|
|
115
116
|
lora_rank = 1, # None for the full weight update
|
|
116
117
|
freeze_base = True, # False recenters the base every generation
|
|
117
|
-
noise_scale = 1e-2
|
|
118
|
+
noise_scale = 1e-2, # std of the induced weight delta
|
|
119
|
+
noise_dtype = None # torch.float16 / torch.bfloat16 / torch.int8 for quantized noise - https://arxiv.org/abs/2602.03120
|
|
118
120
|
)
|
|
119
121
|
|
|
120
122
|
cma()
|
|
@@ -178,6 +180,17 @@ Special thanks to [Pollen Robotics 🤗](https://www.pollen-robotics.com/) for t
|
|
|
178
180
|
|
|
179
181
|
## Citations
|
|
180
182
|
|
|
183
|
+
```bibtex
|
|
184
|
+
@article{xu2026quantized,
|
|
185
|
+
title = {Quantized Evolution Strategies: High-precision Fine-tuning of Quantized LLMs at Low-precision Cost},
|
|
186
|
+
author = {Yinggan Xu and Kajetan Schweighofer and Risto Miikkulainen and Xin Qiu},
|
|
187
|
+
journal = {ArXiv},
|
|
188
|
+
year = {2026},
|
|
189
|
+
volume = {abs/2602.03120},
|
|
190
|
+
url = {https://arxiv.org/abs/2602.03120}
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
181
194
|
```bibtex
|
|
182
195
|
@article{Qiu2025EvolutionSA,
|
|
183
196
|
title = {Evolution Strategies at Scale: LLM Fine-Tuning Beyond Reinforcement Learning},
|
|
@@ -269,4 +282,15 @@ Special thanks to [Pollen Robotics 🤗](https://www.pollen-robotics.com/) for t
|
|
|
269
282
|
}
|
|
270
283
|
```
|
|
271
284
|
|
|
285
|
+
```bibtex
|
|
286
|
+
@inproceedings{anonymous2026continual,
|
|
287
|
+
title = {Continual Reinforcement Learning with Neuroevolution},
|
|
288
|
+
author = {Anonymous},
|
|
289
|
+
booktitle = {Submitted to The Fifteenth International Conference on Learning Representations},
|
|
290
|
+
year = {2026},
|
|
291
|
+
url = {https://openreview.net/forum?id=UxsGk4on0e},
|
|
292
|
+
note = {under review}
|
|
293
|
+
}
|
|
294
|
+
```
|
|
295
|
+
|
|
272
296
|
*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
|
|
@@ -58,7 +59,8 @@ cma = CMAEvoStrategy(
|
|
|
58
59
|
num_generations = 100,
|
|
59
60
|
lora_rank = 1, # None for the full weight update
|
|
60
61
|
freeze_base = True, # False recenters the base every generation
|
|
61
|
-
noise_scale = 1e-2
|
|
62
|
+
noise_scale = 1e-2, # std of the induced weight delta
|
|
63
|
+
noise_dtype = None # torch.float16 / torch.bfloat16 / torch.int8 for quantized noise - https://arxiv.org/abs/2602.03120
|
|
62
64
|
)
|
|
63
65
|
|
|
64
66
|
cma()
|
|
@@ -122,6 +124,17 @@ Special thanks to [Pollen Robotics 🤗](https://www.pollen-robotics.com/) for t
|
|
|
122
124
|
|
|
123
125
|
## Citations
|
|
124
126
|
|
|
127
|
+
```bibtex
|
|
128
|
+
@article{xu2026quantized,
|
|
129
|
+
title = {Quantized Evolution Strategies: High-precision Fine-tuning of Quantized LLMs at Low-precision Cost},
|
|
130
|
+
author = {Yinggan Xu and Kajetan Schweighofer and Risto Miikkulainen and Xin Qiu},
|
|
131
|
+
journal = {ArXiv},
|
|
132
|
+
year = {2026},
|
|
133
|
+
volume = {abs/2602.03120},
|
|
134
|
+
url = {https://arxiv.org/abs/2602.03120}
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
125
138
|
```bibtex
|
|
126
139
|
@article{Qiu2025EvolutionSA,
|
|
127
140
|
title = {Evolution Strategies at Scale: LLM Fine-Tuning Beyond Reinforcement Learning},
|
|
@@ -213,4 +226,15 @@ Special thanks to [Pollen Robotics 🤗](https://www.pollen-robotics.com/) for t
|
|
|
213
226
|
}
|
|
214
227
|
```
|
|
215
228
|
|
|
229
|
+
```bibtex
|
|
230
|
+
@inproceedings{anonymous2026continual,
|
|
231
|
+
title = {Continual Reinforcement Learning with Neuroevolution},
|
|
232
|
+
author = {Anonymous},
|
|
233
|
+
booktitle = {Submitted to The Fifteenth International Conference on Learning Representations},
|
|
234
|
+
year = {2026},
|
|
235
|
+
url = {https://openreview.net/forum?id=UxsGk4on0e},
|
|
236
|
+
note = {under review}
|
|
237
|
+
}
|
|
238
|
+
```
|
|
239
|
+
|
|
216
240
|
*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
|
|
|
@@ -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,6 +49,7 @@ class _CMAState:
|
|
|
54
49
|
mirror_sampling,
|
|
55
50
|
population_size,
|
|
56
51
|
noise_scale,
|
|
52
|
+
noise_dtype,
|
|
57
53
|
sigma_clamp_range
|
|
58
54
|
):
|
|
59
55
|
self.strategy = strategy
|
|
@@ -63,6 +59,7 @@ class _CMAState:
|
|
|
63
59
|
self.lora_rank = lora_rank
|
|
64
60
|
self.freeze_base = freeze_base
|
|
65
61
|
self.sep_cma = sep_cma
|
|
62
|
+
self.noise_dtype = noise_dtype
|
|
66
63
|
self.sigma_clamp_range = sigma_clamp_range
|
|
67
64
|
|
|
68
65
|
self.dim = 0
|
|
@@ -173,6 +170,18 @@ class _CMAState:
|
|
|
173
170
|
base = self.base_params[name]
|
|
174
171
|
param.data.copy_(base + delta.to(base.device))
|
|
175
172
|
|
|
173
|
+
@torch.no_grad()
|
|
174
|
+
def sample_noise_(self, shape, generator):
|
|
175
|
+
noise_dtype = self.noise_dtype
|
|
176
|
+
|
|
177
|
+
if exists(noise_dtype) and not noise_dtype.is_floating_point:
|
|
178
|
+
noise = torch.randn(shape, generator = generator)
|
|
179
|
+
noise = quantize_noise_(noise, bits = torch.iinfo(noise_dtype).bits, generator = generator)
|
|
180
|
+
else:
|
|
181
|
+
noise = torch.randn(shape, generator = generator, dtype = default(noise_dtype, torch.float32))
|
|
182
|
+
|
|
183
|
+
return noise.to(self.strategy.cma_device)
|
|
184
|
+
|
|
176
185
|
@torch.no_grad()
|
|
177
186
|
def sample_(self, num_samples, generator, mirror_sampling = None):
|
|
178
187
|
mirror_sampling = default(mirror_sampling, self.mirror_sampling)
|
|
@@ -180,10 +189,10 @@ class _CMAState:
|
|
|
180
189
|
if mirror_sampling:
|
|
181
190
|
assert (num_samples % 2) == 0
|
|
182
191
|
half = num_samples // 2
|
|
183
|
-
z_half =
|
|
192
|
+
z_half = self.sample_noise_((half, self.dim), generator)
|
|
184
193
|
z = safe_cat((z_half, -z_half), dim = 0)
|
|
185
194
|
else:
|
|
186
|
-
z =
|
|
195
|
+
z = self.sample_noise_((num_samples, self.dim), generator)
|
|
187
196
|
|
|
188
197
|
if self.sep_cma:
|
|
189
198
|
y = z * self.C.sqrt()
|
|
@@ -307,6 +316,7 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
307
316
|
num_generations,
|
|
308
317
|
population_size: int | None = None,
|
|
309
318
|
noise_scale = 1e-2,
|
|
319
|
+
noise_dtype: torch.dtype | None = None, # float16 / bfloat16 / int8 - int8 stochastically rounds the sampled noise
|
|
310
320
|
lora_rank: int | None = 1,
|
|
311
321
|
freeze_base = True,
|
|
312
322
|
merge_every: int | None = None, # fold mean into base every n generations
|
|
@@ -423,6 +433,8 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
423
433
|
|
|
424
434
|
self.population_size = population_size
|
|
425
435
|
self.noise_scale = noise_scale
|
|
436
|
+
validate_noise_dtype(noise_dtype)
|
|
437
|
+
self.noise_dtype = noise_dtype
|
|
426
438
|
self.lora_rank = lora_rank
|
|
427
439
|
self.freeze_base = freeze_base
|
|
428
440
|
self.merge_every = merge_every
|
|
@@ -514,6 +526,7 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
514
526
|
mirror_sampling = self._mirror_sampling,
|
|
515
527
|
population_size = self.population_size,
|
|
516
528
|
noise_scale = self.noise_scale,
|
|
529
|
+
noise_dtype = self.noise_dtype,
|
|
517
530
|
sigma_clamp_range = self.sigma_clamp_range
|
|
518
531
|
)
|
|
519
532
|
|
|
@@ -679,15 +692,9 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
679
692
|
):
|
|
680
693
|
verbose = default(verbose, self.verbose)
|
|
681
694
|
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
original_state = None
|
|
695
|
+
self.model.to(self.device)
|
|
685
696
|
|
|
686
|
-
if rollback_model_at_end
|
|
687
|
-
original_state = {
|
|
688
|
-
name: value.detach().clone()
|
|
689
|
-
for name, value in model.state_dict().items()
|
|
690
|
-
}
|
|
697
|
+
original_state = self.snapshot_model_() if rollback_model_at_end else None
|
|
691
698
|
|
|
692
699
|
self.to_cma_device_()
|
|
693
700
|
|
|
@@ -727,8 +734,8 @@ class CMAEvoStrategy(EvolutionStrategy):
|
|
|
727
734
|
)
|
|
728
735
|
all_fitnesses.append(fitnesses)
|
|
729
736
|
|
|
730
|
-
if
|
|
731
|
-
self.
|
|
737
|
+
if exists(original_state):
|
|
738
|
+
self.restore_model_(original_state)
|
|
732
739
|
|
|
733
740
|
if len(all_fitnesses) == 1:
|
|
734
741
|
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,6 +174,7 @@ 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,
|
|
@@ -237,7 +239,7 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
237
239
|
model = ModuleList(model)
|
|
238
240
|
|
|
239
241
|
self.model = model
|
|
240
|
-
self.noisable_model = Noisable(model, low_rank = noise_low_rank)
|
|
242
|
+
self.noisable_model = Noisable(model, low_rank = noise_low_rank, noise_dtype = noise_dtype)
|
|
241
243
|
|
|
242
244
|
# maybe sync model params and buffers
|
|
243
245
|
|
|
@@ -442,7 +444,7 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
442
444
|
|
|
443
445
|
# reproduce the noise from the seed
|
|
444
446
|
|
|
445
|
-
noise = with_seed(seed)(model.
|
|
447
|
+
noise = with_seed(seed)(model.create_noise_)(shape, dtype = dtype)
|
|
446
448
|
noise = noise.to(self.device)
|
|
447
449
|
|
|
448
450
|
# scale the weight
|
|
@@ -461,7 +463,7 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
461
463
|
# maybe learned sigma
|
|
462
464
|
|
|
463
465
|
if self.learned_noise_scale:
|
|
464
|
-
one_grad_sigma = weight * (noise ** 2 - 1) / noise_scale
|
|
466
|
+
one_grad_sigma = weight * (noise.float() ** 2 - 1) / noise_scale
|
|
465
467
|
|
|
466
468
|
sigma_index = self.param_name_to_sigma_index[param_name]
|
|
467
469
|
sigma = self.sigmas[sigma_index]
|
|
@@ -524,8 +526,7 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
524
526
|
|
|
525
527
|
# maybe save model for rolling back (for meta-evo)
|
|
526
528
|
|
|
527
|
-
if rollback_model_at_end
|
|
528
|
-
self.checkpoint('initial.model')
|
|
529
|
+
original_state = self.snapshot_model_() if rollback_model_at_end else None
|
|
529
530
|
|
|
530
531
|
# maybe sigmas
|
|
531
532
|
|
|
@@ -600,7 +601,7 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
600
601
|
fitnesses.append(None)
|
|
601
602
|
continue
|
|
602
603
|
|
|
603
|
-
def get_fitness(negate = False):
|
|
604
|
+
def get_fitness(negate = False, individual_seed = individual_seed, maybe_rollout_seed = maybe_rollout_seed):
|
|
604
605
|
nonlocal rewards_by_scope
|
|
605
606
|
|
|
606
607
|
individual_param_seeds = with_seed(individual_seed.item())(randint)(0, MAX_SEED_VALUE, (self.num_params,))
|
|
@@ -750,10 +751,8 @@ class EvoStrategy(EvolutionStrategy):
|
|
|
750
751
|
|
|
751
752
|
# maybe rollback
|
|
752
753
|
|
|
753
|
-
if
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
self.model.load_state_dict(orig_state_dict)
|
|
754
|
+
if exists(original_state):
|
|
755
|
+
self.restore_model_(original_state)
|
|
757
756
|
|
|
758
757
|
# return fitnesses across generations
|
|
759
758
|
# for meta-evolutionary (nesting EvoStrategy within the environment of another and optimizing some meta-network)
|
|
File without changes
|
|
File without changes
|