polystep 0.7.0__py3-none-any.whl

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 (52) hide show
  1. polystep/__init__.py +176 -0
  2. polystep/_compiled.py +334 -0
  3. polystep/_step_blockwise.py +994 -0
  4. polystep/_step_momentum.py +128 -0
  5. polystep/_step_monolithic.py +1070 -0
  6. polystep/adaptive_subspace.py +762 -0
  7. polystep/api.py +307 -0
  8. polystep/ask_tell.py +164 -0
  9. polystep/benchmarks/__init__.py +62 -0
  10. polystep/benchmarks/baselines.py +604 -0
  11. polystep/benchmarks/rl/__init__.py +13 -0
  12. polystep/benchmarks/rl/cartpole.py +260 -0
  13. polystep/benchmarks/rl/gym_evaluator.py +304 -0
  14. polystep/benchmarks/rl/metrics.py +53 -0
  15. polystep/benchmarks/rl/policies.py +133 -0
  16. polystep/benchmarks/utils.py +1262 -0
  17. polystep/blockwise.py +549 -0
  18. polystep/cma.py +400 -0
  19. polystep/cma_subspace.py +404 -0
  20. polystep/cost_nn.py +633 -0
  21. polystep/costs.py +86 -0
  22. polystep/dynamics.py +138 -0
  23. polystep/epsilon.py +217 -0
  24. polystep/geometry.py +410 -0
  25. polystep/hybrid_subspace.py +1335 -0
  26. polystep/layers/__init__.py +16 -0
  27. polystep/layers/attention.py +243 -0
  28. polystep/layers/rnn.py +276 -0
  29. polystep/objectives/__init__.py +25 -0
  30. polystep/objectives/base.py +77 -0
  31. polystep/objectives/synthetic.py +232 -0
  32. polystep/optimizer.py +1405 -0
  33. polystep/projection/__init__.py +5 -0
  34. polystep/projection/sparse.py +291 -0
  35. polystep/py.typed +0 -0
  36. polystep/quadratic_model.py +285 -0
  37. polystep/solver.py +654 -0
  38. polystep/solvers/__init__.py +34 -0
  39. polystep/solvers/_prelude.py +129 -0
  40. polystep/solvers/base.py +77 -0
  41. polystep/solvers/greedy.py +159 -0
  42. polystep/solvers/kl_softmax.py +200 -0
  43. polystep/solvers/sinkhorn.py +522 -0
  44. polystep/solvers/softmax.py +151 -0
  45. polystep/solvers/tempered_softmax.py +97 -0
  46. polystep/subspace.py +694 -0
  47. polystep/transform.py +365 -0
  48. polystep-0.7.0.dist-info/METADATA +285 -0
  49. polystep-0.7.0.dist-info/RECORD +52 -0
  50. polystep-0.7.0.dist-info/WHEEL +5 -0
  51. polystep-0.7.0.dist-info/licenses/LICENSE +191 -0
  52. polystep-0.7.0.dist-info/top_level.txt +1 -0
