torch-population 0.0.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.
@@ -0,0 +1,70 @@
1
+ *.sh
2
+ data/
3
+
4
+ # Byte-compiled / optimized / DLL files
5
+ __pycache__/
6
+ *.py[codz]
7
+ *$py.class
8
+
9
+ # C extensions
10
+ *.so
11
+
12
+ # Distribution / packaging
13
+ .Python
14
+ build/
15
+ develop-eggs/
16
+ dist/
17
+ downloads/
18
+ eggs/
19
+ .eggs/
20
+ lib/
21
+ lib64/
22
+ parts/
23
+ sdist/
24
+ var/
25
+ wheels/
26
+ share/python-wheels/
27
+ *.egg-info/
28
+ .installed.cfg
29
+ *.egg
30
+ MANIFEST
31
+
32
+ # Unit test / coverage reports
33
+ htmlcov/
34
+ .tox/
35
+ .nox/
36
+ .coverage
37
+ .coverage.*
38
+ .cache
39
+ nosetests.xml
40
+ coverage.xml
41
+ *.cover
42
+ *.py.cover
43
+ *.lcov
44
+ .hypothesis/
45
+ .pytest_cache/
46
+ cover/
47
+
48
+ # Environments
49
+ .env
50
+ .envrc
51
+ .venv
52
+ env/
53
+ venv/
54
+ ENV/
55
+ env.bak/
56
+ venv.bak/
57
+
58
+ # Jupyter / IPython
59
+ .ipynb_checkpoints
60
+
61
+ # Type checkers & linters
62
+ .mypy_cache/
63
+ .dmypy.json
64
+ dmypy.json
65
+ .pyre/
66
+ .pytype/
67
+ .ruff_cache/
68
+
69
+ # PyPI configuration file
70
+ .pypirc
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 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,197 @@
1
+ Metadata-Version: 2.5
2
+ Name: torch-population
3
+ Version: 0.0.2
4
+ Summary: Minimal PyTorch wrapper for turning a single network into an ensemble or population
5
+ Project-URL: Homepage, https://pypi.org/project/torch-population/
6
+ Project-URL: Repository, https://github.com/lucidrains/torch-population
7
+ Author-email: Phil Wang <lucidrains@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2026 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,deep learning,ensemble,population,pytorch
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3.10
35
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
36
+ Requires-Python: >=3.10
37
+ Requires-Dist: einops>=0.8.1
38
+ Requires-Dist: torch>=2.5
39
+ Provides-Extra: examples
40
+ Requires-Dist: torchvision; extra == 'examples'
41
+ Provides-Extra: test
42
+ Requires-Dist: pytest; extra == 'test'
43
+ Description-Content-Type: text/markdown
44
+
45
+ ## torch-population
46
+
47
+ Colocated population and ensemble wrapper for PyTorch. Parameters, buffers, and any `torch.optim.Optimizer` state live together in one flat `PopulationParameters` container.
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ $ pip install torch-population
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ ### Simple: noop wrapper, population & indexing
58
+
59
+ ```python
60
+ import torch
61
+ from torch import nn
62
+ from torch_population import Population
63
+
64
+ net = nn.Sequential(nn.Linear(16, 32), nn.SiLU(), nn.Linear(32, 4))
65
+ x = torch.randn(8, 16)
66
+
67
+ # zero-overhead noop wrapper (exact param aliasing)
68
+
69
+ pop = Population(net)
70
+ assert pop.unwrap() is net
71
+
72
+ # turn into a vectorized population (or call pop.populate(4))
73
+
74
+ pop = Population(net, pop_size = 4)
75
+
76
+ out = pop(x) # (4, 8, 4) shared input
77
+ out = pop(torch.randn(4, 8, 16), per_individual = True) # (4, 8, 4) per-individual input
78
+
79
+ # index out an individual as a standard single nn.Module and write it back
80
+
81
+ ind = pop[0]
82
+ assert ind(x).shape == (8, 4)
83
+ pop[0] = ind
84
+ ```
85
+
86
+ ### Colocated optimizers (works with any `torch.optim.Optimizer`) & solo checkout
87
+
88
+ ```python
89
+ # wrap any torch.optim.Optimizer class (built-in or custom)
90
+
91
+ opt = pop.optimizer(torch.optim.RMSprop, lr = 1e-3, shared = False)
92
+ # opt = pop.optimizer(AnyOptimizer, lr = 1e-3, shared = True) # 1/P shared state
93
+ # opt = pop.optimizer(AnyOptimizer, lr = [1e-4, 3e-4, 1e-3, 3e-3]) # per-individual HPs
94
+
95
+ opt.zero_grad()
96
+ pop(x).pow(2).mean().backward()
97
+ opt.step()
98
+
99
+ # toggle state sharing across the population at runtime
100
+ # share() reduces the P separate states along the pop dim (default 'mean'; also 'max', 'min', 'sum', 'first', 'zero', member index, callable, or per-key dict)
101
+
102
+ opt.share(reduce = 'mean') # or opt.share(reduce = {'square_avg': 'max', 'step': 'max'})
103
+ opt.unshare() # broadcasts shared state back to P independent slots
104
+
105
+ # extract one individual + its native torch.optim.Optimizer, train solo, write both back in
106
+
107
+ ind, ind_opt = pop.extract(2)
108
+ ind_opt.zero_grad()
109
+ ind(x).pow(2).mean().backward()
110
+ ind_opt.step()
111
+ pop[2] = (ind, ind_opt)
112
+
113
+ # or with a context manager
114
+
115
+ with pop.checkout(2) as (ind, ind_opt):
116
+ ind_opt.zero_grad()
117
+ ind(x).pow(2).mean().backward()
118
+ ind_opt.step()
119
+ ```
120
+
121
+ ### Unified `PopulationParameters`, PyTorch dicts & lifecycle
122
+
123
+ ```python
124
+ pp = pop.population_parameters
125
+
126
+ pp.flat_params # (4, D) contiguous parameters
127
+ pp.named_optimizer_state() # zero-copy views into colocated optimizer state
128
+
129
+ # single-individual PyTorch-compatible dict (zero-copy views; clone = True to copy)
130
+
131
+ ind_dict = pp[2] # {'parameters', 'named_parameters', 'buffers', 'state_dict', 'optimizer_state', ...}
132
+ pop_dict = pp.as_dict()
133
+
134
+ # shared layers, subset forward, dynamic resizing & population soup
135
+
136
+ pop = Population(net, pop_size = 4, shared = ('0.bias',))
137
+ opt = pop.optimizer(torch.optim.RMSprop, lr = 1e-3)
138
+
139
+ sub_out = pop(x, members = (0, 2)) # (2, 8, 4)
140
+
141
+ pop.reset_(torch.tensor([True, False, False, False])) # reinit masked params + buffers + opt state
142
+ pop.replace(3, 0, reset_opt = True) # copy member 0 into slot 3
143
+ pop.delete(1) # P: 4 -> 3 in lockstep across params & opt state
144
+ pop.append(0) # P: 3 -> 4
145
+ avg_net = pop.mean() # standalone nn.Module with averaged weights
146
+ ```
147
+
148
+ ### Differentiable meta-learning & multi-loss gradient control (`autograd`, `functional_step`)
149
+
150
+ ```python
151
+ pop = Population(net, pop_size = 4)
152
+ opt = pop.optimizer(torch.optim.RMSprop, lr = 1e-3, shared = False)
153
+ pp = pop.population_parameters
154
+ ema_pp = pp.clone(include_opt = False)
155
+
156
+ cur_pp = pp
157
+ for _ in range(2):
158
+ inner_loss = pop(x, params = cur_pp).pow(2).mean()
159
+ cur_pp = opt.functional_step(inner_loss, cur_pp, create_graph = True)
160
+
161
+ meta_loss = pop(x, params = cur_pp).pow(2).mean()
162
+ meta_loss.backward() # gradients flow through inner optimizer updates
163
+
164
+ pp.copy_from_(cur_pp.detach())
165
+ ema_pp.lerp_(pp, 0.05)
166
+
167
+ # multi-loss / PCGrad / custom gradient lanes (works with both step() and functional_step())
168
+
169
+ g_task = pp.autograd(loss_task, retain_graph = True) # {name: (P, ...)} scoped via names=
170
+ g_aux = pp.autograd(loss_aux)
171
+ opt.step(grads = {k: g_task[k] + 0.5 * g_aux[k] for k in g_task})
172
+ ```
173
+
174
+ ### Example: train 10 MNIST networks in parallel
175
+
176
+ ```bash
177
+ $ python train_pop_mnist.py
178
+ ```
179
+
180
+ ## Tests
181
+
182
+ ```bash
183
+ $ pytest
184
+ ```
185
+
186
+ ## Citations
187
+
188
+ ```bibtex
189
+ @inproceedings{anonymous2026continual,
190
+ title = {Continual Reinforcement Learning with Neuroevolution},
191
+ author = {Anonymous},
192
+ booktitle = {Submitted to The Fifteenth International Conference on Learning Representations},
193
+ year = {2026},
194
+ url = {https://openreview.net/forum?id=UxsGk4on0e},
195
+ note = {under review}
196
+ }
197
+ ```
@@ -0,0 +1,153 @@
1
+ ## torch-population
2
+
3
+ Colocated population and ensemble wrapper for PyTorch. Parameters, buffers, and any `torch.optim.Optimizer` state live together in one flat `PopulationParameters` container.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ $ pip install torch-population
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Simple: noop wrapper, population & indexing
14
+
15
+ ```python
16
+ import torch
17
+ from torch import nn
18
+ from torch_population import Population
19
+
20
+ net = nn.Sequential(nn.Linear(16, 32), nn.SiLU(), nn.Linear(32, 4))
21
+ x = torch.randn(8, 16)
22
+
23
+ # zero-overhead noop wrapper (exact param aliasing)
24
+
25
+ pop = Population(net)
26
+ assert pop.unwrap() is net
27
+
28
+ # turn into a vectorized population (or call pop.populate(4))
29
+
30
+ pop = Population(net, pop_size = 4)
31
+
32
+ out = pop(x) # (4, 8, 4) shared input
33
+ out = pop(torch.randn(4, 8, 16), per_individual = True) # (4, 8, 4) per-individual input
34
+
35
+ # index out an individual as a standard single nn.Module and write it back
36
+
37
+ ind = pop[0]
38
+ assert ind(x).shape == (8, 4)
39
+ pop[0] = ind
40
+ ```
41
+
42
+ ### Colocated optimizers (works with any `torch.optim.Optimizer`) & solo checkout
43
+
44
+ ```python
45
+ # wrap any torch.optim.Optimizer class (built-in or custom)
46
+
47
+ opt = pop.optimizer(torch.optim.RMSprop, lr = 1e-3, shared = False)
48
+ # opt = pop.optimizer(AnyOptimizer, lr = 1e-3, shared = True) # 1/P shared state
49
+ # opt = pop.optimizer(AnyOptimizer, lr = [1e-4, 3e-4, 1e-3, 3e-3]) # per-individual HPs
50
+
51
+ opt.zero_grad()
52
+ pop(x).pow(2).mean().backward()
53
+ opt.step()
54
+
55
+ # toggle state sharing across the population at runtime
56
+ # share() reduces the P separate states along the pop dim (default 'mean'; also 'max', 'min', 'sum', 'first', 'zero', member index, callable, or per-key dict)
57
+
58
+ opt.share(reduce = 'mean') # or opt.share(reduce = {'square_avg': 'max', 'step': 'max'})
59
+ opt.unshare() # broadcasts shared state back to P independent slots
60
+
61
+ # extract one individual + its native torch.optim.Optimizer, train solo, write both back in
62
+
63
+ ind, ind_opt = pop.extract(2)
64
+ ind_opt.zero_grad()
65
+ ind(x).pow(2).mean().backward()
66
+ ind_opt.step()
67
+ pop[2] = (ind, ind_opt)
68
+
69
+ # or with a context manager
70
+
71
+ with pop.checkout(2) as (ind, ind_opt):
72
+ ind_opt.zero_grad()
73
+ ind(x).pow(2).mean().backward()
74
+ ind_opt.step()
75
+ ```
76
+
77
+ ### Unified `PopulationParameters`, PyTorch dicts & lifecycle
78
+
79
+ ```python
80
+ pp = pop.population_parameters
81
+
82
+ pp.flat_params # (4, D) contiguous parameters
83
+ pp.named_optimizer_state() # zero-copy views into colocated optimizer state
84
+
85
+ # single-individual PyTorch-compatible dict (zero-copy views; clone = True to copy)
86
+
87
+ ind_dict = pp[2] # {'parameters', 'named_parameters', 'buffers', 'state_dict', 'optimizer_state', ...}
88
+ pop_dict = pp.as_dict()
89
+
90
+ # shared layers, subset forward, dynamic resizing & population soup
91
+
92
+ pop = Population(net, pop_size = 4, shared = ('0.bias',))
93
+ opt = pop.optimizer(torch.optim.RMSprop, lr = 1e-3)
94
+
95
+ sub_out = pop(x, members = (0, 2)) # (2, 8, 4)
96
+
97
+ pop.reset_(torch.tensor([True, False, False, False])) # reinit masked params + buffers + opt state
98
+ pop.replace(3, 0, reset_opt = True) # copy member 0 into slot 3
99
+ pop.delete(1) # P: 4 -> 3 in lockstep across params & opt state
100
+ pop.append(0) # P: 3 -> 4
101
+ avg_net = pop.mean() # standalone nn.Module with averaged weights
102
+ ```
103
+
104
+ ### Differentiable meta-learning & multi-loss gradient control (`autograd`, `functional_step`)
105
+
106
+ ```python
107
+ pop = Population(net, pop_size = 4)
108
+ opt = pop.optimizer(torch.optim.RMSprop, lr = 1e-3, shared = False)
109
+ pp = pop.population_parameters
110
+ ema_pp = pp.clone(include_opt = False)
111
+
112
+ cur_pp = pp
113
+ for _ in range(2):
114
+ inner_loss = pop(x, params = cur_pp).pow(2).mean()
115
+ cur_pp = opt.functional_step(inner_loss, cur_pp, create_graph = True)
116
+
117
+ meta_loss = pop(x, params = cur_pp).pow(2).mean()
118
+ meta_loss.backward() # gradients flow through inner optimizer updates
119
+
120
+ pp.copy_from_(cur_pp.detach())
121
+ ema_pp.lerp_(pp, 0.05)
122
+
123
+ # multi-loss / PCGrad / custom gradient lanes (works with both step() and functional_step())
124
+
125
+ g_task = pp.autograd(loss_task, retain_graph = True) # {name: (P, ...)} scoped via names=
126
+ g_aux = pp.autograd(loss_aux)
127
+ opt.step(grads = {k: g_task[k] + 0.5 * g_aux[k] for k in g_task})
128
+ ```
129
+
130
+ ### Example: train 10 MNIST networks in parallel
131
+
132
+ ```bash
133
+ $ python train_pop_mnist.py
134
+ ```
135
+
136
+ ## Tests
137
+
138
+ ```bash
139
+ $ pytest
140
+ ```
141
+
142
+ ## Citations
143
+
144
+ ```bibtex
145
+ @inproceedings{anonymous2026continual,
146
+ title = {Continual Reinforcement Learning with Neuroevolution},
147
+ author = {Anonymous},
148
+ booktitle = {Submitted to The Fifteenth International Conference on Learning Representations},
149
+ year = {2026},
150
+ url = {https://openreview.net/forum?id=UxsGk4on0e},
151
+ note = {under review}
152
+ }
153
+ ```
@@ -0,0 +1,69 @@
1
+ [project]
2
+ name = "torch-population"
3
+ version = "0.0.2"
4
+ description = "Minimal PyTorch wrapper for turning a single network into an ensemble or population"
5
+ authors = [
6
+ { name = "Phil Wang", email = "lucidrains@gmail.com" }
7
+ ]
8
+ readme = "README.md"
9
+ requires-python = ">= 3.10"
10
+ license = { file = "LICENSE" }
11
+ keywords = [
12
+ 'artificial intelligence',
13
+ 'deep learning',
14
+ 'pytorch',
15
+ 'ensemble',
16
+ 'population'
17
+ ]
18
+
19
+ classifiers=[
20
+ 'Development Status :: 4 - Beta',
21
+ 'Intended Audience :: Developers',
22
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
23
+ 'License :: OSI Approved :: MIT License',
24
+ 'Programming Language :: Python :: 3.10',
25
+ ]
26
+
27
+ dependencies = [
28
+ "einops>=0.8.1",
29
+ "torch>=2.5"
30
+ ]
31
+
32
+ [project.urls]
33
+ Homepage = "https://pypi.org/project/torch-population/"
34
+ Repository = "https://github.com/lucidrains/torch-population"
35
+
36
+ [project.optional-dependencies]
37
+ examples = [
38
+ "torchvision"
39
+ ]
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]
61
+ include = [
62
+ "torch_population",
63
+ "pyproject.toml",
64
+ "README.md",
65
+ "LICENSE"
66
+ ]
67
+
68
+ [tool.hatch.build.targets.wheel]
69
+ packages = ["torch_population"]
@@ -0,0 +1,15 @@
1
+ from torch_population.optimizer import PopulationOptimizer
2
+ from torch_population.parameters import PopulationParameters
3
+ from torch_population.store import OptStore, ParamSlot, TensorSpec, TensorStore
4
+ from torch_population.torch_population import Population, PopulationView
5
+
6
+ __all__ = [
7
+ 'OptStore',
8
+ 'ParamSlot',
9
+ 'Population',
10
+ 'PopulationOptimizer',
11
+ 'PopulationParameters',
12
+ 'PopulationView',
13
+ 'TensorSpec',
14
+ 'TensorStore',
15
+ ]