evograd-diff 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.
Files changed (55) hide show
  1. evograd_diff-0.1.0/.claude/settings.local.json +12 -0
  2. evograd_diff-0.1.0/.python-version +1 -0
  3. evograd_diff-0.1.0/LICENSE +201 -0
  4. evograd_diff-0.1.0/PKG-INFO +439 -0
  5. evograd_diff-0.1.0/README.md +412 -0
  6. evograd_diff-0.1.0/Test_new_evograd.ipynb +31427 -0
  7. evograd_diff-0.1.0/evograd/__init__.py +67 -0
  8. evograd_diff-0.1.0/evograd/algorithms/__init__.py +138 -0
  9. evograd_diff-0.1.0/evograd/algorithms/cmaes.py +1365 -0
  10. evograd_diff-0.1.0/evograd/algorithms/de.py +895 -0
  11. evograd_diff-0.1.0/evograd/algorithms/ga.py +532 -0
  12. evograd_diff-0.1.0/evograd/algorithms/pso.py +648 -0
  13. evograd_diff-0.1.0/evograd/algorithms/shade.py +1165 -0
  14. evograd_diff-0.1.0/evograd/benchmarks/functions/__init__.py +229 -0
  15. evograd_diff-0.1.0/evograd/benchmarks/functions/base.py +217 -0
  16. evograd_diff-0.1.0/evograd/benchmarks/functions/cec2017/__init__.py +250 -0
  17. evograd_diff-0.1.0/evograd/benchmarks/functions/cec2017/basic.py +413 -0
  18. evograd_diff-0.1.0/evograd/benchmarks/functions/cec2017/composition.py +580 -0
  19. evograd_diff-0.1.0/evograd/benchmarks/functions/cec2017/data.pkl +0 -0
  20. evograd_diff-0.1.0/evograd/benchmarks/functions/cec2017/data.py +350 -0
  21. evograd_diff-0.1.0/evograd/benchmarks/functions/cec2017/hybrid.py +406 -0
  22. evograd_diff-0.1.0/evograd/benchmarks/functions/cec2017/simple.py +326 -0
  23. evograd_diff-0.1.0/evograd/benchmarks/functions/classical.py +649 -0
  24. evograd_diff-0.1.0/evograd/benchmarks/functions/smoothed_funnel.py +476 -0
  25. evograd_diff-0.1.0/evograd/benchmarks/functions/transforms.py +463 -0
  26. evograd_diff-0.1.0/evograd/benchmarks/run_benchmark_functions.py +1208 -0
  27. evograd_diff-0.1.0/evograd/core/__init__.py +73 -0
  28. evograd_diff-0.1.0/evograd/core/algorithm.py +778 -0
  29. evograd_diff-0.1.0/evograd/core/maximize.py +269 -0
  30. evograd_diff-0.1.0/evograd/core/minimize.py +740 -0
  31. evograd_diff-0.1.0/evograd/core/problem.py +444 -0
  32. evograd_diff-0.1.0/evograd/core/result.py +571 -0
  33. evograd_diff-0.1.0/evograd/core/termination.py +602 -0
  34. evograd_diff-0.1.0/evograd/operators/__init__.py +178 -0
  35. evograd_diff-0.1.0/evograd/operators/crossover.py +1117 -0
  36. evograd_diff-0.1.0/evograd/operators/mutation.py +1098 -0
  37. evograd_diff-0.1.0/evograd/operators/relaxations.py +175 -0
  38. evograd_diff-0.1.0/evograd/operators/repair.py +601 -0
  39. evograd_diff-0.1.0/evograd/operators/sampling.py +577 -0
  40. evograd_diff-0.1.0/evograd/operators/selection.py +981 -0
  41. evograd_diff-0.1.0/evograd/operators/survival.py +1000 -0
  42. evograd_diff-0.1.0/evograd/tests/__init__.py +11 -0
  43. evograd_diff-0.1.0/evograd/tests/run_all.py +78 -0
  44. evograd_diff-0.1.0/evograd/tests/test_core.py +528 -0
  45. evograd_diff-0.1.0/evograd/tests/test_ga.py +572 -0
  46. evograd_diff-0.1.0/evograd/tests/test_operators.py +662 -0
  47. evograd_diff-0.1.0/evograd/tests/test_per_individual.py +326 -0
  48. evograd_diff-0.1.0/evograd/tests/test_utils.py +328 -0
  49. evograd_diff-0.1.0/evograd/utils/__init__.py +97 -0
  50. evograd_diff-0.1.0/evograd/utils/callbacks.py +926 -0
  51. evograd_diff-0.1.0/evograd/utils/device.py +502 -0
  52. evograd_diff-0.1.0/evograd/utils/duplicates.py +421 -0
  53. evograd_diff-0.1.0/plot_benchmarks.py +896 -0
  54. evograd_diff-0.1.0/pyproject.toml +53 -0
  55. evograd_diff-0.1.0/uv.lock +1014 -0
