softopt 0.7.3__tar.gz → 0.8.1__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 (27) hide show
  1. {softopt-0.7.3/softopt.egg-info → softopt-0.8.1}/PKG-INFO +53 -1
  2. {softopt-0.7.3 → softopt-0.8.1}/README.md +52 -0
  3. {softopt-0.7.3 → softopt-0.8.1}/pyproject.toml +1 -1
  4. {softopt-0.7.3 → softopt-0.8.1}/softopt/__init__.py +3 -2
  5. {softopt-0.7.3 → softopt-0.8.1}/softopt/numpy_optimizer.py +85 -1
  6. {softopt-0.7.3 → softopt-0.8.1/softopt.egg-info}/PKG-INFO +53 -1
  7. {softopt-0.7.3 → softopt-0.8.1}/softopt.egg-info/SOURCES.txt +1 -0
  8. softopt-0.8.1/tests/test_mode.py +95 -0
  9. {softopt-0.7.3 → softopt-0.8.1}/LICENSE +0 -0
  10. {softopt-0.7.3 → softopt-0.8.1}/setup.cfg +0 -0
  11. {softopt-0.7.3 → softopt-0.8.1}/softopt/_torch_compile.py +0 -0
  12. {softopt-0.7.3 → softopt-0.8.1}/softopt/calibrate.py +0 -0
  13. {softopt-0.7.3 → softopt-0.8.1}/softopt/compile.py +0 -0
  14. {softopt-0.7.3 → softopt-0.8.1}/softopt/soft_number.py +0 -0
  15. {softopt-0.7.3 → softopt-0.8.1}/softopt/torch_optimizer.py +0 -0
  16. {softopt-0.7.3 → softopt-0.8.1}/softopt.egg-info/dependency_links.txt +0 -0
  17. {softopt-0.7.3 → softopt-0.8.1}/softopt.egg-info/requires.txt +0 -0
  18. {softopt-0.7.3 → softopt-0.8.1}/softopt.egg-info/top_level.txt +0 -0
  19. {softopt-0.7.3 → softopt-0.8.1}/tests/test_basic.py +0 -0
  20. {softopt-0.7.3 → softopt-0.8.1}/tests/test_calibrate.py +0 -0
  21. {softopt-0.7.3 → softopt-0.8.1}/tests/test_causal.py +0 -0
  22. {softopt-0.7.3 → softopt-0.8.1}/tests/test_compile.py +0 -0
  23. {softopt-0.7.3 → softopt-0.8.1}/tests/test_exact_d2.py +0 -0
  24. {softopt-0.7.3 → softopt-0.8.1}/tests/test_measured_slope.py +0 -0
  25. {softopt-0.7.3 → softopt-0.8.1}/tests/test_soft_number.py +0 -0
  26. {softopt-0.7.3 → softopt-0.8.1}/tests/test_torch.py +0 -0
  27. {softopt-0.7.3 → softopt-0.8.1}/tests/test_torch_compile.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: softopt
3
- Version: 0.7.3
3
+ Version: 0.8.1
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,54 @@ 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
+ **Recommended for real hardware (new in 0.8.1): `SoftOpt(..., mode="auto", auto_window=8, auto_z=4)`.**
128
+ On nine stored IBM `ibm_fez` runs (H2), the model's slope and the device's agree while the run is far from the
129
+ optimum (88% of conclusive pairs in the first 10 steps) and disagree near it (61% in steps 21-30). The default
130
+ `mode="auto"` judges all pairs since the start, so this late disagreement is diluted and it rarely switches there.
131
+ `auto_window=8` judges only the last 8 conclusive pairs; `auto_z=4` counts a pair only when its slope is 4 noise
132
+ standard deviations from zero, so that near the optimum shot noise cannot fill the window with random signs.
133
+ Tested (pre-registered, new seeds) on FakeFez H2 with injected coherent gate errors, 240 readings:
134
+ - errors sd 0.1 / 0.05: 0.65 / 0.8 mHa vs default SoftOpt 41 / 7.8 (better on 10/10 at both), vs Adam 3.4 / 2.75,
135
+ vs 0.8.0 `mode="auto"` 1.35 / 1.5; it switched on 10/10 runs.
136
+ - no errors (model right): no switch on 10/10 runs (same as default SoftOpt); exact-model H2 with 300 readings:
137
+ no switch on 10/10.
138
+ - `calibrate=True` stays best when you can write a model of the device's errors (0.3 mHa).
139
+ Not yet tested prospectively on hardware. The defaults of `mode="auto"` are unchanged from 0.8.0.
140
+
141
+ `mode="auto"` and `mode="mn"` are in `SoftOpt` (numpy). They are not combined with `calibrate=True`.
142
+
94
143
  ## Results across domains