polystep/transform.py ADDED
@@ -0,0 +1,365 @@
1
+ """Parameter-particle transformation utilities.
2
+
3
+ Converts between nn.Module state_dict and flat particle arrays,
4
+ handling padding, shared parameter deduplication, and reconstruction
5
+ via ParamLayout metadata.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from collections import OrderedDict
12
+ from dataclasses import dataclass
13
+ from typing import Tuple
14
+
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def get_device(model: nn.Module) -> torch.device:
25
+ """Get device from model's first parameter, defaulting to CPU.
26
+
27
+ Args:
28
+ model: Any PyTorch module.
29
+
30
+ Returns:
31
+ Device of the first parameter, or ``torch.device('cpu')``
32
+ if the module has no parameters or buffers.
33
+ """
34
+ try:
35
+ return next(model.parameters()).device
36
+ except StopIteration:
37
+ return torch.device("cpu")
38
+
39
+
40
+ def create_generator(seed: int, device: torch.device) -> torch.Generator:
41
+ """Create a seeded ``torch.Generator`` on the given device.
42
+
43
+ Args:
44
+ seed: Integer seed for reproducibility.
45
+ device: Device for the generator (must match tensors it will generate).
46
+
47
+ Returns:
48
+ Seeded ``torch.Generator``.
49
+ """
50
+ gen = torch.Generator(device=device)
51
+ gen.manual_seed(seed)
52
+ return gen
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class ParamEntry:
57
+ """Metadata for a single parameter/buffer in the layout.
58
+
59
+ Attributes:
60
+ key: state_dict key (e.g., "fc1.weight").
61
+ shape: Original tensor shape.
62
+ dtype: Original tensor dtype.
63
+ offset: Element offset in the flat (deduplicated) array.
64
+ numel: Number of elements.
65
+ requires_grad: Whether the tensor requires gradient.
66
+ module_path: Parent module path (e.g., "fc1" for "fc1.weight").
67
+ shared_with: Keys sharing the same storage (empty for non-shared).
68
+ """
69
+
70
+ key: str
71
+ shape: Tuple[int, ...]
72
+ dtype: torch.dtype
73
+ offset: int
74
+ numel: int
75
+ requires_grad: bool
76
+ module_path: str
77
+ shared_with: Tuple[str, ...] = ()
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class ParamLayout:
82
+ """Frozen layout describing how to flatten/unflatten nn.Module parameters.
83
+
84
+ Created once via ``from_module()`` and reused for every flatten/unflatten
85
+ call. Stores per-entry metadata, deduplication info for shared parameters,
86
+ and padding/dtype information.
87
+
88
+ Attributes:
89
+ entries: Per-parameter metadata (only canonical/first-seen entries).
90
+ total_params: Total element count (deduplicated).
91
+ padded_size: Total after padding to ``particle_dim`` alignment.
92
+ particle_dim: Number of elements per particle row (default 2).
93
+ dominant_dtype: Most common dtype by element count.
94
+ shared_groups: Tuples of keys sharing the same storage.
95
+ The first key in each group is the canonical one stored in entries.
96
+ _all_keys: All state_dict keys in original order (for unflatten).
97
+ """
98
+
99
+ entries: Tuple[ParamEntry, ...]
100
+ total_params: int
101
+ padded_size: int
102
+ particle_dim: int
103
+ dominant_dtype: torch.dtype
104
+ shared_groups: Tuple[Tuple[str, ...], ...] = ()
105
+ _all_keys: Tuple[str, ...] = ()
106
+
107
+ # ------------------------------------------------------------------
108
+ # Construction
109
+ # ------------------------------------------------------------------
110
+
111
+ @classmethod
112
+ def from_module(
113
+ cls,
114
+ model: nn.Module,
115
+ particle_dim: int = 2,
116
+ ) -> ParamLayout:
117
+ """Create a ``ParamLayout`` from any ``nn.Module``.
118
+
119
+ Uses ``model.state_dict()`` to enumerate all parameters and buffers.
120
+ Shared tensors (same ``data_ptr()``) are deduplicated: only the first
121
+ occurrence is stored in *entries*; sharing relationships are recorded
122
+ in *shared_groups*.
123
+
124
+ Args:
125
+ model: Any PyTorch module.
126
+ particle_dim: Number of elements per particle row.
127
+
128
+ Returns:
129
+ Frozen ``ParamLayout`` ready for ``flatten()`` / ``unflatten()``.
130
+ """
131
+ sd = model.state_dict()
132
+
133
+ if len(sd) == 0:
134
+ return cls(
135
+ entries=(),
136
+ total_params=0,
137
+ padded_size=0,
138
+ particle_dim=particle_dim,
139
+ dominant_dtype=torch.float32,
140
+ shared_groups=(),
141
+ _all_keys=(),
142
+ )
143
+
144
+ # --- Pass 1: detect shared storage via data_ptr ---
145
+ seen_ptrs: dict[int, str] = {} # data_ptr -> canonical key
146
+ canonical_entries: list[ParamEntry] = []
147
+ shared_map: dict[str, list[str]] = {} # canonical_key -> [alias keys]
148
+ offset = 0
149
+
150
+ # Build a lookup for requires_grad from named_parameters.
151
+ # Also collect data_ptrs of trainable params so shared aliases
152
+ # (e.g., tied weights) can be detected even if they appear under
153
+ # a different name in state_dict.
154
+ param_grad = {}
155
+ trainable_ptrs: set[int] = set()
156
+ for name, param in model.named_parameters():
157
+ param_grad[name] = param.requires_grad
158
+ if param.requires_grad:
159
+ trainable_ptrs.add(param.data_ptr())
160
+
161
+ all_keys: list[str] = []
162
+
163
+ for key, tensor in sd.items():
164
+ # Skip non-trainable tensors (buffers). Only trainable
165
+ # parameters (requires_grad=True) belong in the OT particle
166
+ # array. Non-trainable float buffers (e.g., BatchNorm
167
+ # running_mean/running_var) would otherwise drift randomly
168
+ # since the evaluator overrides them with frozen values -
169
+ # the optimizer gets no gradient signal for them.
170
+ # Exception: shared/tied params may appear under a name not
171
+ # in named_parameters() - detect them via data_ptr.
172
+ requires_grad = param_grad.get(key, False)
173
+ is_trainable_alias = tensor.data_ptr() in trainable_ptrs
174
+ if not requires_grad and not is_trainable_alias:
175
+ continue
176
+
177
+ all_keys.append(key)
178
+ ptr = tensor.data_ptr()
179
+
180
+ if ptr in seen_ptrs and tensor.numel() > 0:
181
+ # This tensor shares storage with an earlier one
182
+ canonical_key = seen_ptrs[ptr]
183
+ shared_map.setdefault(canonical_key, [canonical_key]).append(key)
184
+ continue
185
+
186
+ if tensor.numel() > 0:
187
+ seen_ptrs[ptr] = key
188
+
189
+ numel = tensor.numel()
190
+ module_path = key.rsplit(".", 1)[0] if "." in key else ""
191
+
192
+ canonical_entries.append(
193
+ ParamEntry(
194
+ key=key,
195
+ shape=tuple(tensor.shape),
196
+ dtype=tensor.dtype,
197
+ offset=offset,
198
+ numel=numel,
199
+ requires_grad=requires_grad,
200
+ module_path=module_path,
201
+ )
202
+ )
203
+ offset += numel
204
+
205
+ total_params = offset
206
+
207
+ # --- Build shared_groups tuples ---
208
+ shared_groups: list[Tuple[str, ...]] = []
209
+ # Also update entries with shared_with info
210
+ updated_entries: list[ParamEntry] = []
211
+ for entry in canonical_entries:
212
+ if entry.key in shared_map:
213
+ aliases = tuple(shared_map[entry.key])
214
+ shared_groups.append(aliases)
215
+ # Replace entry with shared_with populated
216
+ # shared_with contains alias keys (excluding the canonical one)
217
+ entry = ParamEntry(
218
+ key=entry.key,
219
+ shape=entry.shape,
220
+ dtype=entry.dtype,
221
+ offset=entry.offset,
222
+ numel=entry.numel,
223
+ requires_grad=entry.requires_grad,
224
+ module_path=entry.module_path,
225
+ shared_with=tuple(k for k in aliases if k != entry.key),
226
+ )
227
+ updated_entries.append(entry)
228
+
229
+ # Surface tied-weight detection at INFO level so users see when
230
+ # their model has shared parameters (e.g. transformer embedding
231
+ # tied to lm_head). Otherwise the dedup happens silently and a
232
+ # mysterious parameter-count gap is hard to track down.
233
+ if shared_groups:
234
+ tied_summary = ", ".join(f"{group[0]} <- {{{', '.join(group[1:])}}}" for group in shared_groups)
235
+ logger.info(
236
+ "ParamLayout deduplicated tied / shared weights: %s",
237
+ tied_summary,
238
+ )
239
+
240
+ # --- Determine dominant dtype ---
241
+ dtype_counts: dict[torch.dtype, int] = {}
242
+ for entry in updated_entries:
243
+ dtype_counts[entry.dtype] = dtype_counts.get(entry.dtype, 0) + entry.numel
244
+ dominant_dtype = max(dtype_counts, key=dtype_counts.get) if dtype_counts else torch.float32
245
+
246
+ # --- Padding ---
247
+ padded_size = total_params + ((-total_params) % particle_dim) if total_params > 0 else 0
248
+
249
+ return cls(
250
+ entries=tuple(updated_entries),
251
+ total_params=total_params,
252
+ padded_size=padded_size,
253
+ particle_dim=particle_dim,
254
+ dominant_dtype=dominant_dtype,
255
+ shared_groups=tuple(shared_groups),
256
+ _all_keys=tuple(all_keys),
257
+ )
258
+
259
+ # ------------------------------------------------------------------
260
+ # Flatten / Unflatten
261
+ # ------------------------------------------------------------------
262
+
263
+ def batch_unflatten(self, particles_batch: torch.Tensor) -> dict[str, torch.Tensor]:
264
+ """Convert N particle vectors to stacked param dicts for vmap.
265
+
266
+ Each key maps to a tensor with an extra leading batch dimension.
267
+ Shared parameters produce aliased entries (same tensor object).
268
+
269
+ Args:
270
+ particles_batch: Tensor of shape ``(N, rows, particle_dim)`` or
271
+ ``(N, flat_size)``. The last dimensions are flattened internally.
272
+
273
+ Returns:
274
+ Dict ``{key: tensor of shape (N, *original_shape)}`` suitable for
275
+ ``torch.vmap`` over dimension 0.
276
+ """
277
+ if self.total_params == 0:
278
+ return {}
279
+
280
+ N = particles_batch.shape[0]
281
+ flat = particles_batch.reshape(N, -1)
282
+ stacked: dict[str, torch.Tensor] = {}
283
+
284
+ for entry in self.entries:
285
+ param = flat[:, entry.offset : entry.offset + entry.numel]
286
+ param = param.reshape(N, *entry.shape)
287
+ # Only cast if this entry's dtype differs from dominant_dtype
288
+ # (avoids a no-op .to() kernel launch per entry).
289
+ if entry.dtype != self.dominant_dtype:
290
+ param = param.to(entry.dtype)
291
+ stacked[entry.key] = param
292
+ for alias in entry.shared_with:
293
+ stacked[alias] = param
294
+
295
+ return stacked
296
+
297
+ # ------------------------------------------------------------------
298
+ # Flatten / Unflatten
299
+ # ------------------------------------------------------------------
300
+
301
+ def flatten(self, model: nn.Module) -> torch.Tensor:
302
+ """Flatten model state_dict to a 2D particle tensor.
303
+
304
+ Each entry (deduplicated) is cast to ``dominant_dtype``, concatenated,
305
+ padded, and reshaped to ``(N, particle_dim)``.
306
+
307
+ Args:
308
+ model: Module whose state_dict matches this layout.
309
+
310
+ Returns:
311
+ Tensor of shape ``(N, particle_dim)`` where
312
+ ``N * particle_dim >= total_params``.
313
+ """
314
+ if self.total_params == 0:
315
+ return torch.zeros(0, self.particle_dim, dtype=self.dominant_dtype)
316
+
317
+ sd = model.state_dict()
318
+ parts: list[torch.Tensor] = []
319
+ for entry in self.entries:
320
+ tensor = sd[entry.key]
321
+ parts.append(tensor.detach().to(self.dominant_dtype).reshape(-1))
322
+
323
+ raveled = torch.cat(parts)
324
+
325
+ pad_size = self.padded_size - raveled.shape[0]
326
+ if pad_size > 0:
327
+ raveled = F.pad(raveled, (0, pad_size))
328
+
329
+ return raveled.reshape(-1, self.particle_dim)
330
+
331
+ def unflatten(self, particles: torch.Tensor) -> OrderedDict:
332
+ """Reconstruct a state_dict from a particle tensor.
333
+
334
+ Reverses ``flatten()``: slices the flat array by offset/numel,
335
+ reshapes to original shape, casts back to original dtype, and
336
+ handles shared parameters by assigning the canonical tensor to
337
+ all alias keys.
338
+
339
+ Args:
340
+ particles: Tensor of shape ``(N, particle_dim)``.
341
+
342
+ Returns:
343
+ ``OrderedDict`` compatible with ``model.load_state_dict()``.
344
+ """
345
+ if self.total_params == 0:
346
+ return OrderedDict()
347
+
348
+ flat = particles.reshape(-1)
349
+ reconstructed: dict[str, torch.Tensor] = {}
350
+
351
+ for entry in self.entries:
352
+ param = flat[entry.offset : entry.offset + entry.numel]
353
+ param = param.reshape(entry.shape).to(entry.dtype)
354
+ reconstructed[entry.key] = param
355
+
356
+ # Shared parameters: assign the same tensor to alias keys
357
+ for alias_key in entry.shared_with:
358
+ reconstructed[alias_key] = param
359
+
360
+ # Return in original key order
361
+ result = OrderedDict()
362
+ for key in self._all_keys:
363
+ result[key] = reconstructed[key]
364
+
365
+ return result
@@ -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).