torchneat 0.1.0__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.
- torchneat-0.1.0/CHANGELOG.md +15 -0
- torchneat-0.1.0/LICENSE +21 -0
- torchneat-0.1.0/MANIFEST.in +6 -0
- torchneat-0.1.0/PKG-INFO +135 -0
- torchneat-0.1.0/README.md +89 -0
- torchneat-0.1.0/pyproject.toml +83 -0
- torchneat-0.1.0/setup.cfg +4 -0
- torchneat-0.1.0/torchneat/__init__.py +85 -0
- torchneat-0.1.0/torchneat/_version.py +1 -0
- torchneat-0.1.0/torchneat/backends/__init__.py +26 -0
- torchneat-0.1.0/torchneat/backends/cpu/__init__.py +47 -0
- torchneat-0.1.0/torchneat/backends/cpu/backend.py +60 -0
- torchneat-0.1.0/torchneat/backends/cpu/functional.py +74 -0
- torchneat-0.1.0/torchneat/backends/cpu/initialization.py +57 -0
- torchneat-0.1.0/torchneat/backends/cpu/mutation.py +110 -0
- torchneat-0.1.0/torchneat/backends/cpu/reproduction.py +91 -0
- torchneat-0.1.0/torchneat/backends/cpu/speciation.py +116 -0
- torchneat-0.1.0/torchneat/backends/execution.py +229 -0
- torchneat-0.1.0/torchneat/backends/functional.py +58 -0
- torchneat-0.1.0/torchneat/backends/gpu/__init__.py +47 -0
- torchneat-0.1.0/torchneat/backends/gpu/backend.py +66 -0
- torchneat-0.1.0/torchneat/backends/gpu/functional.py +106 -0
- torchneat-0.1.0/torchneat/backends/gpu/initialization.py +51 -0
- torchneat-0.1.0/torchneat/backends/gpu/mutation.py +100 -0
- torchneat-0.1.0/torchneat/backends/gpu/reproduction.py +77 -0
- torchneat-0.1.0/torchneat/backends/gpu/speciation.py +115 -0
- torchneat-0.1.0/torchneat/backends/initialization.py +62 -0
- torchneat-0.1.0/torchneat/backends/interface.py +69 -0
- torchneat-0.1.0/torchneat/backends/reproduction.py +652 -0
- torchneat-0.1.0/torchneat/backends/seeding.py +92 -0
- torchneat-0.1.0/torchneat/backends/speciation.py +256 -0
- torchneat-0.1.0/torchneat/backends/util.py +127 -0
- torchneat-0.1.0/torchneat/config/__init__.py +6 -0
- torchneat-0.1.0/torchneat/config/base.py +123 -0
- torchneat-0.1.0/torchneat/config/types.py +153 -0
- torchneat-0.1.0/torchneat/core/__init__.py +38 -0
- torchneat-0.1.0/torchneat/core/constants.py +23 -0
- torchneat-0.1.0/torchneat/core/genome.py +47 -0
- torchneat-0.1.0/torchneat/core/population.py +999 -0
- torchneat-0.1.0/torchneat/core/reproduction.py +63 -0
- torchneat-0.1.0/torchneat/core/species.py +151 -0
- torchneat-0.1.0/torchneat/core/stagnation.py +106 -0
- torchneat-0.1.0/torchneat/nn/__init__.py +152 -0
- torchneat-0.1.0/torchneat/nn/activations.py +64 -0
- torchneat-0.1.0/torchneat/nn/blocks/__init__.py +48 -0
- torchneat-0.1.0/torchneat/nn/blocks/_common.py +20 -0
- torchneat-0.1.0/torchneat/nn/blocks/attention.py +721 -0
- torchneat-0.1.0/torchneat/nn/blocks/conv_attention.py +519 -0
- torchneat-0.1.0/torchneat/nn/blocks/conver.py +367 -0
- torchneat-0.1.0/torchneat/nn/blocks/encoding.py +474 -0
- torchneat-0.1.0/torchneat/nn/blocks/feedforward.py +144 -0
- torchneat-0.1.0/torchneat/nn/blocks/reformer.py +221 -0
- torchneat-0.1.0/torchneat/nn/blocks/residual.py +94 -0
- torchneat-0.1.0/torchneat/nn/blocks/transformer.py +225 -0
- torchneat-0.1.0/torchneat/nn/distributions.py +170 -0
- torchneat-0.1.0/torchneat/nn/layers/__init__.py +22 -0
- torchneat-0.1.0/torchneat/nn/layers/containers.py +64 -0
- torchneat-0.1.0/torchneat/nn/layers/convolution.py +254 -0
- torchneat-0.1.0/torchneat/nn/layers/embedding.py +59 -0
- torchneat-0.1.0/torchneat/nn/layers/linear.py +87 -0
- torchneat-0.1.0/torchneat/nn/layers/normalization.py +204 -0
- torchneat-0.1.0/torchneat/nn/layers/pooling.py +173 -0
- torchneat-0.1.0/torchneat/nn/layers/recurrent.py +83 -0
- torchneat-0.1.0/torchneat/nn/layers/shape.py +61 -0
- torchneat-0.1.0/torchneat/nn/legacy.py +98 -0
- torchneat-0.1.0/torchneat/nn/model.py +130 -0
- torchneat-0.1.0/torchneat/nn/module.py +1000 -0
- torchneat-0.1.0/torchneat/nn/parameter.py +212 -0
- torchneat-0.1.0/torchneat/nn/utils.py +80 -0
- torchneat-0.1.0/torchneat/nn/wrapped.py +81 -0
- torchneat-0.1.0/torchneat/optim/__init__.py +6 -0
- torchneat-0.1.0/torchneat/optim/scheduler.py +216 -0
- torchneat-0.1.0/torchneat/py.typed +0 -0
- torchneat-0.1.0/torchneat/reporting/__init__.py +10 -0
- torchneat-0.1.0/torchneat/reporting/attention.py +253 -0
- torchneat-0.1.0/torchneat/reporting/base.py +77 -0
- torchneat-0.1.0/torchneat/reporting/reporters.py +95 -0
- torchneat-0.1.0/torchneat/rl/__init__.py +21 -0
- torchneat-0.1.0/torchneat/rl/base.py +897 -0
- torchneat-0.1.0/torchneat/rl/functional.py +731 -0
- torchneat-0.1.0/torchneat/rl/logger.py +191 -0
- torchneat-0.1.0/torchneat/rl/neat.py +542 -0
- torchneat-0.1.0/torchneat/rl/ppo.py +550 -0
- torchneat-0.1.0/torchneat/rl/replay.py +784 -0
- torchneat-0.1.0/torchneat/utils/__init__.py +11 -0
- torchneat-0.1.0/torchneat/utils/console.py +10 -0
- torchneat-0.1.0/torchneat/utils/helpers.py +34 -0
- torchneat-0.1.0/torchneat/utils/replay.py +276 -0
- torchneat-0.1.0/torchneat/utils/storage.py +295 -0
- torchneat-0.1.0/torchneat/utils/timing.py +41 -0
- torchneat-0.1.0/torchneat.egg-info/PKG-INFO +135 -0
- torchneat-0.1.0/torchneat.egg-info/SOURCES.txt +93 -0
- torchneat-0.1.0/torchneat.egg-info/dependency_links.txt +1 -0
- torchneat-0.1.0/torchneat.egg-info/requires.txt +22 -0
- torchneat-0.1.0/torchneat.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 0.1.0
|
|
6
|
+
- First release of `torchneat`, a restructured package built from an earlier private project (its history is not carried over).
|
|
7
|
+
- New layout: `core/` (genome, species, stagnation, reproduction, population), `backends/` (device-independent
|
|
8
|
+
orchestration plus `cpu/` and `gpu/` kernels), `nn/` (evolvable modules, layers, blocks, wrapped PyTorch modules),
|
|
9
|
+
`rl/` (NEAT and PPO trainers), `config/`, `optim/`, `reporting/` and `utils/`.
|
|
10
|
+
- Added PyTorch activations, regularisation, container and shape modules re-exported from `torchneat.nn`, so user code no
|
|
11
|
+
longer has to import `torch.nn` next to `torchneat`.
|
|
12
|
+
- Moved the old NEAT-style activations to `torchneat.nn.legacy`.
|
|
13
|
+
- GPU tests are marked `gpu` and skip themselves when no usable CUDA device is present.
|
|
14
|
+
- Removed unused code: the stale `cuda` stub, the unused reproduction draft, multiprocessing inference helpers, the legacy RL trainers and
|
|
15
|
+
unused helpers. The examples and the NeatBoard dashboard now live outside this package.
|
torchneat-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Bradley Odimmasi
|
|
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.
|
torchneat-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: torchneat
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: TorchNEAT - GPU/CPU accelerated neuroevolution for PyTorch modules
|
|
5
|
+
Author: Bradley Odimmasi
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/KshRaven/torchneat
|
|
8
|
+
Project-URL: Documentation, https://github.com/KshRaven/torchneat#readme
|
|
9
|
+
Project-URL: Source, https://github.com/KshRaven/torchneat
|
|
10
|
+
Project-URL: Issues, https://github.com/KshRaven/torchneat/issues
|
|
11
|
+
Project-URL: Changelog, https://github.com/KshRaven/torchneat/blob/main/CHANGELOG.md
|
|
12
|
+
Keywords: neuroevolution,neat,pytorch,evolutionary algorithms,reinforcement learning,numba
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: numpy
|
|
28
|
+
Requires-Dist: numba
|
|
29
|
+
Requires-Dist: torch
|
|
30
|
+
Requires-Dist: colorama
|
|
31
|
+
Provides-Extra: gpu
|
|
32
|
+
Requires-Dist: cuda-python>=12.0; extra == "gpu"
|
|
33
|
+
Requires-Dist: cuda-toolkit; extra == "gpu"
|
|
34
|
+
Requires-Dist: numba-cuda[cu13]; extra == "gpu"
|
|
35
|
+
Requires-Dist: cupy-cuda13x; extra == "gpu"
|
|
36
|
+
Provides-Extra: logging
|
|
37
|
+
Requires-Dist: runlytics; extra == "logging"
|
|
38
|
+
Provides-Extra: all
|
|
39
|
+
Requires-Dist: torchneat[gpu,logging]; extra == "all"
|
|
40
|
+
Provides-Extra: dev
|
|
41
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
42
|
+
Requires-Dist: ruff; extra == "dev"
|
|
43
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
44
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
45
|
+
Dynamic: license-file
|
|
46
|
+
|
|
47
|
+
# TorchNEAT
|
|
48
|
+
|
|
49
|
+
TorchNEAT is a PyTorch-based neuroevolution library. It evolves the parameters of `NeatModule` models through
|
|
50
|
+
initialization, mutation, speciation and reproduction, on the CPU (numba) or on an NVIDIA GPU (numba.cuda / cupy).
|
|
51
|
+
RL trainers (`NEAT`, `PPO`) are included; environment design and fitness evaluation remain the caller's job.
|
|
52
|
+
|
|
53
|
+
> TorchNEAT grew out of an earlier private project of the same author. This repository is a clean restructure; the old
|
|
54
|
+
> history is not carried over.
|
|
55
|
+
|
|
56
|
+
## Install
|
|
57
|
+
|
|
58
|
+
Python 3.11 or newer.
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install torchneat # CPU backend
|
|
62
|
+
pip install "torchneat[gpu]" # + CUDA backend (NVIDIA GPU)
|
|
63
|
+
pip install "torchneat[logging]" # + runlytics logging for the RL trainers
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Quick start
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
import torch
|
|
70
|
+
import torchneat as neat
|
|
71
|
+
from torchneat import nn
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Policy(neat.nn.Model):
|
|
75
|
+
def __init__(self, inputs=4, hidden=16, outputs=2):
|
|
76
|
+
super().__init__()
|
|
77
|
+
self.net = nn.Sequential(
|
|
78
|
+
nn.Linear(inputs, hidden), nn.Tanh(), # NEAT-evolvable layer + wrapped PyTorch activation
|
|
79
|
+
nn.Linear(hidden, outputs),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
def forward(self, state, keys=None):
|
|
83
|
+
return self.net(state, keys=keys)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
config = neat.Config(file_name="demo", directory="demo")
|
|
87
|
+
population = neat.Population(100, Policy(), config)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Everything you normally take from `torch.nn` (activations, dropout, flatten, containers, ...) is re-exported from
|
|
91
|
+
`torchneat.nn`. Parameters that evolve use `NeatParameter` /
|
|
92
|
+
`NeatModule`; everything else is plain PyTorch.
|
|
93
|
+
|
|
94
|
+
## Package layout
|
|
95
|
+
|
|
96
|
+
| Package | Contents |
|
|
97
|
+
|---|---|
|
|
98
|
+
| `torchneat.core` | `Genome`, `Species`/`SpeciesSet`, `Stagnation`, `Reproduction`, `Population` |
|
|
99
|
+
| `torchneat.backends` | device-independent init/reproduce/speciate orchestration, `cpu/` and `gpu/` kernels, seeding |
|
|
100
|
+
| `torchneat.nn` | `NeatParameter`, `NeatModule`, `Model`; layers, attention/transformer blocks, activations, PyTorch re-exports; `legacy/` |
|
|
101
|
+
| `torchneat.rl` | `NEAT` and `PPO` trainers, rollout buffers, logger |
|
|
102
|
+
| `torchneat.config` | `Config` and its sections |
|
|
103
|
+
| `torchneat.optim` | hyper-parameter schedulers |
|
|
104
|
+
| `torchneat.reporting` | reporters and loggers |
|
|
105
|
+
| `torchneat.utils` | storage, console colours, timing, helpers |
|
|
106
|
+
|
|
107
|
+
## Devices
|
|
108
|
+
|
|
109
|
+
CPU is the default. Choose the device with `torchneat.set_device("cuda")` or the `TORCHNEAT_DEVICE` environment
|
|
110
|
+
variable; `torchneat.cuda_is_available()` tells whether the GPU backend is usable.
|
|
111
|
+
|
|
112
|
+
## Saving and loading
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
population.save(filename="experiment", directory="neat_save")
|
|
116
|
+
population.load(filename="experiment", directory="neat_save")
|
|
117
|
+
state = population.state_dict()
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Checkpoints use `pickle`; only load files you trust.
|
|
121
|
+
|
|
122
|
+
## Documentation
|
|
123
|
+
|
|
124
|
+
- [Configuration](docs/configuration.md): experiment settings and schedulers.
|
|
125
|
+
- [Reinforcement learning](docs/reinforcement-learning.md): trainers, rollout behaviour and metrics.
|
|
126
|
+
|
|
127
|
+
## Development
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
pip install -e ".[dev]"
|
|
131
|
+
pytest -m "not gpu" # CPU tests
|
|
132
|
+
pytest -m gpu # GPU tests (skipped when no CUDA device is usable)
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md), [CHANGELOG.md](CHANGELOG.md) and [TODO.md](TODO.md).
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# TorchNEAT
|
|
2
|
+
|
|
3
|
+
TorchNEAT is a PyTorch-based neuroevolution library. It evolves the parameters of `NeatModule` models through
|
|
4
|
+
initialization, mutation, speciation and reproduction, on the CPU (numba) or on an NVIDIA GPU (numba.cuda / cupy).
|
|
5
|
+
RL trainers (`NEAT`, `PPO`) are included; environment design and fitness evaluation remain the caller's job.
|
|
6
|
+
|
|
7
|
+
> TorchNEAT grew out of an earlier private project of the same author. This repository is a clean restructure; the old
|
|
8
|
+
> history is not carried over.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
Python 3.11 or newer.
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install torchneat # CPU backend
|
|
16
|
+
pip install "torchneat[gpu]" # + CUDA backend (NVIDIA GPU)
|
|
17
|
+
pip install "torchneat[logging]" # + runlytics logging for the RL trainers
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Quick start
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import torch
|
|
24
|
+
import torchneat as neat
|
|
25
|
+
from torchneat import nn
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Policy(neat.nn.Model):
|
|
29
|
+
def __init__(self, inputs=4, hidden=16, outputs=2):
|
|
30
|
+
super().__init__()
|
|
31
|
+
self.net = nn.Sequential(
|
|
32
|
+
nn.Linear(inputs, hidden), nn.Tanh(), # NEAT-evolvable layer + wrapped PyTorch activation
|
|
33
|
+
nn.Linear(hidden, outputs),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def forward(self, state, keys=None):
|
|
37
|
+
return self.net(state, keys=keys)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
config = neat.Config(file_name="demo", directory="demo")
|
|
41
|
+
population = neat.Population(100, Policy(), config)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Everything you normally take from `torch.nn` (activations, dropout, flatten, containers, ...) is re-exported from
|
|
45
|
+
`torchneat.nn`. Parameters that evolve use `NeatParameter` /
|
|
46
|
+
`NeatModule`; everything else is plain PyTorch.
|
|
47
|
+
|
|
48
|
+
## Package layout
|
|
49
|
+
|
|
50
|
+
| Package | Contents |
|
|
51
|
+
|---|---|
|
|
52
|
+
| `torchneat.core` | `Genome`, `Species`/`SpeciesSet`, `Stagnation`, `Reproduction`, `Population` |
|
|
53
|
+
| `torchneat.backends` | device-independent init/reproduce/speciate orchestration, `cpu/` and `gpu/` kernels, seeding |
|
|
54
|
+
| `torchneat.nn` | `NeatParameter`, `NeatModule`, `Model`; layers, attention/transformer blocks, activations, PyTorch re-exports; `legacy/` |
|
|
55
|
+
| `torchneat.rl` | `NEAT` and `PPO` trainers, rollout buffers, logger |
|
|
56
|
+
| `torchneat.config` | `Config` and its sections |
|
|
57
|
+
| `torchneat.optim` | hyper-parameter schedulers |
|
|
58
|
+
| `torchneat.reporting` | reporters and loggers |
|
|
59
|
+
| `torchneat.utils` | storage, console colours, timing, helpers |
|
|
60
|
+
|
|
61
|
+
## Devices
|
|
62
|
+
|
|
63
|
+
CPU is the default. Choose the device with `torchneat.set_device("cuda")` or the `TORCHNEAT_DEVICE` environment
|
|
64
|
+
variable; `torchneat.cuda_is_available()` tells whether the GPU backend is usable.
|
|
65
|
+
|
|
66
|
+
## Saving and loading
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
population.save(filename="experiment", directory="neat_save")
|
|
70
|
+
population.load(filename="experiment", directory="neat_save")
|
|
71
|
+
state = population.state_dict()
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Checkpoints use `pickle`; only load files you trust.
|
|
75
|
+
|
|
76
|
+
## Documentation
|
|
77
|
+
|
|
78
|
+
- [Configuration](docs/configuration.md): experiment settings and schedulers.
|
|
79
|
+
- [Reinforcement learning](docs/reinforcement-learning.md): trainers, rollout behaviour and metrics.
|
|
80
|
+
|
|
81
|
+
## Development
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
pip install -e ".[dev]"
|
|
85
|
+
pytest -m "not gpu" # CPU tests
|
|
86
|
+
pytest -m gpu # GPU tests (skipped when no CUDA device is usable)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md), [CHANGELOG.md](CHANGELOG.md) and [TODO.md](TODO.md).
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "torchneat"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "TorchNEAT - GPU/CPU accelerated neuroevolution for PyTorch modules"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Bradley Odimmasi" }]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
keywords = ["neuroevolution", "neat", "pytorch", "evolutionary algorithms", "reinforcement learning", "numba"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Intended Audience :: Science/Research",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Programming Language :: Python :: 3.14",
|
|
25
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"numpy",
|
|
30
|
+
"numba",
|
|
31
|
+
"torch",
|
|
32
|
+
"colorama",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
# What you get from each install:
|
|
36
|
+
# pip install torchneat CPU backend (numba prange) + PyTorch modules + RL trainers
|
|
37
|
+
# pip install "torchneat[gpu]" + CUDA backend (cupy / numba-cuda); needs an NVIDIA GPU
|
|
38
|
+
# pip install "torchneat[logging]" + runlytics dashboard logging for the RL trainers
|
|
39
|
+
# pip install -e ".[dev]" + pytest, ruff, build, twine (GPU tests skip themselves without a GPU)
|
|
40
|
+
[project.optional-dependencies]
|
|
41
|
+
gpu = [
|
|
42
|
+
"cuda-python>=12.0",
|
|
43
|
+
"cuda-toolkit",
|
|
44
|
+
"numba-cuda[cu13]",
|
|
45
|
+
"cupy-cuda13x",
|
|
46
|
+
]
|
|
47
|
+
logging = ["runlytics"]
|
|
48
|
+
all = ["torchneat[gpu,logging]"]
|
|
49
|
+
dev = ["pytest>=8", "ruff", "build>=1.0", "twine>=5.0"]
|
|
50
|
+
|
|
51
|
+
[project.urls]
|
|
52
|
+
Homepage = "https://github.com/KshRaven/torchneat"
|
|
53
|
+
Documentation = "https://github.com/KshRaven/torchneat#readme"
|
|
54
|
+
Source = "https://github.com/KshRaven/torchneat"
|
|
55
|
+
Issues = "https://github.com/KshRaven/torchneat/issues"
|
|
56
|
+
Changelog = "https://github.com/KshRaven/torchneat/blob/main/CHANGELOG.md"
|
|
57
|
+
|
|
58
|
+
[tool.setuptools.dynamic]
|
|
59
|
+
version = { attr = "torchneat._version.__version__" }
|
|
60
|
+
|
|
61
|
+
[tool.setuptools.packages.find]
|
|
62
|
+
include = ["torchneat*"]
|
|
63
|
+
|
|
64
|
+
[tool.setuptools.package-data]
|
|
65
|
+
torchneat = ["py.typed"]
|
|
66
|
+
|
|
67
|
+
[tool.pytest.ini_options]
|
|
68
|
+
testpaths = ["tests"]
|
|
69
|
+
# Always import the package from this checkout (not a stale installed copy, or a bare folder of the same name)
|
|
70
|
+
pythonpath = ["."]
|
|
71
|
+
addopts = "-ra"
|
|
72
|
+
markers = [
|
|
73
|
+
"gpu: needs an NVIDIA GPU with cupy and numba.cuda (skipped automatically when none is usable)",
|
|
74
|
+
"slow: long running test",
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
[tool.ruff]
|
|
78
|
+
line-length = 120
|
|
79
|
+
target-version = "py311"
|
|
80
|
+
|
|
81
|
+
[tool.ruff.lint]
|
|
82
|
+
select = ["E9", "F63", "F7", "F82"]
|
|
83
|
+
ignore = []
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""TorchNEAT: CPU/GPU accelerated neuroevolution for PyTorch modules.
|
|
2
|
+
|
|
3
|
+
Typical use::
|
|
4
|
+
|
|
5
|
+
import torchneat as tn
|
|
6
|
+
|
|
7
|
+
config = tn.Config("demo", "demo")
|
|
8
|
+
population = tn.Population(100, MyPolicy(), config)
|
|
9
|
+
|
|
10
|
+
``torchneat.nn`` mirrors ``torch.nn`` (evolvable layers plus the common PyTorch modules re-exported), so model code
|
|
11
|
+
only needs ``import torchneat.nn as nn``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from importlib import import_module
|
|
15
|
+
from typing import TYPE_CHECKING
|
|
16
|
+
|
|
17
|
+
from ._version import __version__
|
|
18
|
+
|
|
19
|
+
# name -> submodule that defines it. Everything is imported lazily (PEP 562) so ``import torchneat`` stays cheap and
|
|
20
|
+
# the optional GPU / logging dependencies are never touched until used.
|
|
21
|
+
_EXPORTS = {
|
|
22
|
+
# configuration
|
|
23
|
+
"Config": "config",
|
|
24
|
+
# modules
|
|
25
|
+
"Genome": "core.genome",
|
|
26
|
+
"Model": "nn.model",
|
|
27
|
+
"NeatModule": "nn.module",
|
|
28
|
+
"NeatParameter": "nn.parameter",
|
|
29
|
+
# evolution
|
|
30
|
+
"Population": "core.population",
|
|
31
|
+
"Reproduction": "core.reproduction",
|
|
32
|
+
"Species": "core.species",
|
|
33
|
+
"SpeciesSet": "core.species",
|
|
34
|
+
"Stagnation": "core.stagnation",
|
|
35
|
+
# reporting
|
|
36
|
+
"BaseReporter": "reporting",
|
|
37
|
+
"ReporterSet": "reporting",
|
|
38
|
+
"StdOutReporter": "reporting",
|
|
39
|
+
# reinforcement learning
|
|
40
|
+
"NEAT": "rl",
|
|
41
|
+
"PPO": "rl",
|
|
42
|
+
# backends
|
|
43
|
+
"cuda_is_available": "backends",
|
|
44
|
+
"get_device": "backends",
|
|
45
|
+
"get_tpb": "backends",
|
|
46
|
+
"set_device": "backends",
|
|
47
|
+
"set_tpb": "backends",
|
|
48
|
+
# utils
|
|
49
|
+
"CM": "utils",
|
|
50
|
+
"Fore": "utils",
|
|
51
|
+
}
|
|
52
|
+
_SUBMODULES = ("backends", "config", "core", "nn", "optim", "reporting", "rl", "utils")
|
|
53
|
+
|
|
54
|
+
__all__ = ["__version__", *_EXPORTS, *_SUBMODULES]
|
|
55
|
+
|
|
56
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
57
|
+
from . import backends, config, core, nn, optim, reporting, rl, utils
|
|
58
|
+
from .backends import cuda_is_available, get_device, get_tpb, set_device, set_tpb
|
|
59
|
+
from .config import Config
|
|
60
|
+
from .core.genome import Genome
|
|
61
|
+
from .core.population import Population
|
|
62
|
+
from .core.reproduction import Reproduction
|
|
63
|
+
from .core.species import Species, SpeciesSet
|
|
64
|
+
from .core.stagnation import Stagnation
|
|
65
|
+
from .nn.model import Model
|
|
66
|
+
from .nn.module import NeatModule
|
|
67
|
+
from .nn.parameter import NeatParameter
|
|
68
|
+
from .reporting import BaseReporter, ReporterSet, StdOutReporter
|
|
69
|
+
from .rl import NEAT, PPO
|
|
70
|
+
from .utils import CM, Fore
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def __getattr__(name):
|
|
74
|
+
if name in _EXPORTS:
|
|
75
|
+
value = getattr(import_module(f"{__name__}.{_EXPORTS[name]}"), name)
|
|
76
|
+
elif name in _SUBMODULES:
|
|
77
|
+
value = import_module(f"{__name__}.{name}")
|
|
78
|
+
else:
|
|
79
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
80
|
+
globals()[name] = value
|
|
81
|
+
return value
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def __dir__():
|
|
85
|
+
return sorted(__all__)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Execution backends: device selection and the CPU (numba) / GPU (numba.cuda + cupy) kernels for
|
|
2
|
+
initialization, reproduction and speciation."""
|
|
3
|
+
|
|
4
|
+
from .execution import (
|
|
5
|
+
DEVICE_ENV_NAME,
|
|
6
|
+
TPB_ENV_NAME,
|
|
7
|
+
cuda_is_available,
|
|
8
|
+
get_device,
|
|
9
|
+
get_device_env,
|
|
10
|
+
get_tpb,
|
|
11
|
+
get_tpb_env,
|
|
12
|
+
initialize,
|
|
13
|
+
reproduce,
|
|
14
|
+
set_device,
|
|
15
|
+
set_device_env,
|
|
16
|
+
set_tpb,
|
|
17
|
+
set_tpb_env,
|
|
18
|
+
speciate,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
'DEVICE_ENV_NAME', 'TPB_ENV_NAME', 'cuda_is_available',
|
|
23
|
+
'get_device', 'get_device_env', 'get_tpb', 'get_tpb_env', 'initialize',
|
|
24
|
+
'reproduce', 'set_device', 'set_device_env', 'set_tpb', 'set_tpb_env',
|
|
25
|
+
'speciate',
|
|
26
|
+
]
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# ---------- CPU (numba, prange) implementation of the genome methods ---------- #
|
|
2
|
+
# Device independent logic lives in torchneat.base.{initialization, reproduction, speciation, util, functional};
|
|
3
|
+
# this package only holds the numba kernels and the CPU backend that plugs them into it.
|
|
4
|
+
|
|
5
|
+
from ...config import Config
|
|
6
|
+
from ...core.species import SpeciesSet
|
|
7
|
+
from ...core.stagnation import Stagnation
|
|
8
|
+
from ...nn import Genome, NeatModule
|
|
9
|
+
from ...reporting import ReporterSet
|
|
10
|
+
from .. import initialization as _initialization
|
|
11
|
+
from .. import reproduction as _reproduction
|
|
12
|
+
from .. import speciation as _speciation
|
|
13
|
+
from . import initialization, mutation, reproduction, speciation
|
|
14
|
+
from .backend import BACKEND, CpuBackend
|
|
15
|
+
from .mutation import mutate
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
'BACKEND', 'CpuBackend', 'initialize', 'initialization', 'mutate', 'mutation',
|
|
19
|
+
'reproduce', 'reproduction', 'speciate', 'speciation',
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def initialize(config: Config, module: NeatModule, tpb=1, verbose: bool | int = False):
|
|
24
|
+
return _initialization.initialize(BACKEND, config, module, tpb, verbose)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def reproduce(
|
|
28
|
+
config: Config, genera: list[int], modules: dict[int, NeatModule], population: dict[int, Genome],
|
|
29
|
+
ancestors: dict[int, tuple[Genome, Genome]], generation: int, to_delete: list[int], genome_indexer: int,
|
|
30
|
+
stagnation: Stagnation, species_set: SpeciesSet, reporters: ReporterSet,
|
|
31
|
+
tpb=1, verbose: bool | int = False):
|
|
32
|
+
return _reproduction.reproduce(
|
|
33
|
+
BACKEND, config, genera, modules, population, ancestors, generation, to_delete, genome_indexer,
|
|
34
|
+
stagnation, species_set, reporters, tpb, verbose
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def speciate(config: Config, genera: list[int], modules: dict[int, NeatModule],
|
|
39
|
+
species_set: SpeciesSet, population: dict[int, Genome],
|
|
40
|
+
generation: int, tpb=10, verbose: bool | int = False):
|
|
41
|
+
return _speciation.speciate(BACKEND, config, genera, modules, species_set, population, generation, tpb, verbose)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# Keep the old module level entry points (e.g. `base.cpu.reproduction.reproduce`) available
|
|
45
|
+
initialization.initialize = initialize
|
|
46
|
+
reproduction.reproduce = reproduce
|
|
47
|
+
speciation.speciate = speciate
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import gc
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from .. import seeding
|
|
6
|
+
from ..interface import Backend
|
|
7
|
+
from .functional import get_rng_states
|
|
8
|
+
from .initialization import initialize as _initialize_kernel
|
|
9
|
+
from .mutation import mutate as _mutate_kernel
|
|
10
|
+
from .reproduction import crossover as _crossover_kernel
|
|
11
|
+
from .speciation import compute_distances as _compute_distances
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CpuBackend(Backend):
|
|
15
|
+
"""Numba (prange) implementation of the device interface, running on numpy arrays."""
|
|
16
|
+
name = 'cpu'
|
|
17
|
+
xp = np
|
|
18
|
+
has_fallback = False
|
|
19
|
+
|
|
20
|
+
def asarray(self, array):
|
|
21
|
+
return np.asarray(array)
|
|
22
|
+
|
|
23
|
+
def zeros(self, shape: tuple):
|
|
24
|
+
return np.zeros(shape, np.float64)
|
|
25
|
+
|
|
26
|
+
def release(self):
|
|
27
|
+
gc.collect()
|
|
28
|
+
|
|
29
|
+
def uniform(self, shape: tuple):
|
|
30
|
+
return seeding.numpy_rng().random(size=shape)
|
|
31
|
+
|
|
32
|
+
def normal_states(self, kernel_shape: tuple, seed: int = None):
|
|
33
|
+
return get_rng_states(kernel_shape, seed, get_normal=True)
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def _check(ret_code: int, ndim: int):
|
|
37
|
+
if ret_code == 1: raise ValueError(f"Expected a 3D array, got {ndim}")
|
|
38
|
+
if ret_code == 2: raise ValueError("Out of bounds")
|
|
39
|
+
|
|
40
|
+
def initialize(self, array, init_type, mean, std, minimum, maximum, rng_states, kernel_shape, info=()):
|
|
41
|
+
try:
|
|
42
|
+
self._check(_initialize_kernel(array, init_type, mean, std, minimum, maximum, rng_states), array.ndim)
|
|
43
|
+
except Exception as e:
|
|
44
|
+
print(*info)
|
|
45
|
+
raise e
|
|
46
|
+
|
|
47
|
+
def crossover(self, genus, source, updates, parents, genera, filled, probabilities, equal_sources, kernel_shape):
|
|
48
|
+
self._check(
|
|
49
|
+
_crossover_kernel(genus, source, updates, parents, genera, filled, probabilities, equal_sources),
|
|
50
|
+
updates.ndim
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
def mutate(self, updates, children, *args, kernel_shape):
|
|
54
|
+
self._check(_mutate_kernel(updates, children, *args), updates.ndim)
|
|
55
|
+
|
|
56
|
+
def compute_distances(self, config, module, dtype, tpb, verbose: bool | int = False):
|
|
57
|
+
return _compute_distances(config, module, dtype, tpb, verbose)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
BACKEND = CpuBackend()
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""CPU (numba) helpers: RNG state sampling and element accessors. Device independent ones are re-exported from ``..functional``."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from numba import njit
|
|
5
|
+
from numpy import ndarray as CPUArray
|
|
6
|
+
|
|
7
|
+
from .. import seeding
|
|
8
|
+
from ..functional import calc, calc_grid, clamp, set_seed, threads_total # noqa: F401 (re-exported)
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"calc",
|
|
12
|
+
"calc_grid",
|
|
13
|
+
"clamp",
|
|
14
|
+
"gauss",
|
|
15
|
+
"get_enumeration",
|
|
16
|
+
"get_rng_states",
|
|
17
|
+
"normal",
|
|
18
|
+
"prob",
|
|
19
|
+
"set_seed",
|
|
20
|
+
"uniform",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get_rng_states(kernel_shape: tuple, seed: int = None, get_normal=True, dtype=np.float64) -> tuple[np.ndarray, int]:
|
|
25
|
+
# `seed` is applied through ``seeding.configure(config.general.seed)``; an explicit value re-seeds the backend
|
|
26
|
+
if seed is not None:
|
|
27
|
+
seeding.configure(seed)
|
|
28
|
+
rng = seeding.numpy_rng()
|
|
29
|
+
total = threads_total(kernel_shape)
|
|
30
|
+
if get_normal:
|
|
31
|
+
rng_states = rng.standard_normal(size=total).astype(dtype)
|
|
32
|
+
else:
|
|
33
|
+
rng_states = rng.random(size=total).astype(dtype)
|
|
34
|
+
return rng_states, total
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@njit(cache=True)
|
|
38
|
+
def gauss(states: CPUArray, index: int) -> float:
|
|
39
|
+
"""
|
|
40
|
+
Get the value at a given index for a Normal Distribution CPU Array
|
|
41
|
+
:param states: 1D CPUArray for all max possible threads
|
|
42
|
+
:param index: int
|
|
43
|
+
:return:
|
|
44
|
+
"""
|
|
45
|
+
return states[index]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@njit(cache=True)
|
|
49
|
+
def prob(states: CPUArray, index: int) -> float:
|
|
50
|
+
"""
|
|
51
|
+
Get the value at a given index for a Probability (Uniform[0, 1]) CPU Array
|
|
52
|
+
:param states: 1D CPUArray for all max possible threads
|
|
53
|
+
:param index: int
|
|
54
|
+
:return:
|
|
55
|
+
"""
|
|
56
|
+
return states[index]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@njit(cache=True)
|
|
60
|
+
def normal(states: CPUArray, index: int, mean: float, std: float) -> float:
|
|
61
|
+
return mean + gauss(states, index) * std
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@njit(cache=True)
|
|
65
|
+
def uniform(states: CPUArray, index: int, minimum: float, maximum: float) -> float:
|
|
66
|
+
difference = maximum - minimum
|
|
67
|
+
return minimum + prob(states, index) * difference
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@njit(cache=True)
|
|
71
|
+
def get_enumeration(array: CPUArray):
|
|
72
|
+
positions: list[tuple[int, ...]] = [index for index, value in np.ndenumerate(array)]
|
|
73
|
+
count = len(positions)
|
|
74
|
+
return positions, count
|