@@ -0,0 +1,12 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(git add *)",
5
+ "Bash(git commit -m ' *)",
6
+ "Bash(git push *)",
7
+ "Bash(uv build *)",
8
+ "Bash(python -m zipfile -l dist/evograd-0.1.0-py3-none-any.whl)",
9
+ "WebFetch(domain:pypi.org)"
10
+ ]
11
+ }
12
+ }
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,439 @@
1
+ Metadata-Version: 2.4
2
+ Name: evograd-diff
3
+ Version: 0.1.0
4
+ Summary: PyTorch-based framework for differentiable evolutionary computation and swarm intelligence
5
+ Project-URL: Homepage, https://github.com/andreatangherloni/EvoGrad
6
+ Project-URL: Repository, https://github.com/andreatangherloni/EvoGrad
7
+ Project-URL: Issues, https://github.com/andreatangherloni/EvoGrad/issues
8
+ Author-email: Andrea Tangherloni <andrea.tangherloni@unibocconi.it>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: CMA-ES,differentiable programming,differential evolution,evolutionary computation,genetic algorithm,metaheuristics,optimization,particle swarm optimization,pytorch
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: matplotlib>=3.10.8
21
+ Requires-Dist: numpy>=2.4.4
22
+ Requires-Dist: pandas>=3.0.2
23
+ Requires-Dist: scipy>=1.17.1
24
+ Requires-Dist: seaborn>=0.13.2
25
+ Requires-Dist: torch>=2.11.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # EvoGrad: Metaheuristics in a Differentiable Wonderland
29
+
30
+ <p align="center">
31
+ <img src="https://img.shields.io/badge/python-3.9+-blue.svg" alt="Python 3.9+">
32
+ <img src="https://img.shields.io/badge/pytorch-2.0+-orange.svg" alt="PyTorch 2.0+">
33
+ <img src="https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg" alt="License: Apache-2.0">
34
+
35
+ </p>
36
+
37
+ **EvoGrad** is a PyTorch-based framework for differentiable Evolutionary Computation and Swarm Intelligence. It bridges classical population-based optimisation with modern differentiable programming by enabling gradient flow through evolutionary operators.
38
+
39
+ ## 🌟 Key Features
40
+
41
+ - **Fully Differentiable**: All operators support gradient computation via reparameterisation tricks (Gumbel-Softmax, Binary-Concrete, pathwise gradients)
42
+ - **GPU Accelerated**: Native PyTorch implementation for seamless CPU/GPU/MPS execution
43
+ - **Modular Design**: Dependency injection pattern inspired by [pymoo](https://pymoo.org/) for flexible operator composition
44
+ - **Learnable Hyperparameters**: Automatically tune algorithm parameters via backpropagation
45
+ - **Four Algorithms**: GA, DE, PSO, and CMA-ES with multiple variants
46
+
47
+ ## 📦 Installation
48
+
49
+ ```bash
50
+ # Clone the repository
51
+ git clone https://github.com/YOUR_USERNAME/evograd.git
52
+ cd evograd
53
+
54
+ # Install dependencies
55
+ pip install torch numpy
56
+
57
+ # Install in development mode
58
+ pip install -e .
59
+ ```
60
+
61
+ ## 🚀 Quick Start
62
+
63
+ ```python
64
+ import torch
65
+ from evograd.core import Problem, minimize
66
+ from evograd.algorithms import GA, DE, PSO, CMAES
67
+
68
+ # Define an optimisation problem
69
+ problem = Problem(
70
+ objective=lambda x: (x**2).sum(dim=-1), # Sphere function
71
+ n_var=30,
72
+ xl=-100.0,
73
+ xu=100.0,
74
+ )
75
+
76
+ # Run with Genetic Algorithm
77
+ ga = GA(pop_size=100, differentiable=True)
78
+ result = minimize(problem, ga, max_evals=10000, seed=42)
79
+ print(f"GA Best: {result.best_fitness:.6f}")
80
+
81
+ # Run with Differential Evolution
82
+ de = DE(pop_size=100, variant="DE/rand/1/bin", adaptive=True)
83
+ result = minimize(problem, de, max_evals=10000, seed=42)
84
+ print(f"DE Best: {result.best_fitness:.6f}")
85
+
86
+ # Run with Particle Swarm Optimisation
87
+ pso = PSO(pop_size=100, adaptive=True, differentiable=True)
88
+ result = minimize(problem, pso, max_evals=10000, seed=42)
89
+ print(f"PSO Best: {result.best_fitness:.6f}")
90
+
91
+ # Run with CMA-ES
92
+ cmaes = CMAES(sigma=0.5, adaptive=True)
93
+ result = minimize(problem, cmaes, max_evals=10000, seed=42)
94
+ print(f"CMA-ES Best: {result.best_fitness:.6f}")
95
+ ```
96
+
97
+ ## 🔧 Algorithms and Operating Modes
98
+
99
+ ### Genetic Algorithm (GA)
100
+
101
+ The GA uses **operator-level differentiability**. Each operator (selection, crossover, mutation, survival) can independently be set to differentiable mode:
102
+
103
+ ```python
104
+ from evograd.algorithms import GA
105
+ from evograd.operators import (
106
+ RouletteSelection,
107
+ SBXCrossover,
108
+ PolynomialMutation,
109
+ MergeSurvival,
110
+ )
111
+
112
+ # Classical GA (no gradients)
113
+ ga = GA(pop_size=100, differentiable=False)
114
+
115
+ # Fully differentiable GA with custom operators
116
+ ga = GA(
117
+ pop_size=100,
118
+ selection=RouletteSelection(differentiable=True, learn_temperature=True),
119
+ crossover=SBXCrossover(differentiable=True, learn_eta=True, learn_prob=True),
120
+ mutation=PolynomialMutation(differentiable=True, learn_eta=True, learn_prob=True),
121
+ survival=MergeSurvival(selection=RouletteSelection(differentiable=True)),
122
+ differentiable=True, # Makes population learnable
123
+ )
124
+ ```
125
+
126
+ | Parameter | Effect |
127
+ |-----------|--------|
128
+ | `differentiable=False` | Classical GA with discrete operators |
129
+ | `differentiable=True` | Population is an `nn.Parameter` (learnable via backprop) |
130
+ | Operator `differentiable=True` | Operator uses Gumbel-Softmax/Binary-Concrete for gradient flow |
131
+ | Operator `learn_*=True` | Operator hyperparameters become learnable `nn.Parameter` |
132
+
133
+ ### Differential Evolution (DE)
134
+
135
+ DE uses **algorithm-level flags** for adaptive hyperparameters and differentiable population:
136
+
137
+ ```python
138
+ from evograd.algorithms import DE, de_rand_1_bin, de_best_1_bin
139
+
140
+ # Classical DE
141
+ de = DE(pop_size=100, variant="DE/rand/1/bin", F=0.5, CR=0.9)
142
+
143
+ # Adaptive DE (learnable F, CR, selection temperature)
144
+ de = DE(pop_size=100, variant="DE/best/1/bin", adaptive=True)
145
+
146
+ # Differentiable population
147
+ de = DE(pop_size=100, variant="DE/rand/1/bin", differentiable=True)
148
+
149
+ # Both adaptive and differentiable
150
+ de = DE(pop_size=100, variant="DE/current-to-best/1/bin", adaptive=True, differentiable=True)
151
+ ```
152
+
153
+ | `adaptive` | `differentiable` | Effect |
154
+ |------------|------------------|--------|
155
+ | False | False | Classical DE |
156
+ | True | False | F, CR, temperatures learnable via backprop |
157
+ | False | True | Population learnable via backprop |
158
+ | True | True | Both hyperparameters and population learnable |
159
+
160
+ **Supported Variants:**
161
+ - `DE/rand/1/bin`, `DE/rand/1/exp`, `DE/rand/2/bin`, `DE/rand/2/exp`
162
+ - `DE/best/1/bin`, `DE/best/1/exp`, `DE/best/2/bin`, `DE/best/2/exp`
163
+ - `DE/current-to-best/1/bin`, `DE/current-to-best/1/exp`
164
+ - `DE/current-to-rand/1`
165
+
166
+ ### Particle Swarm Optimisation (PSO)
167
+
168
+ PSO uses the same **algorithm-level flags** as DE:
169
+
170
+ ```python
171
+ from evograd.algorithms import PSO, pso_constriction, pso_adaptive
172
+
173
+ # Classical PSO
174
+ pso = PSO(pop_size=100, inertia=0.7, c1=1.5, c2=1.5)
175
+
176
+ # Adaptive PSO (learnable inertia, c1, c2)
177
+ pso = PSO(pop_size=100, adaptive=True)
178
+
179
+ # Per-particle adaptive coefficients
180
+ pso = PSO(pop_size=100, adaptive=True, per_particle_coeffs=True)
181
+
182
+ # Constriction factor PSO
183
+ pso = pso_constriction(pop_size=100)
184
+
185
+ # Fully differentiable
186
+ pso = PSO(pop_size=100, adaptive=True, differentiable=True)
187
+ ```
188
+
189
+ | `adaptive` | `differentiable` | Effect |
190
+ |------------|------------------|--------|
191
+ | False | False | Classical PSO |
192
+ | True | False | Inertia, c1, c2 learnable via backprop |
193
+ | False | True | Particle positions learnable via backprop |
194
+ | True | True | Both coefficients and positions learnable |
195
+
196
+ ### CMA-ES
197
+
198
+ CMA-ES supports **adaptive coefficients** and **restart strategies** (IPOP/BIPOP):
199
+
200
+ ```python
201
+ from evograd.algorithms import CMAES, cmaes_ipop, cmaes_bipop
202
+
203
+ # Classical CMA-ES
204
+ cmaes = CMAES(pop_size=50, sigma=0.5)
205
+
206
+ # Adaptive CMA-ES (learnable cc, cs, c1, cmu, damps)
207
+ cmaes = CMAES(pop_size=50, sigma=0.5, adaptive=True)
208
+
209
+ # Differentiable mean
210
+ cmaes = CMAES(pop_size=50, sigma=0.5, differentiable=True)
211
+
212
+ # IPOP-CMA-ES (increasing population restarts)
213
+ cmaes = cmaes_ipop(restarts=9, incpopsize=2)
214
+
215
+ # BIPOP-CMA-ES (alternating small/large populations)
216
+ cmaes = cmaes_bipop(restarts=9)
217
+ ```
218
+
219
+ | `adaptive` | `differentiable` | Effect |
220
+ |------------|------------------|--------|
221
+ | False | False | Classical CMA-ES |
222
+ | True | False | Adaptation coefficients learnable via backprop |
223
+ | False | True | Distribution mean μ learnable via backprop |
224
+ | True | True | Both coefficients and mean learnable |
225
+
226
+ **Restart Strategies:**
227
+ - **IPOP**: Restart with doubled population after convergence
228
+ - **BIPOP**: Alternate between small (focused) and large (exploratory) populations
229
+
230
+ ## 📚 Operators Library
231
+
232
+ EvoGrad provides a comprehensive library of evolutionary operators:
233
+
234
+ ### Selection
235
+ | Operator | Description | Differentiable |
236
+ |----------|-------------|----------------|
237
+ | `RandomSelection` | Uniform random selection | ✗ |
238
+ | `RouletteSelection` | Fitness-proportionate (Gumbel-Softmax) | ✓ |
239
+ | `TournamentSelection` | Tournament with soft winner (Gumbel-Softmax) | ✓ |
240
+ | `RankSelection` | Rank-based probabilities | ✓ |
241
+ | `StochasticUniversalSampling` | SUS with soft selection | ✓ |
242
+
243
+ ### Crossover
244
+ | Operator | Description | Differentiable |
245
+ |----------|-------------|----------------|
246
+ | `SBXCrossover` | Simulated Binary Crossover | ✓ |
247
+ | `BinomialCrossover` | DE-style binomial | ✓ |
248
+ | `ExponentialCrossover` | DE-style exponential | ✓ |
249
+ | `BlendCrossover` | BLX-α crossover | ✓ |
250
+ | `ArithmeticCrossover` | Weighted average | ✓ |
251
+ | `UniformCrossover` | Gene-wise uniform swap | ✓ |
252
+ | `SimulatedBinaryCrossover` | Alias for SBX | ✓ |
253
+
254
+ ### Mutation
255
+ | Operator | Description | Differentiable |
256
+ |----------|-------------|----------------|
257
+ | `PolynomialMutation` | Polynomial bounded mutation | ✓ |
258
+ | `GaussianMutation` | Additive Gaussian noise | ✓ |
259
+ | `UniformMutation` | Uniform random replacement | ✓ |
260
+ | `AdaptiveMutation` | Self-adaptive mutation rates | ✓ |
261
+
262
+ ### Survival
263
+ | Operator | Description |
264
+ |----------|-------------|
265
+ | `MergeSurvival` | (μ+λ) with optional elitism |
266
+ | `ReplacementSurvival` | (μ,λ) generational replacement |
267
+ | `AgingSurvival` | Age-based replacement |
268
+ | `FitnessSurvival` | Pure fitness-based truncation |
269
+
270
+ ### Repair
271
+ | Operator | Description |
272
+ |----------|-------------|
273
+ | `BoundsRepair` | Clamp to bounds |
274
+ | `ReflectionRepair` | Bounce off boundaries |
275
+ | `WrapRepair` | Toroidal wrap-around |
276
+ | `RandomRepair` | Random resampling |
277
+
278
+ ## 🎯 Advanced Usage
279
+
280
+ ### Training Neural Networks with EvoGrad
281
+
282
+ ```python
283
+ import torch
284
+ import torch.nn as nn
285
+ from evograd.algorithms import CMAES
286
+ from evograd.core import Problem
287
+ from evograd.core.termination import MaxEvaluations
288
+
289
+
290
+ # Define a simple MLP
291
+ class MLP(nn.Module):
292
+ def __init__(self):
293
+ super().__init__()
294
+ self.net = nn.Sequential(
295
+ nn.Linear(10, 64),
296
+ nn.Tanh(),
297
+ nn.Linear(64, 1),
298
+ )
299
+
300
+ def forward(self, x):
301
+ return self.net(x)
302
+
303
+ # Flatten parameters for optimisation
304
+ model = MLP()
305
+ n_params = sum(p.numel() for p in model.parameters())
306
+
307
+ def loss_fn(params):
308
+ # Reshape flat params back to model
309
+ idx = 0
310
+ for p in model.parameters():
311
+ numel = p.numel()
312
+ p.data.copy_(params[idx:idx+numel].view(p.shape))
313
+ idx += numel
314
+
315
+ # Compute loss on dummy data
316
+ x = torch.randn(32, 10)
317
+ y = torch.randn(32, 1)
318
+ pred = model(x)
319
+ return ((pred - y)**2).mean()
320
+
321
+ # Batch evaluation
322
+ def batch_loss(pop):
323
+ return torch.stack([loss_fn(p) for p in pop])
324
+
325
+ problem = Problem(
326
+ objective=batch_loss,
327
+ n_var=n_params,
328
+ xl=-10.0,
329
+ xu=10.0,
330
+ )
331
+
332
+ cmaes = CMAES(pop_size=50, sigma=1.0, adaptive=True)
333
+ result = minimize(problem, cmaes, MaxEvaluations(10000))
334
+ print(f"Final loss: {result.best_fitness:.6f}")
335
+ ```
336
+
337
+ ### Callbacks for Logging
338
+
339
+ ```python
340
+ from evograd.core import minimize
341
+ from evograd.utils import HistoryCallback, PrintCallback
342
+
343
+ callbacks = [
344
+ PrintCallback(every=10), # Print progress every 10 generations
345
+ HistoryCallback(), # Record full history
346
+ ]
347
+
348
+ result = minimize(problem, algorithm, termination=MaxEvaluations(10000), callback=callbacks)
349
+
350
+ # Access history
351
+ print(f"Fitness over time: {result.history['best_fitness']}")
352
+ ```
353
+
354
+ ## 🏗️ Architecture
355
+
356
+ ```
357
+ evograd/
358
+ ├── algorithms/
359
+ │ └── cmaes.py # CMA-ES with IPOP/BIPOP
360
+ │ ├── de.py # Differential Evolution
361
+ │ ├── ga.py # Genetic Algorithm
362
+ │ ├── pso.py # Particle Swarm Optimisation
363
+ ├── core/
364
+ │ ├── algorithm.py # Base Algorithm class
365
+ │ ├── maximize.py # Optimisation loop (maximisation)
366
+ │ ├── minimize.py # Optimisation loop (minimisation)
367
+ │ ├── problem.py # Problem definition
368
+ │ ├── result.py # Result container
369
+ │ └── termination.py # Stopping criteria
370
+ ├── operators/
371
+ │ ├── crossover.py # Crossover operators
372
+ │ ├── mutation.py # Mutation operators
373
+ │ ├── sampling.py # Sampling operators
374
+ │ ├── selection.py # Selection operators
375
+ │ ├── survival.py # Survival/replacement
376
+ │ └── repair.py # Constraint handling
377
+ └── utils/
378
+ ├── callbacks.py # Logging utilities
379
+ ├── device.py # Device management
380
+ └── duplicates.py # Duplicate elimination
381
+ ```
382
+
383
+ ## 🔬 How It Works
384
+
385
+ EvoGrad makes evolutionary algorithms differentiable through:
386
+
387
+ 1. **Reparameterisation Trick**: Convert random sampling into deterministic transformations of parameter-free noise:
388
+ ```
389
+ x = g_θ(ε), ε ~ p(ε) → ∇_θ L ≈ ∇_θ f(g_θ(ε))
390
+ ```
391
+
392
+ 2. **Gumbel-Softmax**: Differentiable approximation for categorical selection:
393
+ ```python
394
+ # Soft selection (differentiable)
395
+ probs = softmax((log_probs + gumbel_noise) / temperature)
396
+ selected = probs @ population # Weighted combination
397
+ ```
398
+
399
+ 3. **Binary-Concrete**: Differentiable approximation for binary masks (mutation/crossover):
400
+ ```python
401
+ # Soft mask (differentiable)
402
+ mask = sigmoid((log(u) - log(1-u) + logits) / temperature)
403
+ # Straight-through estimator for hard decisions
404
+ hard_mask = (mask > 0.5).float() - mask.detach() + mask
405
+ ```
406
+
407
+ 4. **Pathwise Gradients**: For continuous distributions (Gaussian sampling in CMA-ES):
408
+ ```python
409
+ # x = μ + σ * L @ z, z ~ N(0, I)
410
+ z = torch.randn(pop_size, n_var)
411
+ x = mean + sigma * (L @ z.T).T # Fully differentiable
412
+ ```
413
+
414
+ ## 📊 Benchmarks
415
+
416
+ TODO
417
+
418
+ ## 📖 Citation
419
+
420
+ TBA
421
+
422
+ ## 📄 License
423
+
424
+ This project is licensed under the Apache-2.0 License - see the [LICENSE](LICENSE) file for details.
425
+
426
+ ## 🤝 Contributing
427
+
428
+ Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
429
+
430
+ 1. Fork the repository
431
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
432
+ 3. Commit your changes (`git commit -m 'Add amazing feature'`)
433
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
434
+ 5. Open a Pull Request
435
+
436
+ ## 🙏 Acknowledgements
437
+
438
+ - Inspired by [pymoo](https://pymoo.org/) for API design
439
+ - Built with [PyTorch](https://pytorch.org/) for automatic differentiation