pygpumeta 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 (73) hide show
  1. pygpumeta-0.1.0/.gitignore +9 -0
  2. pygpumeta-0.1.0/CHANGELOG.md +53 -0
  3. pygpumeta-0.1.0/LICENSE +21 -0
  4. pygpumeta-0.1.0/PKG-INFO +184 -0
  5. pygpumeta-0.1.0/README.md +139 -0
  6. pygpumeta-0.1.0/pyproject.toml +84 -0
  7. pygpumeta-0.1.0/src/pygpumeta/__init__.py +30 -0
  8. pygpumeta-0.1.0/src/pygpumeta/_backend/__init__.py +1 -0
  9. pygpumeta-0.1.0/src/pygpumeta/_backend/arrays.py +24 -0
  10. pygpumeta-0.1.0/src/pygpumeta/_backend/module.py +115 -0
  11. pygpumeta-0.1.0/src/pygpumeta/_backend/msvc.py +222 -0
  12. pygpumeta-0.1.0/src/pygpumeta/_backend/runtime.py +105 -0
  13. pygpumeta-0.1.0/src/pygpumeta/_backend/selection.py +211 -0
  14. pygpumeta-0.1.0/src/pygpumeta/_backend/source.py +158 -0
  15. pygpumeta-0.1.0/src/pygpumeta/_minimize.py +151 -0
  16. pygpumeta-0.1.0/src/pygpumeta/_objective.py +306 -0
  17. pygpumeta-0.1.0/src/pygpumeta/_problem.py +290 -0
  18. pygpumeta-0.1.0/src/pygpumeta/_result.py +97 -0
  19. pygpumeta-0.1.0/src/pygpumeta/_validation.py +84 -0
  20. pygpumeta-0.1.0/src/pygpumeta/_version.py +3 -0
  21. pygpumeta-0.1.0/src/pygpumeta/algorithms/__init__.py +17 -0
  22. pygpumeta-0.1.0/src/pygpumeta/algorithms/_array.py +223 -0
  23. pygpumeta-0.1.0/src/pygpumeta/algorithms/_base.py +373 -0
  24. pygpumeta-0.1.0/src/pygpumeta/algorithms/_kernel.py +304 -0
  25. pygpumeta-0.1.0/src/pygpumeta/algorithms/abc.py +182 -0
  26. pygpumeta-0.1.0/src/pygpumeta/algorithms/de.py +85 -0
  27. pygpumeta-0.1.0/src/pygpumeta/algorithms/gwo.py +67 -0
  28. pygpumeta-0.1.0/src/pygpumeta/algorithms/hho.py +114 -0
  29. pygpumeta-0.1.0/src/pygpumeta/algorithms/pso.py +93 -0
  30. pygpumeta-0.1.0/src/pygpumeta/algorithms/sca.py +32 -0
  31. pygpumeta-0.1.0/src/pygpumeta/algorithms/ssa.py +37 -0
  32. pygpumeta-0.1.0/src/pygpumeta/algorithms/woa.py +33 -0
  33. pygpumeta-0.1.0/src/pygpumeta/benchmarks.py +206 -0
  34. pygpumeta-0.1.0/src/pygpumeta/constraints.py +50 -0
  35. pygpumeta-0.1.0/src/pygpumeta/doctor.py +314 -0
  36. pygpumeta-0.1.0/src/pygpumeta/kernels/metaheuristics.cu +848 -0
  37. pygpumeta-0.1.0/src/pygpumeta/kernels/selection_safe.cu +293 -0
  38. pygpumeta-0.1.0/src/pygpumeta/kernels/separated.cu +237 -0
  39. pygpumeta-0.1.0/src/pygpumeta/py.typed +0 -0
  40. pygpumeta-0.1.0/src/pygpumeta/reference.py +335 -0
  41. pygpumeta-0.1.0/src/pygpumeta/selection.py +273 -0
  42. pygpumeta-0.1.0/src/pygpumeta/space.py +128 -0
  43. pygpumeta-0.1.0/tests/conftest.py +25 -0
  44. pygpumeta-0.1.0/tests/cpu/data/make_reference_golden.py +72 -0
  45. pygpumeta-0.1.0/tests/cpu/data/reference_golden.json +1502 -0
  46. pygpumeta-0.1.0/tests/cpu/test_array_optimizers.py +204 -0
  47. pygpumeta-0.1.0/tests/cpu/test_backend.py +147 -0
  48. pygpumeta-0.1.0/tests/cpu/test_benchmarks.py +77 -0
  49. pygpumeta-0.1.0/tests/cpu/test_doctor.py +184 -0
  50. pygpumeta-0.1.0/tests/cpu/test_examples.py +125 -0
  51. pygpumeta-0.1.0/tests/cpu/test_kernel_calls.py +330 -0
  52. pygpumeta-0.1.0/tests/cpu/test_msvc_discovery.py +198 -0
  53. pygpumeta-0.1.0/tests/cpu/test_optimizer_arguments.py +310 -0
  54. pygpumeta-0.1.0/tests/cpu/test_problem_features.py +353 -0
  55. pygpumeta-0.1.0/tests/cpu/test_reference_characterisation.py +69 -0
  56. pygpumeta-0.1.0/tests/cpu/test_reference_properties.py +114 -0
  57. pygpumeta-0.1.0/tests/cpu/test_validation.py +64 -0
  58. pygpumeta-0.1.0/tests/gpu/conftest.py +50 -0
  59. pygpumeta-0.1.0/tests/gpu/gpu_common.py +20 -0
  60. pygpumeta-0.1.0/tests/gpu/test_against_paper_code.py +102 -0
  61. pygpumeta-0.1.0/tests/gpu/test_bounds_and_constraints.py +229 -0
  62. pygpumeta-0.1.0/tests/gpu/test_kernels_vs_reference.py +89 -0
  63. pygpumeta-0.1.0/tests/gpu/test_objective_modes.py +190 -0
  64. pygpumeta-0.1.0/tests/gpu/test_optimizers.py +246 -0
  65. pygpumeta-0.1.0/tests/gpu/test_pso_de_on_device.py +149 -0
  66. pygpumeta-0.1.0/tests/isolation.py +30 -0
  67. pygpumeta-0.1.0/tests/stubs/README.md +13 -0
  68. pygpumeta-0.1.0/tests/stubs/cupy/__init__.py +23 -0
  69. pygpumeta-0.1.0/tests/stubs/pycuda/__init__.py +3 -0
  70. pygpumeta-0.1.0/tests/stubs/pycuda/compiler.py +1 -0
  71. pygpumeta-0.1.0/tests/stubs/pycuda/driver.py +9 -0
  72. pygpumeta-0.1.0/tests/stubs/pycuda/gpuarray.py +1 -0
  73. pygpumeta-0.1.0/tests/test_array_optimizers_shared.py +26 -0
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ .coverage
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .mypy_cache/
8
+ .ruff_cache/
9
+ .hypothesis/
@@ -0,0 +1,53 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file. The format
4
+ follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the
5
+ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-11-22
10
+
11
+ ### Added
12
+
13
+ - `minimize` and the optimizer classes `ABC`, `GWO`, `WOA`, `SCA`, `SSA`
14
+ and `HHO` (CUDA kernels) and `PSO` and `DE` (array operations on CuPy or
15
+ NumPy arrays), with step-wise control, callbacks, target, patience and
16
+ time limits, and a typed `OptimizeResult` holding the best position, the
17
+ convergence history, the number of evaluations and the termination
18
+ reason.
19
+ - Four ways to supply an objective: the name of a built-in test function, a
20
+ Python callable on CuPy arrays evaluated on the device, a `CudaObjective`
21
+ source compiled into the kernels, and a Python callable on NumPy arrays
22
+ with `mode="host"`.
23
+ - `evaluation` option of `ABC` and `HHO`: the objective is evaluated either
24
+ inside the update kernels or as a separate step, with the same result.
25
+ - Bounds per variable, `maximize=True`, and integer and categorical
26
+ variables through `pygpumeta.space.Real`, `Integer` and `Categorical`,
27
+ decoded before the objective is evaluated.
28
+ - Inequality and equality constraints (`pygpumeta.Constraint`), handled by
29
+ a penalty or by the feasibility rule of Deb; the result reports the
30
+ objective, the constraint violation and feasibility.
31
+ - `pygpumeta.selection`: warp tournament, Ballot-Elite and migration
32
+ selection on PyCUDA and CuPy device arrays. `selection="auto"`, the
33
+ default of the optimizers, is the warp tournament for ABC, GWO, WOA and
34
+ HHO and the native rule for SCA, SSA, PSO and DE.
35
+ - `pygpumeta.reference`: CPU reference that reproduces the selection
36
+ operators bit for bit.
37
+ - `pygpumeta.benchmarks`: names, domains, known optima and NumPy versions
38
+ of the built-in test functions.
39
+ - CUDA kernels shipped as package data, compiled on first use and cached
40
+ per source; importing the package creates no CUDA context. Mathematical
41
+ constants are exact double-precision values. Non-finite objective values
42
+ are replaced by plus or minus 1e299.
43
+ - On Windows the MSVC compiler is located through Visual Studio when
44
+ `cl.exe` is not on the PATH, for the running process only;
45
+ `PYGPUMETA_NO_MSVC_DISCOVERY=1` switches this off.
46
+ - `python -m pygpumeta.doctor` checks driver, CUDA toolkit, C++ compiler,
47
+ PyCUDA and CuPy, explains what is missing and finishes with a small run.
48
+ - Installation guide for Google Colab, Windows and Linux with conda-forge,
49
+ stating which setups have been verified; documentation on objective
50
+ modes with measured timings, on the selection operators and on adding an
51
+ algorithm; eight runnable examples, each compared with a reference value.
52
+ - Test suite in two tiers (CPU anywhere, GPU on a CUDA device), CI for
53
+ Python 3.10 to 3.13, and a release workflow with PyPI trusted publishing.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Emre Can Kuran, Umut Kuran, Ece Ecemiş
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,184 @@
1
+ Metadata-Version: 2.5
2
+ Name: pygpumeta
3
+ Version: 0.1.0
4
+ Summary: GPU metaheuristics with warp-level selection operators for large-population optimisation
5
+ Project-URL: Repository, https://github.com/EmreCanKURAN/pygpumeta-dev
6
+ Project-URL: Issues, https://github.com/EmreCanKURAN/pygpumeta-dev/issues
7
+ Author: Emre Can Kuran, Umut Kuran, Ece Ecemiş
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: cuda,gpu,metaheuristics,optimization,swarm intelligence
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: GPU :: NVIDIA CUDA
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: numpy>=1.23
24
+ Requires-Dist: pycuda>=2022.1
25
+ Provides-Extra: cupy12
26
+ Requires-Dist: cupy-cuda12x>=13; extra == 'cupy12'
27
+ Provides-Extra: cupy13
28
+ Requires-Dist: cupy-cuda13x>=14; extra == 'cupy13'
29
+ Provides-Extra: dev
30
+ Requires-Dist: build>=1.0; extra == 'dev'
31
+ Requires-Dist: hypothesis>=6.80; extra == 'dev'
32
+ Requires-Dist: mypy>=1.8; extra == 'dev'
33
+ Requires-Dist: pre-commit>=3.5; extra == 'dev'
34
+ Requires-Dist: pytest-cov>=4.1; extra == 'dev'
35
+ Requires-Dist: pytest>=7.4; extra == 'dev'
36
+ Requires-Dist: ruff>=0.5; extra == 'dev'
37
+ Provides-Extra: examples
38
+ Requires-Dist: scikit-learn>=1.3; extra == 'examples'
39
+ Requires-Dist: scipy>=1.10; extra == 'examples'
40
+ Provides-Extra: test
41
+ Requires-Dist: hypothesis>=6.80; extra == 'test'
42
+ Requires-Dist: pytest-cov>=4.1; extra == 'test'
43
+ Requires-Dist: pytest>=7.4; extra == 'test'
44
+ Description-Content-Type: text/markdown
45
+
46
+ # pygpumeta
47
+
48
+ GPU metaheuristics for continuous optimisation with large populations,
49
+ built around selection operators that work at the level of GPU warps.
50
+
51
+ ## What it is for
52
+
53
+ Problems where a population of hundreds to tens of thousands of candidates
54
+ is evaluated at once and the objective can be computed for the whole
55
+ population on the GPU: fitting model parameters to data, synthesising
56
+ antenna arrays and filters, sizing structures, dispatching generators,
57
+ thresholding images. You describe the objective as a Python function on GPU
58
+ arrays; you do not write CUDA code.
59
+
60
+ - Eight algorithms: ABC, GWO, WOA, SCA, SSA and HHO as CUDA kernels, PSO
61
+ and DE as array code.
62
+ - Three warp-level selection operators (tournament, Ballot-Elite,
63
+ migration), usable inside the algorithms or on their own.
64
+ - Box bounds per variable, inequality and equality constraints, integer and
65
+ categorical variables, minimisation or maximisation.
66
+ - Reproducible runs for a given seed, step-wise control, callbacks and
67
+ stopping rules.
68
+
69
+ ## What it is not for
70
+
71
+ - **Objectives that must run on the CPU.** They are supported
72
+ (`mode="host"`), but then only the bookkeeping runs on the GPU and there
73
+ is no speedup to expect over a CPU optimizer.
74
+ - **Small populations.** A GPU pays off when there is a lot to do in
75
+ parallel.
76
+ - Multi-objective optimisation, multiple GPUs and GPUs other than NVIDIA's
77
+ are outside its scope.
78
+
79
+ ## Installation
80
+
81
+ An NVIDIA GPU, the CUDA toolkit, a C++ compiler and PyCUDA are required;
82
+ CuPy is needed for objectives written as Python functions on GPU arrays.
83
+ [docs/installation.md](docs/installation.md) has step-by-step instructions
84
+ for Google Colab, Linux with conda-forge and Windows. Afterwards,
85
+
86
+ ```
87
+ python -m pygpumeta.doctor
88
+ ```
89
+
90
+ checks every component, says how to fix what is missing and finishes with a
91
+ small optimisation run.
92
+
93
+ ## Quick start
94
+
95
+ ```python
96
+ import pygpumeta
97
+
98
+ def objective(x): # x: cupy.ndarray of shape (n, 30), on the GPU
99
+ return ((x - 1.0) ** 2).sum(axis=1)
100
+
101
+ result = pygpumeta.minimize(
102
+ objective, (-5.0, 5.0), dim=30, algorithm="gwo", pop_size=1024, max_iter=1000, seed=0,
103
+ )
104
+ print(result.fun, result.x, result.nfev, result.runtime, result.termination)
105
+ ```
106
+
107
+ With constraints and mixed variables:
108
+
109
+ ```python
110
+ from pygpumeta import Constraint, minimize
111
+ from pygpumeta.space import Categorical, Integer, Real
112
+
113
+ result = minimize(
114
+ objective,
115
+ [Real(-1.0, 1.0), Integer(0, 10), Categorical(["a", "b", "c"])],
116
+ constraints=[Constraint(lambda x: x[:, 0] + x[:, 1] - 5.0)], # x0 + x1 <= 5
117
+ constraint_handling="feasibility",
118
+ )
119
+ print(result.values, result.feasible)
120
+ ```
121
+
122
+ ## Documentation
123
+
124
+ - [Which objective mode should I use?](docs/objective_modes.md), with
125
+ measured timings of one problem in each mode.
126
+ - [The selection operators](docs/selection.md): what they do and what they
127
+ do not provide.
128
+ - [Adding an algorithm](docs/adding_an_algorithm.md).
129
+ - [Installation](docs/installation.md).
130
+ - [Examples](docs/examples.md) with their results: antenna array synthesis,
131
+ solar cell parameter extraction, truss sizing, economic load dispatch,
132
+ image thresholding, FIR filter design, SVM tuning and a custom algorithm.
133
+
134
+ Every public function and class has a docstring; `help(pygpumeta.minimize)`
135
+ is the reference for the main entry point.
136
+
137
+ ## Tests
138
+
139
+ Install the package together with its test dependencies (pytest,
140
+ hypothesis, pytest-cov), which a plain `pip install -e .` leaves out:
141
+
142
+ ```
143
+ pip install -e ".[test]"
144
+ pip install scipy scikit-learn # optional: the tests of the examples
145
+ ```
146
+
147
+ ```
148
+ python -m pytest -m "not gpu" # CPU tier, anywhere
149
+ python -m pytest -m gpu # GPU tier, on a machine with a CUDA device
150
+ python -m pytest # both; the GPU tier is skipped without CUDA
151
+ ```
152
+
153
+ On a machine without the CUDA toolkit, PyCUDA cannot be built; use
154
+ `pip install --no-deps -e .` followed by `pip install numpy pytest hypothesis`
155
+ there. `pip install -e ".[dev]"` adds ruff, mypy and pre-commit.
156
+
157
+ `notebooks/gpu_tests.ipynb` runs the GPU tier on Google Colab.
158
+
159
+ ## Citation
160
+
161
+ If you use the library, please cite the paper that introduces the selection
162
+ operators:
163
+
164
+ ```bibtex
165
+ @article{kuran2026warpselection,
166
+ author = {Kuran, Emre Can and Kuran, Umut and Ecemi{\c{s}}, Ece},
167
+ title = {Register-Level Selection via Warp Primitives: Shuffle-Based Tournament and
168
+ Ballot-Elite Mechanisms for {GPU}-Accelerated Metaheuristics},
169
+ journal = {Swarm and Evolutionary Computation},
170
+ year = {2026},
171
+ note = {In press}
172
+ }
173
+ ```
174
+
175
+ ## Acknowledgement
176
+
177
+ This library extends the code of the paper into a general-purpose
178
+ package. It was developed with the assistance of Claude Code
179
+ (Anthropic); the authors have written the original code (paper), reviewed the design, ran the GPU test suite
180
+ and are responsible for the released code.
181
+
182
+ ## License
183
+
184
+ MIT, see `LICENSE`.
@@ -0,0 +1,139 @@
1
+ # pygpumeta
2
+
3
+ GPU metaheuristics for continuous optimisation with large populations,
4
+ built around selection operators that work at the level of GPU warps.
5
+
6
+ ## What it is for
7
+
8
+ Problems where a population of hundreds to tens of thousands of candidates
9
+ is evaluated at once and the objective can be computed for the whole
10
+ population on the GPU: fitting model parameters to data, synthesising
11
+ antenna arrays and filters, sizing structures, dispatching generators,
12
+ thresholding images. You describe the objective as a Python function on GPU
13
+ arrays; you do not write CUDA code.
14
+
15
+ - Eight algorithms: ABC, GWO, WOA, SCA, SSA and HHO as CUDA kernels, PSO
16
+ and DE as array code.
17
+ - Three warp-level selection operators (tournament, Ballot-Elite,
18
+ migration), usable inside the algorithms or on their own.
19
+ - Box bounds per variable, inequality and equality constraints, integer and
20
+ categorical variables, minimisation or maximisation.
21
+ - Reproducible runs for a given seed, step-wise control, callbacks and
22
+ stopping rules.
23
+
24
+ ## What it is not for
25
+
26
+ - **Objectives that must run on the CPU.** They are supported
27
+ (`mode="host"`), but then only the bookkeeping runs on the GPU and there
28
+ is no speedup to expect over a CPU optimizer.
29
+ - **Small populations.** A GPU pays off when there is a lot to do in
30
+ parallel.
31
+ - Multi-objective optimisation, multiple GPUs and GPUs other than NVIDIA's
32
+ are outside its scope.
33
+
34
+ ## Installation
35
+
36
+ An NVIDIA GPU, the CUDA toolkit, a C++ compiler and PyCUDA are required;
37
+ CuPy is needed for objectives written as Python functions on GPU arrays.
38
+ [docs/installation.md](docs/installation.md) has step-by-step instructions
39
+ for Google Colab, Linux with conda-forge and Windows. Afterwards,
40
+
41
+ ```
42
+ python -m pygpumeta.doctor
43
+ ```
44
+
45
+ checks every component, says how to fix what is missing and finishes with a
46
+ small optimisation run.
47
+
48
+ ## Quick start
49
+
50
+ ```python
51
+ import pygpumeta
52
+
53
+ def objective(x): # x: cupy.ndarray of shape (n, 30), on the GPU
54
+ return ((x - 1.0) ** 2).sum(axis=1)
55
+
56
+ result = pygpumeta.minimize(
57
+ objective, (-5.0, 5.0), dim=30, algorithm="gwo", pop_size=1024, max_iter=1000, seed=0,
58
+ )
59
+ print(result.fun, result.x, result.nfev, result.runtime, result.termination)
60
+ ```
61
+
62
+ With constraints and mixed variables:
63
+
64
+ ```python
65
+ from pygpumeta import Constraint, minimize
66
+ from pygpumeta.space import Categorical, Integer, Real
67
+
68
+ result = minimize(
69
+ objective,
70
+ [Real(-1.0, 1.0), Integer(0, 10), Categorical(["a", "b", "c"])],
71
+ constraints=[Constraint(lambda x: x[:, 0] + x[:, 1] - 5.0)], # x0 + x1 <= 5
72
+ constraint_handling="feasibility",
73
+ )
74
+ print(result.values, result.feasible)
75
+ ```
76
+
77
+ ## Documentation
78
+
79
+ - [Which objective mode should I use?](docs/objective_modes.md), with
80
+ measured timings of one problem in each mode.
81
+ - [The selection operators](docs/selection.md): what they do and what they
82
+ do not provide.
83
+ - [Adding an algorithm](docs/adding_an_algorithm.md).
84
+ - [Installation](docs/installation.md).
85
+ - [Examples](docs/examples.md) with their results: antenna array synthesis,
86
+ solar cell parameter extraction, truss sizing, economic load dispatch,
87
+ image thresholding, FIR filter design, SVM tuning and a custom algorithm.
88
+
89
+ Every public function and class has a docstring; `help(pygpumeta.minimize)`
90
+ is the reference for the main entry point.
91
+
92
+ ## Tests
93
+
94
+ Install the package together with its test dependencies (pytest,
95
+ hypothesis, pytest-cov), which a plain `pip install -e .` leaves out:
96
+
97
+ ```
98
+ pip install -e ".[test]"
99
+ pip install scipy scikit-learn # optional: the tests of the examples
100
+ ```
101
+
102
+ ```
103
+ python -m pytest -m "not gpu" # CPU tier, anywhere
104
+ python -m pytest -m gpu # GPU tier, on a machine with a CUDA device
105
+ python -m pytest # both; the GPU tier is skipped without CUDA
106
+ ```
107
+
108
+ On a machine without the CUDA toolkit, PyCUDA cannot be built; use
109
+ `pip install --no-deps -e .` followed by `pip install numpy pytest hypothesis`
110
+ there. `pip install -e ".[dev]"` adds ruff, mypy and pre-commit.
111
+
112
+ `notebooks/gpu_tests.ipynb` runs the GPU tier on Google Colab.
113
+
114
+ ## Citation
115
+
116
+ If you use the library, please cite the paper that introduces the selection
117
+ operators:
118
+
119
+ ```bibtex
120
+ @article{kuran2026warpselection,
121
+ author = {Kuran, Emre Can and Kuran, Umut and Ecemi{\c{s}}, Ece},
122
+ title = {Register-Level Selection via Warp Primitives: Shuffle-Based Tournament and
123
+ Ballot-Elite Mechanisms for {GPU}-Accelerated Metaheuristics},
124
+ journal = {Swarm and Evolutionary Computation},
125
+ year = {2026},
126
+ note = {In press}
127
+ }
128
+ ```
129
+
130
+ ## Acknowledgement
131
+
132
+ This library extends the code of the paper into a general-purpose
133
+ package. It was developed with the assistance of Claude Code
134
+ (Anthropic); the authors have written the original code (paper), reviewed the design, ran the GPU test suite
135
+ and are responsible for the released code.
136
+
137
+ ## License
138
+
139
+ MIT, see `LICENSE`.
@@ -0,0 +1,84 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.21"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pygpumeta"
7
+ dynamic = ["version"]
8
+ description = "GPU metaheuristics with warp-level selection operators for large-population optimisation"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Emre Can Kuran" }, { name = "Umut Kuran" }, { name = "Ece Ecemiş" }]
13
+ keywords = ["optimization", "metaheuristics", "gpu", "cuda", "swarm intelligence"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: GPU :: NVIDIA CUDA",
17
+ "Intended Audience :: Science/Research",
18
+ "License :: OSI Approved :: MIT License",
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
+ "Topic :: Scientific/Engineering :: Mathematics",
25
+ "Typing :: Typed",
26
+ ]
27
+ dependencies = ["numpy>=1.23", "pycuda>=2022.1"]
28
+
29
+ [project.optional-dependencies]
30
+ # CuPy has one package per CUDA major version; pick the one that matches
31
+ # the installed toolkit (docs/installation.md).
32
+ cupy12 = ["cupy-cuda12x>=13"]
33
+ cupy13 = ["cupy-cuda13x>=14"]
34
+ examples = ["scipy>=1.10", "scikit-learn>=1.3"]
35
+ test = ["pytest>=7.4", "pytest-cov>=4.1", "hypothesis>=6.80"]
36
+ dev = ["pygpumeta[test]", "ruff>=0.5", "mypy>=1.8", "pre-commit>=3.5", "build>=1.0"]
37
+
38
+ [project.urls]
39
+ Repository = "https://github.com/EmreCanKURAN/pygpumeta-dev"
40
+ Issues = "https://github.com/EmreCanKURAN/pygpumeta-dev/issues"
41
+
42
+ [tool.hatch.version]
43
+ path = "src/pygpumeta/_version.py"
44
+
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["src/pygpumeta"]
47
+
48
+ [tool.hatch.build.targets.sdist]
49
+ include = ["src", "tests", "README.md", "LICENSE", "CHANGELOG.md"]
50
+ exclude = ["tests/legacy"]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
54
+ pythonpath = ["tests"]
55
+ addopts = "-ra --strict-markers"
56
+ markers = ["gpu: needs a CUDA device and PyCUDA; skipped automatically when unavailable"]
57
+
58
+ [tool.coverage.run]
59
+ source = ["pygpumeta"]
60
+
61
+ [tool.ruff]
62
+ line-length = 100
63
+ target-version = "py310"
64
+ extend-exclude = ["tests/legacy", "tests/stubs", "README.md"]
65
+
66
+ [tool.ruff.lint]
67
+ select = ["E", "F", "W", "I", "UP", "B", "SIM", "RUF", "D"]
68
+ ignore = ["D105", "D107"]
69
+
70
+ [tool.ruff.lint.pydocstyle]
71
+ convention = "numpy"
72
+
73
+ [tool.ruff.lint.per-file-ignores]
74
+ "tests/**" = ["D"]
75
+ "benchmarks/**" = ["D103"]
76
+ "examples/**" = ["D103", "E501"]
77
+
78
+ [tool.mypy]
79
+ strict = true
80
+ files = ["src"]
81
+
82
+ [[tool.mypy.overrides]]
83
+ module = ["pycuda.*", "cupy.*"]
84
+ ignore_missing_imports = true
@@ -0,0 +1,30 @@
1
+ """GPU metaheuristics with warp-level selection operators.
2
+
3
+ Importing the package has no side effects: the CUDA context is created and
4
+ the kernels are compiled the first time they are needed.
5
+ """
6
+
7
+ from pygpumeta._minimize import minimize
8
+ from pygpumeta._objective import CudaObjective
9
+ from pygpumeta._result import OptimizeResult, TerminationReason
10
+ from pygpumeta._version import __version__
11
+ from pygpumeta.algorithms import ABC, DE, GWO, HHO, PSO, SCA, SSA, WOA, Optimizer
12
+ from pygpumeta.constraints import Constraint
13
+
14
+ __all__ = [
15
+ "ABC",
16
+ "DE",
17
+ "GWO",
18
+ "HHO",
19
+ "PSO",
20
+ "SCA",
21
+ "SSA",
22
+ "WOA",
23
+ "Constraint",
24
+ "CudaObjective",
25
+ "OptimizeResult",
26
+ "Optimizer",
27
+ "TerminationReason",
28
+ "__version__",
29
+ "minimize",
30
+ ]
@@ -0,0 +1 @@
1
+ """Internal layer between the library and PyCUDA."""
@@ -0,0 +1,24 @@
1
+ """Passing arrays of either GPU library to the kernels."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+
9
+
10
+ def is_cupy_array(array: Any) -> bool:
11
+ """Return whether ``array`` is a CuPy array, without importing CuPy."""
12
+ return type(array).__module__.split(".")[0] == "cupy" and hasattr(array, "data")
13
+
14
+
15
+ def kernel_argument(value: Any) -> Any:
16
+ """Return ``value`` in the form a PyCUDA kernel launch accepts.
17
+
18
+ PyCUDA arrays and NumPy scalars pass through. A CuPy array is replaced
19
+ by its device address; both libraries work in the same CUDA context, so
20
+ the address is valid for the kernels.
21
+ """
22
+ if is_cupy_array(value):
23
+ return np.uintp(value.data.ptr)
24
+ return value
@@ -0,0 +1,115 @@
1
+ """Compiled CUDA modules with explicit kernel handles."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import threading
7
+ import time
8
+ from collections.abc import Callable
9
+ from typing import Any
10
+
11
+ from pygpumeta._backend import msvc
12
+ from pygpumeta._backend.source import kernel_names
13
+
14
+ Compiler = Callable[[str], Any]
15
+
16
+ _cache: dict[str, CompiledModule] = {}
17
+ _cache_lock = threading.Lock()
18
+
19
+
20
+ class CompilationError(RuntimeError):
21
+ """Raised when the CUDA compiler rejects a source."""
22
+
23
+
24
+ class CompiledModule:
25
+ """A compiled CUDA source and its kernels.
26
+
27
+ Parameters
28
+ ----------
29
+ source : str
30
+ Complete CUDA C source.
31
+ label : str
32
+ Short name used in error messages.
33
+ compiler : callable, optional
34
+ Function turning a source into an object with ``get_function`` and
35
+ ``get_global``. Defaults to PyCUDA's ``SourceModule`` on the shared
36
+ runtime.
37
+ """
38
+
39
+ def __init__(self, source: str, *, label: str, compiler: Compiler | None = None) -> None:
40
+ self.label = label
41
+ self.source = source
42
+ self.source_hash = source_digest(source)
43
+ self.kernel_names = kernel_names(source)
44
+ self._handles: dict[str, Any] = {}
45
+ start = time.perf_counter()
46
+ self._module = (compiler or _pycuda_compiler)(source)
47
+ self.compile_time = time.perf_counter() - start
48
+
49
+ def kernel(self, name: str) -> Any:
50
+ """Return the handle of a kernel.
51
+
52
+ Raises
53
+ ------
54
+ KeyError
55
+ If the source defines no kernel of that name.
56
+ """
57
+ handle = self._handles.get(name)
58
+ if handle is None:
59
+ if name not in self.kernel_names:
60
+ raise KeyError(
61
+ f"module '{self.label}' has no kernel named {name!r}; "
62
+ f"available: {', '.join(sorted(self.kernel_names))}"
63
+ )
64
+ handle = self._handles[name] = self._module.get_function(name)
65
+ return handle
66
+
67
+ def global_pointer(self, name: str) -> Any:
68
+ """Return the device address of a global variable of the module."""
69
+ return self._module.get_global(name)[0]
70
+
71
+ def __repr__(self) -> str:
72
+ return f"CompiledModule({self.label!r}, {len(self.kernel_names)} kernels)"
73
+
74
+
75
+ def source_digest(source: str) -> str:
76
+ """Return the cache key of a source."""
77
+ return hashlib.sha256(source.encode("utf-8")).hexdigest()
78
+
79
+
80
+ def compile_cached(source: str, *, label: str, compiler: Compiler | None = None) -> CompiledModule:
81
+ """Compile a source once per process and return the shared module."""
82
+ key = source_digest(source)
83
+ with _cache_lock:
84
+ module = _cache.get(key)
85
+ if module is None:
86
+ module = _cache[key] = CompiledModule(source, label=label, compiler=compiler)
87
+ return module
88
+
89
+
90
+ def clear_cache() -> None:
91
+ """Forget all compiled modules."""
92
+ with _cache_lock:
93
+ _cache.clear()
94
+
95
+
96
+ def _pycuda_compiler(source: str) -> Any:
97
+ from pygpumeta._backend.runtime import get_runtime
98
+
99
+ get_runtime()
100
+ from pycuda.compiler import SourceModule
101
+
102
+ try:
103
+ return SourceModule(source)
104
+ except Exception as exc:
105
+ compiler = msvc.ensure_host_compiler()
106
+ if not compiler.available:
107
+ raise CompilationError(
108
+ f"the kernels could not be compiled. {msvc.describe_missing(compiler)}\n{exc}"
109
+ ) from exc
110
+ # Kernel names are exported with C linkage and looked up right after
111
+ # compilation, so compiler and linker messages both end up here.
112
+ raise CompilationError(
113
+ f"the CUDA compiler rejected the kernel source. If you passed a CudaObjective, "
114
+ f"check its code; helper functions must be declared __device__.\n{exc}"
115
+ ) from exc