95
144
 
96
145
  One small problem per domain, one protocol for all: the model is the domain's standard simulator with its
@@ -364,6 +413,9 @@ The full soft-number algebra is available from the package (`from softopt import
364
413
  measure a real system.
365
414
  - default (`slope="model"`) — your model is exact; the measurements are only noisy.
366
415
  - `slope="measured"` — the model is approximate and you do not want to name its uncertain parameters.
416
+ - `mode="auto"` — you do not know whether the model's optimum matches the real system's; it keeps the default
417
+ when the readings agree with the model and switches to `mode="mn"` when they do not. On hardware, add
418
+ `auto_window=8, auto_z=4` (0.8.1). If you can model the device's errors, `calibrate=True` is better still.
367
419
 
368
420
  `calibrate=True` is available in `SoftOpt` (numpy). `SoftOptTorch` runs the default correction.
369
421
 
@@ -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,54 @@ 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
+ **Recommended for real hardware (new in 0.8.1): `SoftOpt(..., mode="auto", auto_window=8, auto_z=4)`.**
102
+ On nine stored IBM `ibm_fez` runs (H2), the model's slope and the device's agree while the run is far from the
103
+ optimum (88% of conclusive pairs in the first 10 steps) and disagree near it (61% in steps 21-30). The default
104
+ `mode="auto"` judges all pairs since the start, so this late disagreement is diluted and it rarely switches there.
105
+ `auto_window=8` judges only the last 8 conclusive pairs; `auto_z=4` counts a pair only when its slope is 4 noise
106
+ standard deviations from zero, so that near the optimum shot noise cannot fill the window with random signs.
107
+ Tested (pre-registered, new seeds) on FakeFez H2 with injected coherent gate errors, 240 readings:
108
+ - errors sd 0.1 / 0.05: 0.65 / 0.8 mHa vs default SoftOpt 41 / 7.8 (better on 10/10 at both), vs Adam 3.4 / 2.75,
109
+ vs 0.8.0 `mode="auto"` 1.35 / 1.5; it switched on 10/10 runs.
110
+ - no errors (model right): no switch on 10/10 runs (same as default SoftOpt); exact-model H2 with 300 readings:
111
+ no switch on 10/10.
112
+ - `calibrate=True` stays best when you can write a model of the device's errors (0.3 mHa).
113
+ Not yet tested prospectively on hardware. The defaults of `mode="auto"` are unchanged from 0.8.0.
114
+
115
+ `mode="auto"` and `mode="mn"` are in `SoftOpt` (numpy). They are not combined with `calibrate=True`.
116
+
68
117
  ## Results across domains
69
118
 
70
119
  One small problem per domain, one protocol for all: the model is the domain's standard simulator with its
@@ -338,6 +387,9 @@ The full soft-number algebra is available from the package (`from softopt import
338
387
  measure a real system.
339
388
  - default (`slope="model"`) — your model is exact; the measurements are only noisy.
340
389
  - `slope="measured"` — the model is approximate and you do not want to name its uncertain parameters.
390
+ - `mode="auto"` — you do not know whether the model's optimum matches the real system's; it keeps the default
391
+ when the readings agree with the model and switches to `mode="mn"` when they do not. On hardware, add
392
+ `auto_window=8, auto_z=4` (0.8.1). If you can model the device's errors, `calibrate=True` is better still.
341
393
 
342
394
  `calibrate=True` is available in `SoftOpt` (numpy). `SoftOptTorch` runs the default correction.
343
395
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "softopt"
7
- version = "0.7.3"
7
+ version = "0.8.1"
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
- See README.md.
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.7.3"
41
+ __version__ = "0.8.1"
@@ -31,6 +31,30 @@ 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. auto_window=W (0.8.1) judges only the last W conclusive
49
+ pairs instead of all of them: far from the optimum a displaced model and the device still agree on
50
+ the way down, and the disagreement appears near the optimum (seen on ibm_fez), where a
51
+ whole-run count dilutes it. Until a switch "auto" is bit-identical to
52
+ "full". Defaults (8 pairs, 0.6, z = 2, mn_lr = 1.0) are the rule frozen and
53
+ tested in the pre-registered selector study (H4 simulation, then FakeFez H2/H4).
54
+ "mn" and "auto" need direction=, measured_slope= (and for "auto" slope_sd=, the
55
+ standard deviation of measured_slope; for an SPSA pair with reading sd s and
56
+ offset c it is sqrt(2) * s / (2c)) on every step. `mode_state` reports the
57
+ current mode, the switch step and the agreement so far.
34
58
  """
35
59
  import numpy as np
36
60
 
@@ -39,9 +63,21 @@ class SoftOpt:
39
63
  def __init__(self, n_params, g_delta, lr=0.02, betas=(0.9, 0.999), eps=1e-8,
40
64
  newton_lo=-0.5, newton_hi=0.5, eta_fallback=0.3,
41
65
  h_fd=1e-4, seed=None, slope="model", exact_d2="auto", calibrate=False, bias_scale=None,
66
+ mode="full", mn_lr=1.0, auto_min_pairs=8, auto_threshold=0.6, auto_z=2.0, auto_window=None,
42
67
  _test_frozen_constant=1.0):
43
68
  if slope not in ("model", "measured"):
44
69
  raise ValueError(f'slope must be "model" or "measured", got {slope!r}')
70
+ if mode not in ("full", "mn", "auto"):
71
+ raise ValueError(f'mode must be "full", "mn" or "auto", got {mode!r}')
72
+ if mode != "full" and calibrate:
73
+ raise ValueError('mode="mn"/"auto" is not combined with calibrate=True (use mode="full")')
74
+ self.mode, self.mn_lr = mode, mn_lr
75
+ self.auto_min_pairs, self.auto_threshold, self.auto_z = auto_min_pairs, auto_threshold, auto_z
76
+ if auto_window is not None and auto_window < 1:
77
+ raise ValueError("auto_window must be a positive number of conclusive pairs, or None")
78
+ self.auto_window = auto_window
79
+ self._active = "mn" if mode == "mn" else "full"
80
+ self._agree, self._switch_step, self._n_steps = [], None, 0
45
81
  self.slope = slope
46
82
  self.g_delta = g_delta
47
83
  self.lr = lr
@@ -71,8 +107,56 @@ class SoftOpt:
71
107
  self._ablation_rng = None
72
108
  self._test_frozen_constant = _test_frozen_constant
73
109
 
74
- def step(self, theta, grad_estimate, direction=None, measured_slope=None,
110
+ def step(self, theta, grad_estimate, direction=None, measured_slope=None, slope_sd=None,
75
111
  _test_magnitude_source=None, _test_foreign_sampler=None, _test_rng=None):
112
+ if self.mode == "full":
113
+ return self._full_step(theta, grad_estimate, direction, measured_slope,
114
+ _test_magnitude_source, _test_foreign_sampler, _test_rng)
115
+ theta = np.asarray(theta, dtype=float)
116
+ if direction is None or measured_slope is None:
117
+ raise ValueError(f'mode="{self.mode}" needs direction= and measured_slope= on every step '
118
+ '(spsa_gradient() returns both)')
119
+ direction = np.asarray(direction, dtype=float)
120
+ if direction.shape != theta.shape:
121
+ raise ValueError(f"direction has shape {direction.shape}, theta has {theta.shape}")
122
+ sl = float(measured_slope)
123
+ if self._active == "full": # mode="auto", not yet switched
124
+ if slope_sd is None:
125
+ raise ValueError('mode="auto" needs slope_sd= (the standard deviation of measured_slope) '
126
+ 'on every step')
127
+ if abs(sl) > self.auto_z * float(slope_sd):
128
+ self._agree.append(bool(np.sign(self.g_delta(theta, direction)) == np.sign(sl)))
129
+ recent = self._agree[-self.auto_window:] if self.auto_window else self._agree
130
+ if (len(self._agree) >= max(self.auto_min_pairs, self.auto_window or 0)
131
+ and np.mean(recent) < self.auto_threshold):
132
+ self._active, self._switch_step = "mn", self._n_steps
133
+ self._n_steps += 1
134
+ if self._active == "full":
135
+ return self._full_step(theta, grad_estimate, direction, measured_slope,
136
+ _test_magnitude_source, _test_foreign_sampler, _test_rng)
137
+ return self._mn_step(theta, direction, sl)
138
+
139
+ def _mn_step(self, theta, d, sl):
140
+ if self._d1_d2 is not None:
141
+ D2 = self._d1_d2(theta, d)[1]
142
+ else:
143
+ D2 = (self.g_delta(theta + self.h_fd * d, d) - self.g_delta(theta - self.h_fd * d, d)) / (2 * self.h_fd)
144
+ if D2 > 1e-8:
145
+ t = float(np.clip(-sl / D2, self.newton_lo, self.newton_hi))
146
+ else:
147
+ t = float(np.clip(-self.eta_fallback * sl, self.newton_lo, self.newton_hi))
148
+ return theta + self.mn_lr * t * d
149
+
150
+ @property
151
+ def mode_state(self):
152
+ """mode="auto"/"mn": the mode in use, the step at which "auto" switched (None if it has not),
153
+ the number of conclusive probe pairs and the fraction that agreed with the model's slope."""
154
+ return dict(mode=self.mode, active=self._active, switch_step=self._switch_step,
155
+ n_conclusive=len(self._agree),
156
+ agreement=float(np.mean(self._agree)) if self._agree else None)
157
+
158
+ def _full_step(self, theta, grad_estimate, direction=None, measured_slope=None,
159
+ _test_magnitude_source=None, _test_foreign_sampler=None, _test_rng=None):
76
160
  """One complete optimizer step: Adam base update + Newton-style
77
161
  correction from the known model, in a single call.
78
162
  theta: current parameters (np.ndarray)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: softopt
3
- Version: 0.7.3
3
+ Version: 0.8.1
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,54 @@ 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
+ **Recommended for real hardware (new in 0.8.1): `SoftOpt(..., mode="auto", auto_window=8, auto_z=4)`.**
128
+ On nine stored IBM `ibm_fez` runs (H2), the model's slope and the device's agree while the run is far from the
129
+ optimum (88% of conclusive pairs in the first 10 steps) and disagree near it (61% in steps 21-30). The default
130
+ `mode="auto"` judges all pairs since the start, so this late disagreement is diluted and it rarely switches there.
131
+ `auto_window=8` judges only the last 8 conclusive pairs; `auto_z=4` counts a pair only when its slope is 4 noise
132
+ standard deviations from zero, so that near the optimum shot noise cannot fill the window with random signs.
133
+ Tested (pre-registered, new seeds) on FakeFez H2 with injected coherent gate errors, 240 readings:
134
+ - errors sd 0.1 / 0.05: 0.65 / 0.8 mHa vs default SoftOpt 41 / 7.8 (better on 10/10 at both), vs Adam 3.4 / 2.75,
135
+ vs 0.8.0 `mode="auto"` 1.35 / 1.5; it switched on 10/10 runs.
136
+ - no errors (model right): no switch on 10/10 runs (same as default SoftOpt); exact-model H2 with 300 readings:
137
+ no switch on 10/10.
138
+ - `calibrate=True` stays best when you can write a model of the device's errors (0.3 mHa).
139
+ Not yet tested prospectively on hardware. The defaults of `mode="auto"` are unchanged from 0.8.0.
140
+
141
+ `mode="auto"` and `mode="mn"` are in `SoftOpt` (numpy). They are not combined with `calibrate=True`.
142
+
94
143
  ## Results across domains
95
144
 
96
145
  One small problem per domain, one protocol for all: the model is the domain's standard simulator with its
@@ -364,6 +413,9 @@ The full soft-number algebra is available from the package (`from softopt import
364
413
  measure a real system.
365
414
  - default (`slope="model"`) — your model is exact; the measurements are only noisy.
366
415
  - `slope="measured"` — the model is approximate and you do not want to name its uncertain parameters.
416
+ - `mode="auto"` — you do not know whether the model's optimum matches the real system's; it keeps the default
417
+ when the readings agree with the model and switches to `mode="mn"` when they do not. On hardware, add
418
+ `auto_window=8, auto_z=4` (0.8.1). If you can model the device's errors, `calibrate=True` is better still.
367
419
 
368
420
  `calibrate=True` is available in `SoftOpt` (numpy). `SoftOptTorch` runs the default correction.
369
421
 
@@ -19,6 +19,7 @@ tests/test_causal.py
19
19
  tests/test_compile.py
20
20
  tests/test_exact_d2.py
21
21
  tests/test_measured_slope.py
22
+ tests/test_mode.py
22
23
  tests/test_soft_number.py
23
24
  tests/test_torch.py
24
25
  tests/test_torch_compile.py
@@ -0,0 +1,95 @@
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
81
+
82
+
83
+ def test_auto_window_switches_when_late_disagreement_is_diluted():
84
+ # agreement 1 for 20 conclusive pairs, then 0: the whole-run rule needs many pairs, the window switches fast
85
+ o_all = SoftOpt(N, g_model, mode="auto"); o_win = SoftOpt(N, g_model, mode="auto", auto_window=8)
86
+ for o in (o_all, o_win):
87
+ o._agree = [True] * 20 + [False] * 6
88
+ o._agree.append(False)
89
+ recent = o._agree[-o.auto_window:] if o.auto_window else o._agree
90
+ assert (np.mean(recent) < 0.6) == (o is o_win)
91
+
92
+
93
+ def test_auto_window_validation():
94
+ with pytest.raises(ValueError):
95
+ SoftOpt(N, g_model, mode="auto", auto_window=0)
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