softopt 0.7.3__tar.gz → 0.8.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.
- {softopt-0.7.3/softopt.egg-info → softopt-0.8.0}/PKG-INFO +38 -1
- {softopt-0.7.3 → softopt-0.8.0}/README.md +37 -0
- {softopt-0.7.3 → softopt-0.8.0}/pyproject.toml +1 -1
- {softopt-0.7.3 → softopt-0.8.0}/softopt/__init__.py +3 -2
- {softopt-0.7.3 → softopt-0.8.0}/softopt/numpy_optimizer.py +77 -1
- {softopt-0.7.3 → softopt-0.8.0/softopt.egg-info}/PKG-INFO +38 -1
- {softopt-0.7.3 → softopt-0.8.0}/softopt.egg-info/SOURCES.txt +1 -0
- softopt-0.8.0/tests/test_mode.py +80 -0
- {softopt-0.7.3 → softopt-0.8.0}/LICENSE +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/setup.cfg +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/softopt/_torch_compile.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/softopt/calibrate.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/softopt/compile.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/softopt/soft_number.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/softopt/torch_optimizer.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/softopt.egg-info/dependency_links.txt +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/softopt.egg-info/requires.txt +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/softopt.egg-info/top_level.txt +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/tests/test_basic.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/tests/test_calibrate.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/tests/test_causal.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/tests/test_compile.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/tests/test_exact_d2.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/tests/test_measured_slope.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/tests/test_soft_number.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/tests/test_torch.py +0 -0
- {softopt-0.7.3 → softopt-0.8.0}/tests/test_torch_compile.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: softopt
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.8.0
|
|
4
4
|
Summary: An optimization layer that closes the gap between your model and the real system, built on Klein–Maimon soft-number calculus
|
|
5
5
|
Author: Ido Angel
|
|
6
6
|
License: MIT
|
|
@@ -76,6 +76,7 @@ Everything else stays as it was: the same Adam update, the same measurements, no
|
|
|
76
76
|
|---|---|
|
|
77
77
|
| a model with uncertain parameters + measurements of the real system | **SoftOpt, `calibrate=True`** |
|
|
78
78
|
| an exact model + noisy measurements | SoftOpt, default settings |
|
|
79
|
+
| a model that may or may not be right, and you cannot say which | **SoftOpt, `mode="auto"`** (new in 0.8.0) |
|
|
79
80
|
| you can compute a residual vector `model(theta) - data` | `scipy.optimize.least_squares` |
|
|
80
81
|
| only a learned black-box surrogate (a neural network) + an expensive oracle | Bayesian optimization |
|
|
81
82
|
|
|
@@ -91,6 +92,40 @@ calibrated model is evaluated at the target before the step is taken.
|
|
|
91
92
|
`calibrate=True` also works on a plain `model(theta)` with no bias parameters; naming the uncertain parameters is
|
|
92
93
|
what makes it reliable across domains.
|
|
93
94
|
|
|
95
|
+
## `mode="auto"`: when you do not know whether your model is right (new in 0.8.0)
|
|
96
|
+
|
|
97
|
+
The default correction pulls towards the model's optimum. When the model is right, that is what wins; when the
|
|
98
|
+
model's optimum is displaced from the real system's, it pulls the answer back to the wrong place.
|
|
99
|
+
`mode="auto"` decides from the measurements you already pay for:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
opt = SoftOpt(n, g, lr=0.02, mode="auto")
|
|
103
|
+
for step in range(num_steps):
|
|
104
|
+
grad, direction, slope = spsa_gradient(measure, theta, c=0.1)
|
|
105
|
+
slope_sd = np.sqrt(2) * reading_sd / (2 * 0.1) # standard deviation of the measured slope
|
|
106
|
+
theta = opt.step(theta, grad, direction=direction, measured_slope=slope, slope_sd=slope_sd)
|
|
107
|
+
opt.mode_state # {'active': 'full' or 'mn', 'switch_step': ..., 'n_conclusive': ..., 'agreement': ...}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
It starts as the default SoftOpt. A probe pair is conclusive when the measured slope stands out of its noise
|
|
111
|
+
(|slope| > 2 sd). Once 8 conclusive pairs exist, if fewer than 60% agree in sign with the model's slope along the
|
|
112
|
+
same direction, it switches once, permanently, to `mode="mn"`: one bounded Newton step along the probed direction
|
|
113
|
+
from the *measured* slope and the model's *curvature* (D2, from the nested soft pass). The readings then decide
|
|
114
|
+
which way to move and the model only how far. Until a switch, `mode="auto"` is bit-identical to the default.
|
|
115
|
+
|
|
116
|
+
What it was tested on (pre-registered; rule frozen before each test):
|
|
117
|
+
- H4 UCCSD simulation, start 20 mHa above the device optimum, 300 readings, 10 new machines per condition:
|
|
118
|
+
(lr 1e-4, mn_lr 0.3): exact model 0.15 mHa (identical to default SoftOpt, no false switch); displaced model
|
|
119
|
+
(shift and two curvature-changing over-rotation levels) 3.0–4.3 mHa, against 19 for the default SoftOpt
|
|
120
|
+
(better in 30/30 runs) and 3.1–5.1 for Adam. Detecting the mismatch costs about 12–14% of the budget: it ends 0.1–0.5 mHa behind
|
|
121
|
+
`mode="mn"` chosen in advance.
|
|
122
|
+
- The official FakeFez benchmarks (lr 0.02, mn_lr 1.0): it never switched and kept the results (H2 0.21 mHa, chemical accuracy 10/10,
|
|
123
|
+
vs COBYLA 5.81; H4 367 vs Adam 1219, 10/10).
|
|
124
|
+
- `mode="mn"` on its own: better than a tuned fixed gain on the same measurements in every test above, but worse
|
|
125
|
+
than the default SoftOpt whenever the model is right. Use it only when you know the model's optimum is off.
|
|
126
|
+
|
|
127
|
+
`mode="auto"` and `mode="mn"` are in `SoftOpt` (numpy). They are not combined with `calibrate=True`.
|
|
128
|
+
|
|
94
129
|
## Results across domains
|
|
95
130
|
|
|
96
131
|
One small problem per domain, one protocol for all: the model is the domain's standard simulator with its
|
|
@@ -364,6 +399,8 @@ The full soft-number algebra is available from the package (`from softopt import
|
|
|
364
399
|
measure a real system.
|
|
365
400
|
- default (`slope="model"`) — your model is exact; the measurements are only noisy.
|
|
366
401
|
- `slope="measured"` — the model is approximate and you do not want to name its uncertain parameters.
|
|
402
|
+
- `mode="auto"` — you do not know whether the model's optimum matches the real system's; it keeps the default
|
|
403
|
+
when the readings agree with the model and switches to `mode="mn"` when they do not.
|
|
367
404
|
|
|
368
405
|
`calibrate=True` is available in `SoftOpt` (numpy). `SoftOptTorch` runs the default correction.
|
|
369
406
|
|
|
@@ -50,6 +50,7 @@ Everything else stays as it was: the same Adam update, the same measurements, no
|
|
|
50
50
|
|---|---|
|
|
51
51
|
| a model with uncertain parameters + measurements of the real system | **SoftOpt, `calibrate=True`** |
|
|
52
52
|
| an exact model + noisy measurements | SoftOpt, default settings |
|
|
53
|
+
| a model that may or may not be right, and you cannot say which | **SoftOpt, `mode="auto"`** (new in 0.8.0) |
|
|
53
54
|
| you can compute a residual vector `model(theta) - data` | `scipy.optimize.least_squares` |
|
|
54
55
|
| only a learned black-box surrogate (a neural network) + an expensive oracle | Bayesian optimization |
|
|
55
56
|
|
|
@@ -65,6 +66,40 @@ calibrated model is evaluated at the target before the step is taken.
|
|
|
65
66
|
`calibrate=True` also works on a plain `model(theta)` with no bias parameters; naming the uncertain parameters is
|
|
66
67
|
what makes it reliable across domains.
|
|
67
68
|
|
|
69
|
+
## `mode="auto"`: when you do not know whether your model is right (new in 0.8.0)
|
|
70
|
+
|
|
71
|
+
The default correction pulls towards the model's optimum. When the model is right, that is what wins; when the
|
|
72
|
+
model's optimum is displaced from the real system's, it pulls the answer back to the wrong place.
|
|
73
|
+
`mode="auto"` decides from the measurements you already pay for:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
opt = SoftOpt(n, g, lr=0.02, mode="auto")
|
|
77
|
+
for step in range(num_steps):
|
|
78
|
+
grad, direction, slope = spsa_gradient(measure, theta, c=0.1)
|
|
79
|
+
slope_sd = np.sqrt(2) * reading_sd / (2 * 0.1) # standard deviation of the measured slope
|
|
80
|
+
theta = opt.step(theta, grad, direction=direction, measured_slope=slope, slope_sd=slope_sd)
|
|
81
|
+
opt.mode_state # {'active': 'full' or 'mn', 'switch_step': ..., 'n_conclusive': ..., 'agreement': ...}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
It starts as the default SoftOpt. A probe pair is conclusive when the measured slope stands out of its noise
|
|
85
|
+
(|slope| > 2 sd). Once 8 conclusive pairs exist, if fewer than 60% agree in sign with the model's slope along the
|
|
86
|
+
same direction, it switches once, permanently, to `mode="mn"`: one bounded Newton step along the probed direction
|
|
87
|
+
from the *measured* slope and the model's *curvature* (D2, from the nested soft pass). The readings then decide
|
|
88
|
+
which way to move and the model only how far. Until a switch, `mode="auto"` is bit-identical to the default.
|
|
89
|
+
|
|
90
|
+
What it was tested on (pre-registered; rule frozen before each test):
|
|
91
|
+
- H4 UCCSD simulation, start 20 mHa above the device optimum, 300 readings, 10 new machines per condition:
|
|
92
|
+
(lr 1e-4, mn_lr 0.3): exact model 0.15 mHa (identical to default SoftOpt, no false switch); displaced model
|
|
93
|
+
(shift and two curvature-changing over-rotation levels) 3.0–4.3 mHa, against 19 for the default SoftOpt
|
|
94
|
+
(better in 30/30 runs) and 3.1–5.1 for Adam. Detecting the mismatch costs about 12–14% of the budget: it ends 0.1–0.5 mHa behind
|
|
95
|
+
`mode="mn"` chosen in advance.
|
|
96
|
+
- The official FakeFez benchmarks (lr 0.02, mn_lr 1.0): it never switched and kept the results (H2 0.21 mHa, chemical accuracy 10/10,
|
|
97
|
+
vs COBYLA 5.81; H4 367 vs Adam 1219, 10/10).
|
|
98
|
+
- `mode="mn"` on its own: better than a tuned fixed gain on the same measurements in every test above, but worse
|
|
99
|
+
than the default SoftOpt whenever the model is right. Use it only when you know the model's optimum is off.
|
|
100
|
+
|
|
101
|
+
`mode="auto"` and `mode="mn"` are in `SoftOpt` (numpy). They are not combined with `calibrate=True`.
|
|
102
|
+
|
|
68
103
|
## Results across domains
|
|
69
104
|
|
|
70
105
|
One small problem per domain, one protocol for all: the model is the domain's standard simulator with its
|
|
@@ -338,6 +373,8 @@ The full soft-number algebra is available from the package (`from softopt import
|
|
|
338
373
|
measure a real system.
|
|
339
374
|
- default (`slope="model"`) — your model is exact; the measurements are only noisy.
|
|
340
375
|
- `slope="measured"` — the model is approximate and you do not want to name its uncertain parameters.
|
|
376
|
+
- `mode="auto"` — you do not know whether the model's optimum matches the real system's; it keeps the default
|
|
377
|
+
when the readings agree with the model and switches to `mode="mn"` when they do not.
|
|
341
378
|
|
|
342
379
|
`calibrate=True` is available in `SoftOpt` (numpy). `SoftOptTorch` runs the default correction.
|
|
343
380
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "softopt"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.8.0"
|
|
8
8
|
description = "An optimization layer that closes the gap between your model and the real system, built on Klein–Maimon soft-number calculus"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = { text = "MIT" }
|
|
@@ -11,7 +11,8 @@ model (a simulator, a circuit, a physical law) and the real system you measure.
|
|
|
11
11
|
|
|
12
12
|
calibrate=True (new in 0.7.0): soft_compile(model, n_params, n_bias=k) for model(theta, beta), then
|
|
13
13
|
SoftOpt(..., calibrate=True, bias_scale=s) -- the measurements also calibrate the model's uncertain parameters.
|
|
14
|
-
|
|
14
|
+
mode="auto" (new in 0.8.0): start as full SoftOpt and switch once to the soft first stage ("mn": measured
|
|
15
|
+
slope, model curvature) when the readings keep disagreeing with the model's slope. See README.md.
|
|
15
16
|
"""
|
|
16
17
|
from .numpy_optimizer import SoftOpt, spsa_gradient
|
|
17
18
|
from .compile import soft_compile
|
|
@@ -37,4 +38,4 @@ __all__ = [
|
|
|
37
38
|
"sadd", "sneg", "ssub", "smul", "sinv", "sdiv",
|
|
38
39
|
"spow", "sroot", "ssqrt", "ssin", "scos", "sexp", "slog",
|
|
39
40
|
]
|
|
40
|
-
__version__ = "0.
|
|
41
|
+
__version__ = "0.8.0"
|
|
@@ -31,6 +31,27 @@ D1 (the slope) has two possible sources, set by `slope`:
|
|
|
31
31
|
|
|
32
32
|
`spsa_gradient` returns the gradient estimate, the direction and the measured
|
|
33
33
|
slope in one call, ready for either mode.
|
|
34
|
+
|
|
35
|
+
mode (new in 0.8.0) chooses how the model is used:
|
|
36
|
+
|
|
37
|
+
mode="full" (default) exactly the 0.7.x behaviour above.
|
|
38
|
+
mode="mn" no Adam and no extra correction: one bounded Newton step along the probed
|
|
39
|
+
direction, t = clip(-measured_slope / D2, newton_lo, newton_hi), times mn_lr,
|
|
40
|
+
with D2 the model's curvature along that direction (fallback
|
|
41
|
+
clip(-eta_fallback * measured_slope) when D2 <= 1e-8). The model only decides
|
|
42
|
+
HOW FAR to move; the readings decide which way, so a model whose optimum is
|
|
43
|
+
displaced does not pull the answer back to it.
|
|
44
|
+
mode="auto" start as "full"; switch once, permanently, to "mn" when the readings disagree
|
|
45
|
+
with the model. A probe pair is conclusive when |measured_slope| >
|
|
46
|
+
auto_z * slope_sd; once auto_min_pairs conclusive pairs exist, if fewer than
|
|
47
|
+
auto_threshold of them agree in sign with the model slope along the same
|
|
48
|
+
direction, the optimizer switches. Until a switch "auto" is bit-identical to
|
|
49
|
+
"full". Defaults (8 pairs, 0.6, z = 2, mn_lr = 1.0) are the rule frozen and
|
|
50
|
+
tested in the pre-registered selector study (H4 simulation, then FakeFez H2/H4).
|
|
51
|
+
"mn" and "auto" need direction=, measured_slope= (and for "auto" slope_sd=, the
|
|
52
|
+
standard deviation of measured_slope; for an SPSA pair with reading sd s and
|
|
53
|
+
offset c it is sqrt(2) * s / (2c)) on every step. `mode_state` reports the
|
|
54
|
+
current mode, the switch step and the agreement so far.
|
|
34
55
|
"""
|
|
35
56
|
import numpy as np
|
|
36
57
|
|
|
@@ -39,9 +60,18 @@ class SoftOpt:
|
|
|
39
60
|
def __init__(self, n_params, g_delta, lr=0.02, betas=(0.9, 0.999), eps=1e-8,
|
|
40
61
|
newton_lo=-0.5, newton_hi=0.5, eta_fallback=0.3,
|
|
41
62
|
h_fd=1e-4, seed=None, slope="model", exact_d2="auto", calibrate=False, bias_scale=None,
|
|
63
|
+
mode="full", mn_lr=1.0, auto_min_pairs=8, auto_threshold=0.6, auto_z=2.0,
|
|
42
64
|
_test_frozen_constant=1.0):
|
|
43
65
|
if slope not in ("model", "measured"):
|
|
44
66
|
raise ValueError(f'slope must be "model" or "measured", got {slope!r}')
|
|
67
|
+
if mode not in ("full", "mn", "auto"):
|
|
68
|
+
raise ValueError(f'mode must be "full", "mn" or "auto", got {mode!r}')
|
|
69
|
+
if mode != "full" and calibrate:
|
|
70
|
+
raise ValueError('mode="mn"/"auto" is not combined with calibrate=True (use mode="full")')
|
|
71
|
+
self.mode, self.mn_lr = mode, mn_lr
|
|
72
|
+
self.auto_min_pairs, self.auto_threshold, self.auto_z = auto_min_pairs, auto_threshold, auto_z
|
|
73
|
+
self._active = "mn" if mode == "mn" else "full"
|
|
74
|
+
self._agree, self._switch_step, self._n_steps = [], None, 0
|
|
45
75
|
self.slope = slope
|
|
46
76
|
self.g_delta = g_delta
|
|
47
77
|
self.lr = lr
|
|
@@ -71,8 +101,54 @@ class SoftOpt:
|
|
|
71
101
|
self._ablation_rng = None
|
|
72
102
|
self._test_frozen_constant = _test_frozen_constant
|
|
73
103
|
|
|
74
|
-
def step(self, theta, grad_estimate, direction=None, measured_slope=None,
|
|
104
|
+
def step(self, theta, grad_estimate, direction=None, measured_slope=None, slope_sd=None,
|
|
75
105
|
_test_magnitude_source=None, _test_foreign_sampler=None, _test_rng=None):
|
|
106
|
+
if self.mode == "full":
|
|
107
|
+
return self._full_step(theta, grad_estimate, direction, measured_slope,
|
|
108
|
+
_test_magnitude_source, _test_foreign_sampler, _test_rng)
|
|
109
|
+
theta = np.asarray(theta, dtype=float)
|
|
110
|
+
if direction is None or measured_slope is None:
|
|
111
|
+
raise ValueError(f'mode="{self.mode}" needs direction= and measured_slope= on every step '
|
|
112
|
+
'(spsa_gradient() returns both)')
|
|
113
|
+
direction = np.asarray(direction, dtype=float)
|
|
114
|
+
if direction.shape != theta.shape:
|
|
115
|
+
raise ValueError(f"direction has shape {direction.shape}, theta has {theta.shape}")
|
|
116
|
+
sl = float(measured_slope)
|
|
117
|
+
if self._active == "full": # mode="auto", not yet switched
|
|
118
|
+
if slope_sd is None:
|
|
119
|
+
raise ValueError('mode="auto" needs slope_sd= (the standard deviation of measured_slope) '
|
|
120
|
+
'on every step')
|
|
121
|
+
if abs(sl) > self.auto_z * float(slope_sd):
|
|
122
|
+
self._agree.append(bool(np.sign(self.g_delta(theta, direction)) == np.sign(sl)))
|
|
123
|
+
if len(self._agree) >= self.auto_min_pairs and np.mean(self._agree) < self.auto_threshold:
|
|
124
|
+
self._active, self._switch_step = "mn", self._n_steps
|
|
125
|
+
self._n_steps += 1
|
|
126
|
+
if self._active == "full":
|
|
127
|
+
return self._full_step(theta, grad_estimate, direction, measured_slope,
|
|
128
|
+
_test_magnitude_source, _test_foreign_sampler, _test_rng)
|
|
129
|
+
return self._mn_step(theta, direction, sl)
|
|
130
|
+
|
|
131
|
+
def _mn_step(self, theta, d, sl):
|
|
132
|
+
if self._d1_d2 is not None:
|
|
133
|
+
D2 = self._d1_d2(theta, d)[1]
|
|
134
|
+
else:
|
|
135
|
+
D2 = (self.g_delta(theta + self.h_fd * d, d) - self.g_delta(theta - self.h_fd * d, d)) / (2 * self.h_fd)
|
|
136
|
+
if D2 > 1e-8:
|
|
137
|
+
t = float(np.clip(-sl / D2, self.newton_lo, self.newton_hi))
|
|
138
|
+
else:
|
|
139
|
+
t = float(np.clip(-self.eta_fallback * sl, self.newton_lo, self.newton_hi))
|
|
140
|
+
return theta + self.mn_lr * t * d
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def mode_state(self):
|
|
144
|
+
"""mode="auto"/"mn": the mode in use, the step at which "auto" switched (None if it has not),
|
|
145
|
+
the number of conclusive probe pairs and the fraction that agreed with the model's slope."""
|
|
146
|
+
return dict(mode=self.mode, active=self._active, switch_step=self._switch_step,
|
|
147
|
+
n_conclusive=len(self._agree),
|
|
148
|
+
agreement=float(np.mean(self._agree)) if self._agree else None)
|
|
149
|
+
|
|
150
|
+
def _full_step(self, theta, grad_estimate, direction=None, measured_slope=None,
|
|
151
|
+
_test_magnitude_source=None, _test_foreign_sampler=None, _test_rng=None):
|
|
76
152
|
"""One complete optimizer step: Adam base update + Newton-style
|
|
77
153
|
correction from the known model, in a single call.
|
|
78
154
|
theta: current parameters (np.ndarray)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: softopt
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.8.0
|
|
4
4
|
Summary: An optimization layer that closes the gap between your model and the real system, built on Klein–Maimon soft-number calculus
|
|
5
5
|
Author: Ido Angel
|
|
6
6
|
License: MIT
|
|
@@ -76,6 +76,7 @@ Everything else stays as it was: the same Adam update, the same measurements, no
|
|
|
76
76
|
|---|---|
|
|
77
77
|
| a model with uncertain parameters + measurements of the real system | **SoftOpt, `calibrate=True`** |
|
|
78
78
|
| an exact model + noisy measurements | SoftOpt, default settings |
|
|
79
|
+
| a model that may or may not be right, and you cannot say which | **SoftOpt, `mode="auto"`** (new in 0.8.0) |
|
|
79
80
|
| you can compute a residual vector `model(theta) - data` | `scipy.optimize.least_squares` |
|
|
80
81
|
| only a learned black-box surrogate (a neural network) + an expensive oracle | Bayesian optimization |
|
|
81
82
|
|
|
@@ -91,6 +92,40 @@ calibrated model is evaluated at the target before the step is taken.
|
|
|
91
92
|
`calibrate=True` also works on a plain `model(theta)` with no bias parameters; naming the uncertain parameters is
|
|
92
93
|
what makes it reliable across domains.
|
|
93
94
|
|
|
95
|
+
## `mode="auto"`: when you do not know whether your model is right (new in 0.8.0)
|
|
96
|
+
|
|
97
|
+
The default correction pulls towards the model's optimum. When the model is right, that is what wins; when the
|
|
98
|
+
model's optimum is displaced from the real system's, it pulls the answer back to the wrong place.
|
|
99
|
+
`mode="auto"` decides from the measurements you already pay for:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
opt = SoftOpt(n, g, lr=0.02, mode="auto")
|
|
103
|
+
for step in range(num_steps):
|
|
104
|
+
grad, direction, slope = spsa_gradient(measure, theta, c=0.1)
|
|
105
|
+
slope_sd = np.sqrt(2) * reading_sd / (2 * 0.1) # standard deviation of the measured slope
|
|
106
|
+
theta = opt.step(theta, grad, direction=direction, measured_slope=slope, slope_sd=slope_sd)
|
|
107
|
+
opt.mode_state # {'active': 'full' or 'mn', 'switch_step': ..., 'n_conclusive': ..., 'agreement': ...}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
It starts as the default SoftOpt. A probe pair is conclusive when the measured slope stands out of its noise
|
|
111
|
+
(|slope| > 2 sd). Once 8 conclusive pairs exist, if fewer than 60% agree in sign with the model's slope along the
|
|
112
|
+
same direction, it switches once, permanently, to `mode="mn"`: one bounded Newton step along the probed direction
|
|
113
|
+
from the *measured* slope and the model's *curvature* (D2, from the nested soft pass). The readings then decide
|
|
114
|
+
which way to move and the model only how far. Until a switch, `mode="auto"` is bit-identical to the default.
|
|
115
|
+
|
|
116
|
+
What it was tested on (pre-registered; rule frozen before each test):
|
|
117
|
+
- H4 UCCSD simulation, start 20 mHa above the device optimum, 300 readings, 10 new machines per condition:
|
|
118
|
+
(lr 1e-4, mn_lr 0.3): exact model 0.15 mHa (identical to default SoftOpt, no false switch); displaced model
|
|
119
|
+
(shift and two curvature-changing over-rotation levels) 3.0–4.3 mHa, against 19 for the default SoftOpt
|
|
120
|
+
(better in 30/30 runs) and 3.1–5.1 for Adam. Detecting the mismatch costs about 12–14% of the budget: it ends 0.1–0.5 mHa behind
|
|
121
|
+
`mode="mn"` chosen in advance.
|
|
122
|
+
- The official FakeFez benchmarks (lr 0.02, mn_lr 1.0): it never switched and kept the results (H2 0.21 mHa, chemical accuracy 10/10,
|
|
123
|
+
vs COBYLA 5.81; H4 367 vs Adam 1219, 10/10).
|
|
124
|
+
- `mode="mn"` on its own: better than a tuned fixed gain on the same measurements in every test above, but worse
|
|
125
|
+
than the default SoftOpt whenever the model is right. Use it only when you know the model's optimum is off.
|
|
126
|
+
|
|
127
|
+
`mode="auto"` and `mode="mn"` are in `SoftOpt` (numpy). They are not combined with `calibrate=True`.
|
|
128
|
+
|
|
94
129
|
## Results across domains
|
|
95
130
|
|
|
96
131
|
One small problem per domain, one protocol for all: the model is the domain's standard simulator with its
|
|
@@ -364,6 +399,8 @@ The full soft-number algebra is available from the package (`from softopt import
|
|
|
364
399
|
measure a real system.
|
|
365
400
|
- default (`slope="model"`) — your model is exact; the measurements are only noisy.
|
|
366
401
|
- `slope="measured"` — the model is approximate and you do not want to name its uncertain parameters.
|
|
402
|
+
- `mode="auto"` — you do not know whether the model's optimum matches the real system's; it keeps the default
|
|
403
|
+
when the readings agree with the model and switches to `mode="mn"` when they do not.
|
|
367
404
|
|
|
368
405
|
`calibrate=True` is available in `SoftOpt` (numpy). `SoftOptTorch` runs the default correction.
|
|
369
406
|
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""mode="full" / "mn" / "auto" (0.8.0)."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pytest
|
|
4
|
+
from softopt import SoftOpt, spsa_gradient
|
|
5
|
+
|
|
6
|
+
N = 6
|
|
7
|
+
A = np.linspace(-0.5, 0.5, N) # model optimum
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def g_model(theta, d): # model f = sum (theta - A)^2 + 0.1 sum theta^4 : directional slope
|
|
11
|
+
return float(np.dot(2 * (theta - A) + 0.4 * theta ** 3, d))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _d1_d2(theta, d):
|
|
15
|
+
return g_model(theta, d), float(np.dot(2 + 1.2 * theta ** 2, d * d))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
g_model.d1_d2 = _d1_d2
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def device(shift, sd, rng):
|
|
22
|
+
def f(th):
|
|
23
|
+
x = th + shift
|
|
24
|
+
return float(np.sum((x - A) ** 2) + 0.1 * np.sum(x ** 4) + rng.normal(0, sd))
|
|
25
|
+
return f
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def truth(th, shift):
|
|
29
|
+
x = th + shift
|
|
30
|
+
return float(np.sum((x - A) ** 2) + 0.1 * np.sum(x ** 4))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def run(mode, shift, steps=150, seed=0, sd=0.01, c=0.1):
|
|
34
|
+
rng = np.random.default_rng(seed); probe = np.random.default_rng(seed + 1)
|
|
35
|
+
f = device(shift, sd, rng)
|
|
36
|
+
o = SoftOpt(N, g_model, lr=0.02, seed=seed + 999, mode=mode)
|
|
37
|
+
x = np.zeros(N)
|
|
38
|
+
for _ in range(steps):
|
|
39
|
+
g, d, sl = spsa_gradient(f, x, c=c, rng=probe)
|
|
40
|
+
x = o.step(x, g, direction=d, measured_slope=sl, slope_sd=np.sqrt(2) * sd / (2 * c))
|
|
41
|
+
return x, o
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_auto_without_switch_is_bit_identical_to_full():
|
|
45
|
+
xa, oa = run("auto", 0.0)
|
|
46
|
+
xf, _ = run("full", 0.0)
|
|
47
|
+
assert oa.mode_state["switch_step"] is None
|
|
48
|
+
assert oa.mode_state["n_conclusive"] >= 8
|
|
49
|
+
assert np.array_equal(xa, xf)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_auto_switches_when_model_is_displaced_and_beats_full():
|
|
53
|
+
shift = np.full(N, 0.6)
|
|
54
|
+
xa, oa = run("auto", shift)
|
|
55
|
+
xf, _ = run("full", shift)
|
|
56
|
+
assert oa.mode_state["switch_step"] is not None and oa.mode_state["agreement"] < 0.6
|
|
57
|
+
assert truth(xa, shift) < truth(xf, shift)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_mn_converges_to_the_device_optimum_not_the_model_optimum():
|
|
61
|
+
shift = np.full(N, 0.6)
|
|
62
|
+
xm, _ = run("mn", shift, steps=300)
|
|
63
|
+
start = truth(np.zeros(N), shift)
|
|
64
|
+
model_opt_on_device = truth(A, shift) # where full SoftOpt is pulled to
|
|
65
|
+
assert truth(xm, shift) < 0.05 * start and truth(xm, shift) < 0.05 * model_opt_on_device
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_full_default_unchanged():
|
|
69
|
+
o = SoftOpt(N, g_model, seed=1)
|
|
70
|
+
assert o.mode == "full" and o.mode_state["active"] == "full"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_errors():
|
|
74
|
+
with pytest.raises(ValueError):
|
|
75
|
+
SoftOpt(N, g_model, mode="other")
|
|
76
|
+
o = SoftOpt(N, g_model, mode="auto")
|
|
77
|
+
with pytest.raises(ValueError):
|
|
78
|
+
o.step(np.zeros(N), np.zeros(N), direction=np.ones(N), measured_slope=0.1) # no slope_sd
|
|
79
|
+
with pytest.raises(ValueError):
|
|
80
|
+
SoftOpt(N, g_model, mode="mn").step(np.zeros(N), np.zeros(N)) # no direction
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|