polystep 0.7.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 (106) hide show
  1. polystep-0.7.0/LICENSE +191 -0
  2. polystep-0.7.0/PKG-INFO +285 -0
  3. polystep-0.7.0/README.md +237 -0
  4. polystep-0.7.0/pyproject.toml +101 -0
  5. polystep-0.7.0/setup.cfg +4 -0
  6. polystep-0.7.0/src/polystep/__init__.py +176 -0
  7. polystep-0.7.0/src/polystep/_compiled.py +334 -0
  8. polystep-0.7.0/src/polystep/_step_blockwise.py +994 -0
  9. polystep-0.7.0/src/polystep/_step_momentum.py +128 -0
  10. polystep-0.7.0/src/polystep/_step_monolithic.py +1070 -0
  11. polystep-0.7.0/src/polystep/adaptive_subspace.py +762 -0
  12. polystep-0.7.0/src/polystep/api.py +307 -0
  13. polystep-0.7.0/src/polystep/ask_tell.py +164 -0
  14. polystep-0.7.0/src/polystep/benchmarks/__init__.py +62 -0
  15. polystep-0.7.0/src/polystep/benchmarks/baselines.py +604 -0
  16. polystep-0.7.0/src/polystep/benchmarks/rl/__init__.py +13 -0
  17. polystep-0.7.0/src/polystep/benchmarks/rl/cartpole.py +260 -0
  18. polystep-0.7.0/src/polystep/benchmarks/rl/gym_evaluator.py +304 -0
  19. polystep-0.7.0/src/polystep/benchmarks/rl/metrics.py +53 -0
  20. polystep-0.7.0/src/polystep/benchmarks/rl/policies.py +133 -0
  21. polystep-0.7.0/src/polystep/benchmarks/utils.py +1262 -0
  22. polystep-0.7.0/src/polystep/blockwise.py +549 -0
  23. polystep-0.7.0/src/polystep/cma.py +400 -0
  24. polystep-0.7.0/src/polystep/cma_subspace.py +404 -0
  25. polystep-0.7.0/src/polystep/cost_nn.py +633 -0
  26. polystep-0.7.0/src/polystep/costs.py +86 -0
  27. polystep-0.7.0/src/polystep/dynamics.py +138 -0
  28. polystep-0.7.0/src/polystep/epsilon.py +217 -0
  29. polystep-0.7.0/src/polystep/geometry.py +410 -0
  30. polystep-0.7.0/src/polystep/hybrid_subspace.py +1335 -0
  31. polystep-0.7.0/src/polystep/layers/__init__.py +16 -0
  32. polystep-0.7.0/src/polystep/layers/attention.py +243 -0
  33. polystep-0.7.0/src/polystep/layers/rnn.py +276 -0
  34. polystep-0.7.0/src/polystep/objectives/__init__.py +25 -0
  35. polystep-0.7.0/src/polystep/objectives/base.py +77 -0
  36. polystep-0.7.0/src/polystep/objectives/synthetic.py +232 -0
  37. polystep-0.7.0/src/polystep/optimizer.py +1405 -0
  38. polystep-0.7.0/src/polystep/projection/__init__.py +5 -0
  39. polystep-0.7.0/src/polystep/projection/sparse.py +291 -0
  40. polystep-0.7.0/src/polystep/py.typed +0 -0
  41. polystep-0.7.0/src/polystep/quadratic_model.py +285 -0
  42. polystep-0.7.0/src/polystep/solver.py +654 -0
  43. polystep-0.7.0/src/polystep/solvers/__init__.py +34 -0
  44. polystep-0.7.0/src/polystep/solvers/_prelude.py +129 -0
  45. polystep-0.7.0/src/polystep/solvers/base.py +77 -0
  46. polystep-0.7.0/src/polystep/solvers/greedy.py +159 -0
  47. polystep-0.7.0/src/polystep/solvers/kl_softmax.py +200 -0
  48. polystep-0.7.0/src/polystep/solvers/sinkhorn.py +522 -0
  49. polystep-0.7.0/src/polystep/solvers/softmax.py +151 -0
  50. polystep-0.7.0/src/polystep/solvers/tempered_softmax.py +97 -0
  51. polystep-0.7.0/src/polystep/subspace.py +694 -0
  52. polystep-0.7.0/src/polystep/transform.py +365 -0
  53. polystep-0.7.0/src/polystep.egg-info/PKG-INFO +285 -0
  54. polystep-0.7.0/src/polystep.egg-info/SOURCES.txt +104 -0
  55. polystep-0.7.0/src/polystep.egg-info/dependency_links.txt +1 -0
  56. polystep-0.7.0/src/polystep.egg-info/requires.txt +29 -0
  57. polystep-0.7.0/src/polystep.egg-info/top_level.txt +1 -0
  58. polystep-0.7.0/tests/test_ablation_solvers.py +273 -0
  59. polystep-0.7.0/tests/test_adaptive_mnist.py +466 -0
  60. polystep-0.7.0/tests/test_adaptive_subspace.py +535 -0
  61. polystep-0.7.0/tests/test_api.py +362 -0
  62. polystep-0.7.0/tests/test_ask_tell.py +79 -0
  63. polystep-0.7.0/tests/test_baseline_fairness.py +105 -0
  64. polystep-0.7.0/tests/test_benchmarks.py +164 -0
  65. polystep-0.7.0/tests/test_biased_rotation.py +53 -0
  66. polystep-0.7.0/tests/test_blockwise.py +398 -0
  67. polystep-0.7.0/tests/test_bug_regressions.py +456 -0
  68. polystep-0.7.0/tests/test_cma.py +427 -0
  69. polystep-0.7.0/tests/test_cma_subspace.py +629 -0
  70. polystep-0.7.0/tests/test_compiled.py +450 -0
  71. polystep-0.7.0/tests/test_cost_nn.py +502 -0
  72. polystep-0.7.0/tests/test_costs.py +81 -0
  73. polystep-0.7.0/tests/test_dfo_features.py +342 -0
  74. polystep-0.7.0/tests/test_dynamics.py +216 -0
  75. polystep-0.7.0/tests/test_fullspace_chunk_bound.py +49 -0
  76. polystep-0.7.0/tests/test_fused_projection_rebuild.py +53 -0
  77. polystep-0.7.0/tests/test_geometry.py +248 -0
  78. polystep-0.7.0/tests/test_hardening.py +205 -0
  79. polystep-0.7.0/tests/test_hybrid_mnist.py +473 -0
  80. polystep-0.7.0/tests/test_hybrid_subspace.py +977 -0
  81. polystep-0.7.0/tests/test_integration.py +433 -0
  82. polystep-0.7.0/tests/test_kl_softmax.py +144 -0
  83. polystep-0.7.0/tests/test_layers.py +303 -0
  84. polystep-0.7.0/tests/test_mixed_precision.py +219 -0
  85. polystep-0.7.0/tests/test_mixed_precision_step.py +104 -0
  86. polystep-0.7.0/tests/test_mnist.py +546 -0
  87. polystep-0.7.0/tests/test_no_test_set_leakage.py +18 -0
  88. polystep-0.7.0/tests/test_nondiff_data.py +157 -0
  89. polystep-0.7.0/tests/test_nondiff_models.py +582 -0
  90. polystep-0.7.0/tests/test_numerical_stress.py +220 -0
  91. polystep-0.7.0/tests/test_optimizer.py +995 -0
  92. polystep-0.7.0/tests/test_quadratic_model.py +369 -0
  93. polystep-0.7.0/tests/test_rl_benchmarks.py +159 -0
  94. polystep-0.7.0/tests/test_sinkhorn.py +796 -0
  95. polystep-0.7.0/tests/test_sinkhorn_correctness.py +357 -0
  96. polystep-0.7.0/tests/test_softmax.py +251 -0
  97. polystep-0.7.0/tests/test_softmax_integration.py +422 -0
  98. polystep-0.7.0/tests/test_solver_numerics.py +160 -0
  99. polystep-0.7.0/tests/test_sparse_integration.py +367 -0
  100. polystep-0.7.0/tests/test_sparse_projection.py +328 -0
  101. polystep-0.7.0/tests/test_subspace.py +540 -0
  102. polystep-0.7.0/tests/test_subspace_blockwise.py +543 -0
  103. polystep-0.7.0/tests/test_transform.py +292 -0
  104. polystep-0.7.0/tests/test_trust_region.py +97 -0
  105. polystep-0.7.0/tests/test_turbo.py +676 -0
  106. polystep-0.7.0/tests/test_vmap_layer_compatibility.py +313 -0
