x-evolution 0.0.1__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.
@@ -0,0 +1,36 @@
1
+ # This workflow will upload a Python Package using Twine when a release is created
2
+ # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
3
+
4
+ # This workflow uses actions that are not certified by GitHub.
5
+ # They are provided by a third-party and are governed by
6
+ # separate terms of service, privacy policy, and support
7
+ # documentation.
8
+
9
+ name: Upload Python Package
10
+
11
+ on:
12
+ release:
13
+ types: [published]
14
+
15
+ jobs:
16
+ deploy:
17
+
18
+ runs-on: ubuntu-latest
19
+
20
+ steps:
21
+ - uses: actions/checkout@v2
22
+ - name: Set up Python
23
+ uses: actions/setup-python@v2
24
+ with:
25
+ python-version: '3.x'
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m pip install --upgrade pip
29
+ pip install build
30
+ - name: Build package
31
+ run: python -m build
32
+ - name: Publish package
33
+ uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
34
+ with:
35
+ user: __token__
36
+ password: ${{ secrets.PYPI_API_TOKEN }}
@@ -0,0 +1,21 @@
1
+ name: Pytest
2
+ on: [push, pull_request]
3
+
4
+ jobs:
5
+ build:
6
+
7
+ runs-on: ubuntu-latest
8
+
9
+ steps:
10
+ - uses: actions/checkout@v4
11
+ - name: Set up Python 3.10
12
+ uses: actions/setup-python@v5
13
+ with:
14
+ python-version: "3.10"
15
+ - name: Install dependencies
16
+ run: |
17
+ python -m pip install --upgrade pip
18
+ python -m pip install -e .[test]
19
+ - name: Test with pytest
20
+ run: |
21
+ python -m pytest tests/
@@ -0,0 +1,207 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Phil Wang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: x-evolution
3
+ Version: 0.0.1
4
+ Summary: x-evolution
5
+ Project-URL: Homepage, https://pypi.org/project/x-evolution/
6
+ Project-URL: Repository, https://github.com/lucidrains/x-evolution
7
+ Author-email: Phil Wang <lucidrains@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2025 Phil Wang
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENSE
30
+ Keywords: artificial intelligence,evolution,evolutionary algorithms
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3.9
35
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
36
+ Requires-Python: >=3.9
37
+ Requires-Dist: accelerate
38
+ Requires-Dist: beartype
39
+ Requires-Dist: einops>=0.8.0
40
+ Requires-Dist: torch>=2.4
41
+ Requires-Dist: x-mlps-pytorch>=0.1.8
42
+ Requires-Dist: x-transformers>=2.11.23
43
+ Provides-Extra: examples
44
+ Provides-Extra: test
45
+ Requires-Dist: pytest; extra == 'test'
46
+ Description-Content-Type: text/markdown
47
+
48
+ ## x-evolution (wip)
49
+
50
+ Implementation of various evolutionary algorithms, starting with evolutionary strategies
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ $ pip install x-evolution
56
+ ```
57
+
58
+ ## Usage
59
+
60
+ ```python
61
+ import torch
62
+ from x_evolution import EvoStrategy
63
+
64
+ # model
65
+
66
+ from torch import nn
67
+ model = torch.nn.Sequential(
68
+ nn.Linear(8, 16),
69
+ nn.ReLU(),
70
+ nn.Linear(16, 4)
71
+ )
72
+
73
+ # evolution wrapper
74
+
75
+ evo_strat = EvoStrategy(
76
+ model,
77
+ environment = lambda model: torch.randint(0, 100, ()), # environment is just a function that takes in the individual model (with unique noise) and outputs the fitness - you can select for whatever you want here, does not have to be differentiable.
78
+ population_size = 30,
79
+ num_generations = 100,
80
+ learning_rate = 1e-3,
81
+ noise_scale = 1e-3
82
+ )
83
+
84
+ # do evolution with your desired fitness function for so many generations
85
+
86
+ evo_strat()
87
+
88
+ # then save your evolved model, maybe for alternating with gradient based training
89
+
90
+ torch.save(model.state_dict(), './evolved.pt')
91
+ ```
92
+
93
+ ## Citations
94
+
95
+ ```bibtex
96
+ @article{Qiu2025EvolutionSA,
97
+ title = {Evolution Strategies at Scale: LLM Fine-Tuning Beyond Reinforcement Learning},
98
+ author = {Xin Qiu and Yulu Gan and Conor F. Hayes and Qiyao Liang and Elliot Meyerson and Babak Hodjat and Risto Miikkulainen},
99
+ journal = {ArXiv},
100
+ year = {2025},
101
+ volume = {abs/2509.24372},
102
+ url = {https://api.semanticscholar.org/CorpusID:281674745}
103
+ }
104
+ ```
@@ -0,0 +1,57 @@
1
+ ## x-evolution (wip)
2
+
3
+ Implementation of various evolutionary algorithms, starting with evolutionary strategies
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ $ pip install x-evolution
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ import torch
15
+ from x_evolution import EvoStrategy
16
+
17
+ # model
18
+
19
+ from torch import nn
20
+ model = torch.nn.Sequential(
21
+ nn.Linear(8, 16),
22
+ nn.ReLU(),
23
+ nn.Linear(16, 4)
24
+ )
25
+
26
+ # evolution wrapper
27
+
28
+ evo_strat = EvoStrategy(
29
+ model,
30
+ environment = lambda model: torch.randint(0, 100, ()), # environment is just a function that takes in the individual model (with unique noise) and outputs the fitness - you can select for whatever you want here, does not have to be differentiable.
31
+ population_size = 30,
32
+ num_generations = 100,
33
+ learning_rate = 1e-3,
34
+ noise_scale = 1e-3
35
+ )
36
+
37
+ # do evolution with your desired fitness function for so many generations
38
+
39
+ evo_strat()
40
+
41
+ # then save your evolved model, maybe for alternating with gradient based training
42
+
43
+ torch.save(model.state_dict(), './evolved.pt')
44
+ ```
45
+
46
+ ## Citations
47
+
48
+ ```bibtex
49
+ @article{Qiu2025EvolutionSA,
50
+ title = {Evolution Strategies at Scale: LLM Fine-Tuning Beyond Reinforcement Learning},
51
+ author = {Xin Qiu and Yulu Gan and Conor F. Hayes and Qiyao Liang and Elliot Meyerson and Babak Hodjat and Risto Miikkulainen},
52
+ journal = {ArXiv},
53
+ year = {2025},
54
+ volume = {abs/2509.24372},
55
+ url = {https://api.semanticscholar.org/CorpusID:281674745}
56
+ }
57
+ ```
@@ -0,0 +1,61 @@
1
+ [project]
2
+ name = "x-evolution"
3
+ version = "0.0.1"
4
+ description = "x-evolution"
5
+ authors = [
6
+ { name = "Phil Wang", email = "lucidrains@gmail.com" }
7
+ ]
8
+ readme = "README.md"
9
+ requires-python = ">= 3.9"
10
+ license = { file = "LICENSE" }
11
+ keywords = [
12
+ 'artificial intelligence',
13
+ 'evolutionary algorithms',
14
+ 'evolution'
15
+ ]
16
+
17
+ classifiers=[
18
+ 'Development Status :: 4 - Beta',
19
+ 'Intended Audience :: Developers',
20
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
21
+ 'License :: OSI Approved :: MIT License',
22
+ 'Programming Language :: Python :: 3.9',
23
+ ]
24
+
25
+ dependencies = [
26
+ "accelerate",
27
+ "beartype",
28
+ "einops>=0.8.0",
29
+ "torch>=2.4",
30
+ "x-mlps-pytorch>=0.1.8",
31
+ "x-transformers>=2.11.23"
32
+ ]
33
+
34
+ [project.urls]
35
+ Homepage = "https://pypi.org/project/x-evolution/"
36
+ Repository = "https://github.com/lucidrains/x-evolution"
37
+
38
+ [project.optional-dependencies]
39
+ examples = []
40
+ test = [
41
+ "pytest"
42
+ ]
43
+
44
+ [tool.pytest.ini_options]
45
+ pythonpath = [
46
+ "."
47
+ ]
48
+
49
+ [build-system]
50
+ requires = ["hatchling"]
51
+ build-backend = "hatchling.build"
52
+
53
+ [tool.rye]
54
+ managed = true
55
+ dev-dependencies = []
56
+
57
+ [tool.hatch.metadata]
58
+ allow-direct-references = true
59
+
60
+ [tool.hatch.build.targets.wheel]
61
+ packages = ["x_evolution"]
@@ -0,0 +1,19 @@
1
+ import pytest
2
+
3
+ import torch
4
+
5
+ def test_evo_strat():
6
+ from random import randrange
7
+
8
+ from x_evolution.x_evolution import EvoStrategy
9
+
10
+ from x_mlps_pytorch import MLP
11
+ model = MLP(8, 16, 4)
12
+
13
+ evo_strat = EvoStrategy(
14
+ model,
15
+ environment = lambda model: float(randrange(100)),
16
+ num_generations = 100
17
+ )
18
+
19
+ evo_strat()
@@ -0,0 +1,4 @@
1
+
2
+ from x_evolution.x_evolution import (
3
+ EvoStrategy
4
+ )
@@ -0,0 +1,188 @@
1
+ from __future__ import annotations
2
+ from typing import Callable
3
+
4
+ import torch
5
+ from torch import tensor, is_tensor
6
+ from torch.nn import Module
7
+ import torch.nn.functional as F
8
+ from torch.func import functional_call, vmap
9
+
10
+ from beartype import beartype
11
+ from beartype.door import is_bearable
12
+
13
+ from accelerate import Accelerator
14
+
15
+ from x_mlps_pytorch.noisable import (
16
+ Noisable,
17
+ with_seed
18
+ )
19
+
20
+ # constants
21
+
22
+ MAX_SEED_VALUE = int(2 ** 32)
23
+
24
+ # helper functions
25
+
26
+ def exists(v):
27
+ return v is not None
28
+
29
+ def default(v, d):
30
+ return v if exists(v) else d
31
+
32
+ def normalize(t, eps = 1e-6):
33
+ return F.layer_norm(t, t.shape[-1:], eps = eps)
34
+
35
+ # class
36
+
37
+ class EvoStrategy(Module):
38
+
39
+ @beartype
40
+ def __init__(
41
+ self,
42
+ model: Module,
43
+ *,
44
+ environment: Callable[[Module], float], # the environment is simply a function that takes in the model and returns a fitness score
45
+ num_generations,
46
+ population_size = 30,
47
+ learning_rate = 1e-3, # todo - optimizer
48
+ noise_scale = 1e-3, # 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
49
+ param_names_to_optimize: list[str] | None = None,
50
+ fitness_to_weighted_factor: Callable[[Tensor], Tensor] = normalize,
51
+ cpu = False,
52
+ accelerate_kwargs: dict = dict(),
53
+ ):
54
+ super().__init__()
55
+
56
+ self.accelerate = Accelerator(cpu = cpu, **accelerate_kwargs)
57
+
58
+ self.model = model
59
+ self.noisable_model = Noisable(model)
60
+
61
+ self.environment = environment
62
+
63
+ param_names = set(dict(model.named_parameters()).keys())
64
+
65
+ # default to all parameters to optimize with evo strategy
66
+
67
+ param_names_to_optimize = default(param_names_to_optimize, param_names)
68
+
69
+ # validate
70
+
71
+ assert all([name in param_names for name in param_names_to_optimize])
72
+ assert len(param_names_to_optimize) > 0, 'nothing to optimize'
73
+
74
+ # sort param names and store
75
+
76
+ param_names_list = list(param_names_to_optimize)
77
+ param_names_list.sort()
78
+
79
+ self.param_names_to_optimize = param_names_list
80
+
81
+ # hyperparameters
82
+
83
+ self.population_size = population_size
84
+ self.num_params = len(param_names_list) # just convenience for generating all the seeds for all the randn for the proposed memory efficient way
85
+
86
+ self.num_generations = num_generations
87
+
88
+ # the function that transforms a tensor of fitness floats to the weight for the weighted average of the noise for rolling out 1x1 ES
89
+
90
+ self.fitness_to_weighted_factor = fitness_to_weighted_factor
91
+
92
+ self.noise_scale = noise_scale
93
+ self.learning_rate = learning_rate
94
+
95
+ self.register_buffer('_dummy', tensor(0), persistent = False)
96
+
97
+ @property
98
+ def device(self):
99
+ return self._dummy.device
100
+
101
+ def print(self, *args, **kwargs):
102
+ return self.accelerate.print(*args, **kwargs)
103
+
104
+ @torch.inference_mode()
105
+ def evolve_(
106
+ self,
107
+ fitnesses: list[float] | Tensor,
108
+ seeds_for_population: list[int] | Tensor
109
+ ):
110
+ model = self.noisable_model
111
+
112
+ if isinstance(fitnesses, list):
113
+ fitnesses = tensor(fitnesses)
114
+
115
+ if isinstance(seeds_for_population, list):
116
+ seeds_for_population = tensor(seeds_for_population)
117
+
118
+ fitnesses = fitnesses.to(self.device)
119
+ seeds_for_population.to(self.device)
120
+
121
+ # they use a simple z-score for the fitnesses, need to figure out the natural ES connection
122
+
123
+ noise_weights = self.fitness_to_weighted_factor(fitnesses)
124
+
125
+ noise_weights *= self.learning_rate # some learning rate that subsumes another constant
126
+
127
+ # update one seed at a time for enabling evolutionary strategy for large models
128
+
129
+ for individual_seed, noise_weight in zip(seeds_for_population.tolist(), noise_weights.tolist()):
130
+
131
+ individual_param_seeds = with_seed(individual_seed)(torch.randint)(0, MAX_SEED_VALUE, (self.num_params,))
132
+
133
+ noise_config = dict(zip(self.param_names_to_optimize, individual_param_seeds.tolist()))
134
+
135
+ # set the noise weight
136
+
137
+ noise_config = {param_name: (seed, noise_weight) for param_name, seed in noise_config.items()}
138
+
139
+ # now update
140
+
141
+ model.add_noise_(noise_config)
142
+
143
+ @torch.inference_mode()
144
+ def forward(
145
+ self
146
+ ):
147
+
148
+ model = self.noisable_model
149
+
150
+ for index in range(self.num_generations):
151
+ generation = index + 1
152
+
153
+ fitnesses = []
154
+
155
+ # predetermine the seeds for each population
156
+ # each seed is then used as a seed for all the parameters
157
+
158
+ seeds_for_population = torch.randint(0, MAX_SEED_VALUE, (self.population_size,))
159
+
160
+ # now loop through the entire population of noise
161
+
162
+ for individual_seed in seeds_for_population.tolist():
163
+
164
+ individual_param_seeds = with_seed(individual_seed)(torch.randint)(0, MAX_SEED_VALUE, (self.num_params,))
165
+
166
+ noise_config = dict(zip(self.param_names_to_optimize, individual_param_seeds.tolist()))
167
+ noise_config = {param_name: (seed, self.noise_scale) for param_name, seed in noise_config.items()}
168
+
169
+ with model.temp_add_noise_(noise_config):
170
+ fitness = self.environment(model)
171
+
172
+ if is_tensor(fitness):
173
+ assert fitness.numel() == 1
174
+ fitness = fitness.item()
175
+
176
+ fitnesses.append(fitness)
177
+
178
+ # normalize the fitness and weighted sum of all the noise is the update
179
+
180
+ fitnesses = tensor(fitnesses).float()
181
+
182
+ self.evolve_(fitnesses, seeds_for_population)
183
+
184
+ # log
185
+
186
+ self.print(f'[{generation}] average fitness: {fitnesses.mean():.3f} | fitness std: {fitnesses.std():.3f}')
187
+
188
+ self.print('evolution complete')