polystep-0.7.0/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2026 An T. Le
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,285 @@
1
+ Metadata-Version: 2.4
2
+ Name: polystep
3
+ Version: 0.7.0
4
+ Summary: PyTorch PolyStep Optimizer - gradient-free neural network training via entropic optimal transport
5
+ Author: An T. Le
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/anindex/polystep
8
+ Project-URL: Repository, https://github.com/anindex/polystep
9
+ Project-URL: Issues, https://github.com/anindex/polystep/issues
10
+ Keywords: pytorch,optimal-transport,gradient-free,sinkhorn,polystep,optimization,neural-network
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.11
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: torch>=2.4
23
+ Requires-Dist: numpy>=1.24
24
+ Provides-Extra: examples
25
+ Requires-Dist: torchvision>=0.25; extra == "examples"
26
+ Requires-Dist: matplotlib>=3.8; extra == "examples"
27
+ Requires-Dist: Pillow>=10.0; extra == "examples"
28
+ Requires-Dist: gymnasium[classic-control]>=0.29; extra == "examples"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8.0; extra == "dev"
31
+ Requires-Dist: pytest-timeout>=2.2; extra == "dev"
32
+ Requires-Dist: pytest-rerunfailures>=14.0; extra == "dev"
33
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
34
+ Requires-Dist: ruff>=0.15.12; extra == "dev"
35
+ Provides-Extra: experiments
36
+ Requires-Dist: scipy>=1.11; extra == "experiments"
37
+ Requires-Dist: statsmodels>=0.14; extra == "experiments"
38
+ Requires-Dist: pandas>=2.0; extra == "experiments"
39
+ Requires-Dist: python-sat; extra == "experiments"
40
+ Requires-Dist: torchvision>=0.25; extra == "experiments"
41
+ Requires-Dist: cma>=3.3; extra == "experiments"
42
+ Requires-Dist: gymnasium>=0.29; extra == "experiments"
43
+ Provides-Extra: rl
44
+ Requires-Dist: gymnasium[box2d]>=0.29; extra == "rl"
45
+ Requires-Dist: stable-baselines3>=2.3; extra == "rl"
46
+ Requires-Dist: swig>=4.2; extra == "rl"
47
+ Dynamic: license-file
48
+
49
+ # polystep
50
+
51
+ [![PyPI](https://img.shields.io/pypi/v/polystep.svg)](https://pypi.org/project/polystep/)
52
+ [![arXiv](https://img.shields.io/badge/arXiv-2605.01928-b31b1b.svg)](https://arxiv.org/abs/2605.01928)
53
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
54
+ [![PyTorch 2.4+](https://img.shields.io/badge/PyTorch-2.4%2B-ee4c2c.svg)](https://pytorch.org/)
55
+ [![License](https://img.shields.io/badge/license-Apache%202.0-green.svg)](LICENSE)
56
+
57
+ **Gradient-free neural network training via optimal transport.**
58
+
59
+ PolyStep optimizes neural networks without backpropagation. At each step, it samples polytope vertices around current parameters, evaluates losses via forward passes only, and computes softmax-weighted projections to find descent directions. This enables training models with non-differentiable components (spiking networks, quantized layers, blackbox modules) where gradients are unavailable or undefined.
60
+
61
+ Based on the Sinkhorn Step algorithm ([Le et al., NeurIPS 2023](https://arxiv.org/abs/2309.15970)), extended with subspace compression, a softmax solver, and convergence analysis for piecewise-smooth losses.
62
+
63
+ ### How it works
64
+
65
+ 1. **Sample** polytope vertices around the current parameters in a compressed subspace.
66
+ 2. **Evaluate** the loss at each vertex (forward pass only, no gradients).
67
+ 3. **Compute** softmax weights over the cost matrix.
68
+ 4. **Update** the parameters by barycentric projection from the weighted vertices.
69
+
70
+ <p align="center">
71
+ <img src="docs/figures/method_diagram.png" width="840"
72
+ alt="One PolyStep: subspace projection, polytope probes, cost matrix, soft entropic-OT assignment, and barycentric projection, plus the softmax-to-full-OT solver continuum.">
73
+ </p>
74
+
75
+ > Want to play around with parameters? [**Viet T. Nguyen**](https://vietngth.github.io/) built a gorgeous interactive walkthrough that animates every step of the method -> **[explore the PolyStep visualization](https://vietngth.github.io/polystep-visualization/)**.
76
+
77
+ ## Installation
78
+
79
+ ```bash
80
+ pip install polystep # from PyPI (core: torch + numpy)
81
+ uv add polystep # or with uv
82
+ ```
83
+
84
+ From source:
85
+
86
+ ```bash
87
+ pip install -e . # core library (torch + numpy)
88
+ pip install -e ".[examples]" # + torchvision, matplotlib
89
+ pip install -e ".[dev]" # + pytest, ruff (development)
90
+ pip install -e ".[experiments]" # + scipy, pandas, python-sat (paper reproduction)
91
+ ```
92
+
93
+ GPU: `pip install torch --index-url https://download.pytorch.org/whl/cu130` (or pick the CUDA build that matches your driver from the [PyTorch install page](https://pytorch.org/get-started/locally/)).
94
+
95
+ ## Quickstart
96
+
97
+ ### Synthetic optimization
98
+
99
+ ```python
100
+ import torch
101
+ from polystep import PolyStep, Ackley
102
+
103
+ solver = PolyStep.create(Ackley(dim=10), epsilon=0.5, max_iterations=50)
104
+ state = solver.run(torch.randn(100, 10))
105
+ print(f"Best cost: {min(state.costs):.4f}")
106
+ ```
107
+
108
+ ### Neural network training
109
+
110
+ ```python
111
+ import torch
112
+ import torch.nn as nn
113
+ from torch.utils.data import DataLoader, TensorDataset
114
+
115
+ from polystep import PolyStepOptimizer, train, TrainConfig
116
+ from polystep.epsilon import CosineEpsilon
117
+ from polystep.hybrid_subspace import HybridSubspace
118
+ from polystep.transform import ParamLayout
119
+
120
+ model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10))
121
+
122
+ # Replace this with your real DataLoader.
123
+ train_loader = DataLoader(
124
+ TensorDataset(torch.randn(1024, 784), torch.randint(0, 10, (1024,))),
125
+ batch_size=64,
126
+ )
127
+
128
+ # HybridSubspace compresses the parameter space per-layer.
129
+ layout = ParamLayout.from_module(model)
130
+ subspace = HybridSubspace.from_layout(layout, rank=8)
131
+
132
+ # Cosine schedules: broad exploration -> fine exploitation.
133
+ optimizer = PolyStepOptimizer(
134
+ model, subspace=subspace, solver="softmax",
135
+ epsilon=CosineEpsilon(init=10.0, target=0.1, decay=0.02),
136
+ step_radius=CosineEpsilon(init=5.0, target=1.0, decay=0.008),
137
+ probe_radius=CosineEpsilon(init=10.0, target=2.0, decay=0.016),
138
+ )
139
+
140
+ train(model, train_loader, nn.CrossEntropyLoss(), optimizer, TrainConfig(epochs=5))
141
+ ```
142
+
143
+ ### Drop-in gradient-free optimizer (ask/tell)
144
+
145
+ PolyStep also exposes the `ask`/`tell` interface used by evolution-strategy libraries, so it drops into ES benchmark harnesses (evosax, NeuroEvoBench) and any black-box loop:
146
+
147
+ ```python
148
+ import torch
149
+ from polystep import PolyStepES
150
+
151
+ es = PolyStepES(dim=20, epsilon=0.1, step_radius=0.3, x0=torch.full((20,), 2.0))
152
+ for _ in range(300):
153
+ candidates = es.ask() # (popsize, dim) points to evaluate
154
+ es.tell(objective(candidates)) # lower fitness is better
155
+ print(es.best_fitness, es.mean)
156
+ ```
157
+
158
+ [`experiments/bench_ask_tell.py`](experiments/bench_ask_tell.py) compares it head-to-head with a Gaussian ES on the standard synthetic suite under a matched evaluation budget.
159
+
160
+ See [`examples/`](examples/) for runnable demos covering SNN, RL, MAX-SAT, MNIST, a Loihi 2 on-chip adaptation skeleton, STE-free binary-net training vs OpenAI-ES, direct F1 minimization where PolyStep beats both a biased gradient (Adam+STE) and OpenAI-ES, and a hard oblique decision tree with strict argmax routing that PolyStep trains directly while OpenAI-ES and SPSA stall.
161
+
162
+ <table>
163
+ <tr>
164
+ <td align="center"><img src="docs/figures/polystep_snn_progress.gif" width="330"><br><sub>Spiking net (hard LIF thresholds) trained with forward passes only</sub></td>
165
+ <td align="center"><img src="docs/figures/rl_cartpole_policy.gif" width="330"><br><sub>CartPole policy search: no value function, no gradients</sub></td>
166
+ </tr>
167
+ </table>
168
+
169
+ ## When to use PolyStep
170
+
171
+ PolyStep is designed for models where gradients are **unavailable or unreliable**:
172
+
173
+ - **Spiking neural networks**: hard LIF thresholds, discrete spike events
174
+ - **Quantized layers**: int8 weights, binary/ternary networks
175
+ - **Blackbox modules**: external simulators, API-based models, hardware-in-the-loop
176
+ - **Hard routing**: argmax gating, hard mixture-of-experts
177
+ - **Combinatorial optimization**: MAX-SAT, discrete assignment problems
178
+
179
+ If your model is fully differentiable, Adam/SGD will be faster and more accurate.
180
+
181
+ ## How PolyStep relates to other gradient-free methods
182
+
183
+ Zeroth-order optimization splits into two camps. Memory-efficient fine-tuning (MeZO and successors) runs zeroth-order updates on differentiable networks to skip the backprop tape, but still assumes a useful local gradient. Evolution strategies and SPSA (CMA-ES, OpenAI-ES) optimize black-box objectives by estimating a local gradient from small perturbations.
184
+
185
+ PolyStep is a randomized direct search: it probes a finite-radius polytope around the current parameters and moves toward the lowest-cost vertices through an optimal-transport barycenter. When the loss is piecewise-constant or genuinely non-differentiable, the local gradient is zero almost everywhere, so finite-difference estimates carry no signal and ES/SPSA stall, while a finite radius steps across the flat regions. This is the setting where direct search (generalized pattern search, MADS) has convergence guarantees on nonsmooth and discontinuous objectives that gradient-estimate methods lack. Example 09 shows the separation on a hard decision tree.
186
+
187
+ Recent gradient-free work targets the same regime, including low-rank evolution strategies for spiking networks (arXiv:2605.30361) and gradient-free trust regions for recurrent spiking networks (arXiv:2601.21572). PolyStep is complementary: a general-purpose direct-search optimizer with subspace compression.
188
+
189
+ ## Benchmarks
190
+
191
+ 5-seed mean ± std (seeds: 42, 123, 456, 789, 1337). Hardware: NVIDIA RTX 5090.
192
+
193
+ ### Non-differentiable tasks
194
+
195
+ Best accuracy (%), 5 seeds. Bold marks the best method on each row. Adam is gradient-based (backprop on a smoothed surrogate), so it is an unfair reference upper bound, not a gradient-free peer of PolyStep, CMA-ES, OpenAI-ES, and SPSA; it is shown only to bound how far the gradient-free methods sit from a gradient method. A dash means the run is not in this release.
196
+
197
+ | Task | PolyStep | Adam (surrogate) | CMA-ES | OpenAI-ES | SPSA | Non-diff op |
198
+ |------|----------|------------------|--------|-----------|------|-------------|
199
+ | SNN/LIF (MNIST) | **93.4 ± 0.2** | 80.5 | 16.2 | 33.1 | 29.4 | threshold() |
200
+ | Int8 quantized | 97.1 ± 0.1 | **98.1** | 80.7 | 78.1 | 91.2 | round() |
201
+ | Argmax attention | 86.8 ± 0.4 | **89.1** | 72.6 | 75.7 | 77.7 | argmax() |
202
+ | Staircase activation | 93.2 ± 0.3 | **97.6** | 72.8 | 85.5 | 49.3 | floor() |
203
+ | Hard MoE routing | **90.7 ± 0.2** | - | 62.8 | 63.5 | 69.3 | argmax() |
204
+ | MAX-SAT 100K vars | **98.0 ± 0.01** | - | 90.1 | 88.9 | - | round() |
205
+ | MAX-SAT 1M vars | **92.6 ± 0.02** | - | - | 87.8 | - | round() |
206
+
207
+ ### Differentiable sanity checks
208
+
209
+ Adam here is gradient-based (backprop), an unfair reference rather than a peer; PolyStep stays gradient-free and forward-only. These rows only check that PolyStep lands close to a gradient method when gradients do exist.
210
+
211
+ | Task | PolyStep | Adam | Architecture |
212
+ |------|---------|------|--------------|
213
+ | MNIST | **96.0% ± 0.1** | 97.9% | 2-layer MLP (101K) |
214
+ | ETTh1 timeseries | **MSE 0.121 ± 0.004** | MSE 0.187 | LSTM (23K) |
215
+
216
+ ### SNN memory scaling (forward-only vs. BPTT)
217
+
218
+ | Timesteps | PolyStep | BPTT (surrogate) | Savings |
219
+ |-----------|---------|------------------|---------|
220
+ | T=25 | 31.8 MB | 132 MB | 4.2x |
221
+ | T=400 | 51.6 MB | 1,538 MB | **29.8x** |
222
+
223
+ Among gradient-free optimizers PolyStep is the strongest on every task here, at 100 to 10,000x more evaluations than the ES and SPSA baselines. Against the gradient surrogate, PolyStep wins where the non-differentiability is hard (SNN hard LIF, hard MoE routing) and loses where an accurate smooth surrogate exists (int8, argmax, staircase), so its niche is hard non-differentiability rather than non-differentiability in general. On MAX-SAT the domain-specialized probSAT and WalkSAT-style SLS solvers beat every general optimizer (probSAT reaches about 99.6% at 100K variables and 98.9% at 1M); PolyStep is the strongest general-purpose gradient-free method here, not a replacement for a domain solver.
224
+
225
+ ## Features
226
+
227
+ - **Softmax OT solver** with an entropic Sinkhorn alternative.
228
+ - **Subspace compression**: `HybridSubspace` (recommended), `AdaptiveSubspace`, and sparse projection for very large models.
229
+ - **Block-wise OT** for per-layer decomposition.
230
+ - **`torch.compile`** opt-in on hot paths.
231
+ - **Vmap-safe layers**: drop-in attention and LSTM that play nicely with `torch.vmap`.
232
+ - **Sub-linear memory**: forward-only evaluation, no BPTT activation tape (~30x savings at long SNN horizons).
233
+ - **CMA-ES inspired adaptation** of subspace covariance (experimental, monolithic step only; `use_adaptive_radius` is the stable default).
234
+ - **MLP fast path** using batched `torch.bmm` instead of vmap for pure-MLP `nn.Sequential` models.
235
+ - **Ask/tell API**: `PolyStepES` drops into evosax / NeuroEvoBench-style ES harnesses and black-box loops.
236
+
237
+ ## Limitations
238
+
239
+ - **Compute cost.** Roughly tens of millions of forward passes (on the SNN benchmark, around 30M) vs. tens of thousands of Adam gradient steps for the same MNIST accuracy. This is inherent to zeroth-order methods.
240
+ - **High-dimensional NLP.** Near-random accuracy on SST-2 (4.2M parameters trained from scratch). Gradient-free methods do not scale to this regime in our experiments.
241
+ - **Adam baseline.** On a smoothed surrogate, Adam beats PolyStep on int8 (98.1 vs 97.1), argmax (89.1 vs 86.8), and staircase (97.6 vs 93.2), and only loses where the non-differentiability is hard (SNN hard LIF 93.4 vs 80.5; hard MoE routing). The stronger surrogate-gradient / BPTT baseline for SNNs (paper §5.3) is not bundled with this release; see the arXiv preprint.
242
+
243
+ See [`LIMITATIONS.md`](LIMITATIONS.md) for the full discussion.
244
+
245
+ ## Project structure
246
+
247
+ ```
248
+ src/polystep/ Core library (optimizer, solvers, subspaces, geometry)
249
+ tests/ Unit, integration, and regression tests
250
+ examples/ 8 runnable demos (quickstart, SNN, RL, MAX-SAT, MNIST, Loihi 2, STE-free binary net, direct loss minimization)
251
+ experiments/ Paper reproduction: runners, results, baselines
252
+ docs/ API overview, reproducibility guide
253
+ ```
254
+
255
+ ## Documentation
256
+
257
+ | Resource | Description |
258
+ |----------|-------------|
259
+ | [`examples/`](examples/) | 8 runnable demos with output figures |
260
+ | [`experiments/`](experiments/) | Full paper reproduction harness |
261
+ | [`docs/api_overview.md`](docs/api_overview.md) | API reference |
262
+ | [`LIMITATIONS.md`](LIMITATIONS.md) | Known limitations |
263
+ | [`CONTRIBUTING.md`](CONTRIBUTING.md) | Contribution guidelines |
264
+ | [`CHANGELOG.md`](CHANGELOG.md) | Release history |
265
+
266
+ ## Citation
267
+
268
+ If you find this work useful, please consider citing:
269
+
270
+ ```bibtex
271
+ @article{le2026training,
272
+ title={Training Non-Differentiable Networks via Optimal Transport},
273
+ author={Le, An T},
274
+ journal={arXiv preprint arXiv:2605.01928},
275
+ year={2026}
276
+ }
277
+ ```
278
+
279
+ ## Acknowledgments
280
+
281
+ A huge thank you to [**Viet**](https://vietngth.github.io/) for building a beautiful interactive [PolyStep visualization](https://vietngth.github.io/polystep-visualization/), it brings the method to life and makes every step click!
282
+
283
+ ## License
284
+
285
+ Apache License 2.0. See [LICENSE](LICENSE).