dsh-eval-guard 0.7.4 → 0.7.6

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 (31) hide show
  1. package/ISSUES.md +4 -2
  2. package/README.md +3 -3
  3. package/assets/neural-pendulum/SPEC.md +40 -42
  4. package/assets/neural-pendulum/TASK.md +34 -47
  5. package/assets/neural-pendulum/sim.cpp +97 -45
  6. package/assets/neural-pendulum/sim_agent +0 -0
  7. package/assets/neural-pendulum/sim_eval +0 -0
  8. package/assets/neural-pendulum/workspace.zip +0 -0
  9. package/lib/index.js +27 -10
  10. package/neural-pendulum-eval/README.md +4 -3
  11. package/neural-pendulum-eval/run_eval.py +133 -70
  12. package/neural-pendulum-eval/sim_eval +0 -0
  13. package/package.json +1 -1
  14. package/assets/neural-pendulum/rl-feasibility/README.md +0 -60
  15. package/assets/neural-pendulum/rl-feasibility/RESULTS.md +0 -370
  16. package/assets/neural-pendulum/rl-feasibility/evaluate.py +0 -107
  17. package/assets/neural-pendulum/rl-feasibility/finalize_run.py +0 -168
  18. package/assets/neural-pendulum/rl-feasibility/models.py +0 -124
  19. package/assets/neural-pendulum/rl-feasibility/obs.py +0 -205
  20. package/assets/neural-pendulum/rl-feasibility/plot_selected.py +0 -55
  21. package/assets/neural-pendulum/rl-feasibility/reference_controller.py +0 -112
  22. package/assets/neural-pendulum/rl-feasibility/results/curves_selected.png +0 -0
  23. package/assets/neural-pendulum/rl-feasibility/results/reference_controller.json +0 -417
  24. package/assets/neural-pendulum/rl-feasibility/results/summary.json +0 -1599
  25. package/assets/neural-pendulum/rl-feasibility/results/table.md +0 -39
  26. package/assets/neural-pendulum/rl-feasibility/sim.py +0 -324
  27. package/assets/neural-pendulum/rl-feasibility/summarize.py +0 -175
  28. package/assets/neural-pendulum/rl-feasibility/task.py +0 -342
  29. package/assets/neural-pendulum/rl-feasibility/test_contract.py +0 -188
  30. package/assets/neural-pendulum/rl-feasibility/train_ppo.py +0 -403
  31. package/assets/neural-pendulum/rl-feasibility/train_sac.py +0 -406
@@ -1,370 +0,0 @@
1
- # RESULTS — fixed-physics 3-link pendulum RL feasibility
2
-
3
- Work dir: `feasibility/neural-pendulum-fixedenv`.
4
- Started 2026-10-23 01:13 CST; experiment matrix completed 06:35 CST.
5
- All numbers below are new runs in the corrected environment; no old
6
- `(tau1, 0, tau3)` result is reused.
7
-
8
- ## TL;DR
9
-
10
- * **PPO and SAC both learn the corrected dynamics from the mandated random
11
- near-down resets and reach t_can >= 10 s at the fixed evaluation state.**
12
- * PPO (64 env, full 36D, base reward): first success at **11.33M env steps /
13
- 16.0 min**; best **26.85 s**; final 26.61 s; best-checkpoint robustness
14
- **8/8**.
15
- * SAC (32 env, full 36D, base reward): first success at **0.70M env steps /
16
- 24.7 min**; best **28.75 s**; final 28.21 s; best-checkpoint robustness
17
- **6/8** (final 8/8).
18
- * **The learnability boundary is set by observation information, not by the
19
- algorithm alone.**
20
- * `full` H=4 (36D: cos/sin + da/5) works for both PPO and SAC.
21
- * `angle` H=4 (24D, no da): PPO best 0.97 s, SAC best 0.04 s — fails.
22
- * `full_h1` (9D) and `angle_h1` (6D): fail completely (best <= 0.06 s);
23
- even a 50% upright curriculum does not rescue H=1.
24
- * `angle_h8` (48D): best 1.31 s — longer history helps a little but does
25
- not replace `da/5`.
26
- * **Reward boundary:** base works; sparse and strong energy shaping fail.
27
- * `sparse`: 19.12M steps, best t_can 0, policy converges to tiny actions.
28
- * `energy`: two designs fail; energy chasing with manual `da` has a
29
- degenerate high-kinetic-energy spin optimum.
30
- * **Init boundary is algorithm-dependent.** Random init is required for PPO
31
- (fixed-init PPO: best 1.19 s, robust 0/8). SAC fixed-init *does* succeed
32
- (best 28.86 s, robust 8/8) because its replay covers the state space; PPO's
33
- on-policy batch of 64 identical states does not.
34
- * Three PPO seeds all reach >26 s at their best checkpoint (26.85 / 27.17 /
35
- 28.46 s) but the final checkpoint is unreliable (seed 2 final 0.00 s).
36
- Use `_best.pt`, not the last model.
37
- * A non-RL pole-placement stabiliser with a 0.5 low-pass torque filter holds
38
- **29.99 s** from the fixed upright offset and succeeds on 32/32 random
39
- upright offsets. The hold is physically feasible with the corrected
40
- mapping; it is not an RL result (privileged omega).
41
-
42
- ## 1. Environment and contract
43
-
44
- * Simulator returns angles only: `reset(theta,omega)->theta`,
45
- `step(u)->theta`. No reward, done, info, omega or tip is exposed.
46
- * Corrected physical torque mapping:
47
- `generalized_torque = (tau1, -tau3, tau3)` (joint 3 is the internal motor
48
- between links 2 and 3; joint 2 is passive). `sim.generalized_torque` and
49
- `sim.make_torch_consts` both implement it. Do not revert to
50
- `(tau1, 0, tau3)`.
51
- * 100 Hz ZOH, RK4 with 4 substeps, 30 s episodes (3000 steps),
52
- tau_max = 18 N m, damping 0.01, success tolerance 0.05 rad, t_tgt = 10 s.
53
- * `test_contract.py` passes; the Python sim was cross-validated against
54
- `assets/neural-pendulum/sim_eval` by the Lead (~5e-6).
55
- * Training reset (random arm): theta_i ~ U(-0.05,0.05),
56
- omega_i ~ U(-0.02,0.02), independent, no fixed bias.
57
- Fixed arm: theta = [0.013,-0.008,0.021], omega = 0.
58
- Curriculum arm: 50% near down, 50% theta = pi + U(-0.05,0.05).
59
- * Evaluation: fixed theta = [0.013,-0.008,0.021], omega = 0, deterministic
60
- actions, full 3000 steps. t_can is the longest continuous interval with
61
- max_i |wrap(theta_i - pi)| < 0.05 rad. Eval always uses the **same** obs
62
- mode and reward preset as training; no reward switch at eval.
63
-
64
- ## 2. Code changes in this directory
65
-
66
- 1. `obs.py`: switchable modes
67
- `full` 36D, `angle` 24D, `full_h1` 9D, `angle_h1` 6D,
68
- `full_h2` 18D, `angle_h2` 12D, plus `angle_h8` 48D.
69
- `da` is always computed internally because the reward uses it;
70
- `diff=False` only drops it from the policy input.
71
- 2. `task.py`: reward presets `base`, `sparse`, `energy` (exact weights
72
- below), bounded energy error, and `--init mix` curriculum support.
73
- 3. `train_ppo.py` / `train_sac.py`: `--obs`, `--reward`, `--init`,
74
- `--up-frac`; eval uses the same mode/reward; live TB flush every
75
- iteration/log tick; 8 extra deterministic rollouts from the training
76
- reset distribution for final and best checkpoints.
77
- 4. `evaluate.py`: obs-mode aware, plus `evaluate_starts`.
78
- 5. `reference_controller.py`: non-RL local stabilisability proof.
79
- 6. `finalize_run.py`: rebuild a results JSON from checkpoints + log when a
80
- trainer crashes after saving checkpoints (used once for PPO seed 0).
81
- 7. `summarize.py`, `plot_selected.py`: aggregate table/JSON/curves.
82
-
83
- ## 3. Observation modes
84
-
85
- | --obs | frame | H | dim | contents |
86
- |---|---|---|---|---|
87
- | full | [cos a_i, sin a_i, da_i/5] | 4 | 36 | baseline |
88
- | angle | [cos a_i, sin a_i] | 4 | 24 | no explicit velocity |
89
- | full_h1 | [cos a_i, sin a_i, da_i/5] | 1 | 9 | single frame |
90
- | angle_h1 | [cos a_i, sin a_i] | 1 | 6 | single frame, no velocity |
91
- | full_h2 | [cos a_i, sin a_i, da_i/5] | 2 | 18 | optional |
92
- | angle_h2 | [cos a_i, sin a_i] | 2 | 12 | optional |
93
- | angle_h8 | [cos a_i, sin a_i] | 8 | 48 | longer history follow-up |
94
-
95
- `a_i = wrap_to_pi(theta_i - pi)`, `da_i = wrap_to_pi(a_i(t)-a_i(t-1))/dt`,
96
- `da(0)=0`. Theta is in radians, never divided by pi. History is oldest
97
- first, reset repeats the first frame. The eval builder is the same class and
98
- mode as training.
99
-
100
- ## 4. Reward presets (exact)
101
-
102
- ```
103
- r = exp * exp(-2 s2)
104
- + sharp * exp(-50 s2)
105
- - ang * s2
106
- - vel * sum da^2
107
- - act * sum u^2
108
- + up * 1[max_i |a_i| < 0.15]
109
- + tip * (tip_y + L)/(2L)
110
- - energy * |E - E_up| / (E_up - E_down)
111
- ```
112
-
113
- All terms are trainer-side functions of theta, the manual difference da and
114
- the action u; no simulator omega is read. `E` uses da as velocity. The
115
- energy error is clamped at 3 to keep the reward bounded at high spin.
116
-
117
- ```json
118
- base = {"exp":1.0,"sharp":2.0,"ang":0.05,"vel":0.001,"act":0.01,"up":3.0,"tip":0.3,"energy":0.01}
119
- sparse = {"exp":0.2,"sharp":0.0,"ang":0.0,"vel":0.001,"act":0.01,"up":3.0,"tip":0.0,"energy":0.0}
120
- energy = {"exp":1.0,"sharp":2.0,"ang":0.05,"vel":0.0,"act":0.005,"up":3.0,"tip":0.0,"energy":0.5}
121
- ```
122
-
123
- `sparse`: at the near-down reset the only dense term is ~1e-26, so it is an
124
- intentionally hard exploration test. `energy`: base angle terms + strong
125
- energy shaping + no velocity penalty; an earlier energy-dominant design
126
- (`exp=.2, sharp=.5, ang=.01, vel=.0002`) is archived under
127
- `failed/energy_unbounded/`.
128
-
129
- ## 5. Training protocol
130
-
131
- PPO: 2x128 tanh actor/critic, 64 envs, horizon 600, 8 epochs,
132
- minibatch 2048, lr 3e-4 linearly decayed to 20%, gamma .99, lambda .95,
133
- clip .2, entropy .003, vf .5, target KL .03, grad clip .5.
134
-
135
- SAC: 2x256 tanh squashed-Gaussian actor, shared-trunk twin Q, 32 envs,
136
- batch 256, replay 300k, auto-alpha (target entropy -2), gamma .99,
137
- tau .005, lr 3e-4, UTD 0.25 (8 gradient updates per 32-env vector step).
138
-
139
- Both: CPU PyTorch, 4 threads per process, at most 2 training processes
140
- concurrently. Eval every 5 PPO iterations (192k steps) or every 20k SAC
141
- steps. Best checkpoint by eval t_can (ties by return). Final checkpoint at
142
- the time budget. TensorBoard flushed during training (not only at the end).
143
- At the end, 8 deterministic rollouts from the training distribution are run
144
- for the final and best checkpoints.
145
-
146
- ## 6. Complete experiment matrix (fixed-initial deterministic eval)
147
-
148
- `best trob` = success rate / mean t_can of the best checkpoint on the 8
149
- training-distribution starts. `first succ` = first eval snapshot with
150
- t_can >= 10 s.
151
-
152
- | exp | algo | obs | reward | init | env steps | wall | best t_can | final t_can | ever_up | best trob | first succ |
153
- |---|---|---|---|---|---|---|---|---|---|---|---|
154
- | ppo_full_base_rand | PPO | full 36 | base | rand | 35.98M | 45.1 min | **26.85 s** | 26.61 s | yes | 8/8, 26.86 s | **11.33M** |
155
- | ppo_full_base_rand_s1 | PPO | full 36 | base | rand | 29.03M | 40.8 min | **27.17 s** | 0.23 s | yes | 8/8, 26.78 s | 13.63M |
156
- | ppo_full_base_rand_s2 | PPO | full 36 | base | rand | 34.21M | 40.3 min | **28.46 s** | 0.00 s | no | 8/8, 28.03 s | 14.40M |
157
- | sac_full_base_rand | SAC | full 36 | base | rand | 1.42M | 50.6 min | **28.75 s** | 28.21 s | yes | 6/8, 20.89 s | **0.70M** |
158
- | ppo_angle_base_rand | PPO | angle 24 | base | rand | 31.76M | 40.6 min | 0.97 s | 0.04 s | yes | 0/8 | - |
159
- | sac_angle_base_rand | SAC | angle 24 | base | rand | 1.42M | 50.6 min | 0.04 s | 0.00 s | no | 0/8 | - |
160
- | ppo_full_h1_rand | PPO | full_h1 9 | base | rand | 25.42M | 35.3 min | 0.06 s | 0.00 s | no | 0/8 | - |
161
- | ppo_angle_h1_rand | PPO | angle_h1 6 | base | rand | 20.97M | 30.4 min | 0.00 s | 0.00 s | no | 0/8 | - |
162
- | ppo_angle_h8_rand | PPO | angle_h8 48 | base | rand | 30.11M | 40.4 min | 1.31 s | 0.05 s | yes | 0/8 | - |
163
- | ppo_full_h1_mix | PPO | full_h1 9 | base | mix 50% up | 21.39M | 30.5 min | 0.02 s | 0.00 s | no | 0/8 | - |
164
- | ppo_angle_mix | PPO | angle 24 | base | mix 50% up | 23.50M | 30.5 min | 0.25 s | 0.00 s | yes | 0/8 | - |
165
- | ppo_full_sparse_rand | PPO | full 36 | sparse | rand | 19.12M | 30.5 min | 0.00 s | 0.00 s | no | 0/8 | - |
166
- | ppo_full_energy_rand | PPO | full 36 | energy | rand | 24.50M | 35.5 min | 0.00 s | 0.00 s | no | 0/8 | - |
167
- | ppo_full_base_fixed | PPO | full 36 | base | fixed | 21.93M | 30.5 min | 1.19 s | 0.00 s | no | 0/8 | - |
168
- | sac_full_base_fixed | SAC | full 36 | base | fixed | 1.41M | 50.4 min | **28.86 s** | 27.62 s | yes | 8/8, 23.45 s | **0.52M** |
169
-
170
- Raw machine-readable table: `results/table.md`; per-run JSON:
171
- `results/<exp>.json`; plots: `results/curves_selected.png`.
172
-
173
- ## 7. Results by question
174
-
175
- ### Q1. Are PPO and SAC learnable? Steps/time to t_can >= 10 s
176
-
177
- **Yes, both, with full 36D observations and base reward.**
178
-
179
- | algo | envs | first success | wall to first success | steps/s | budget | best | final | best-checkpoint robustness |
180
- |---|---|---|---|---|---|---|---|---|
181
- | PPO | 64 | 11.33M | 16.0 min | ~13.3k | 45 min / 35.98M | 26.85 s | 26.61 s | 8/8 (mean 26.86 s) |
182
- | SAC | 32 | 0.70M | 24.7 min | ~470 | 50 min / 1.42M | 28.75 s | 28.21 s | 6/8 (mean 20.89 s) |
183
-
184
- The first successful snapshots were 26.65 s (PPO at 11.33M) and 16.74 s
185
- (SAC at 0.70M). SAC needs ~16x fewer environment steps but ~28x more
186
- wall-clock per step, so the time to first success is comparable (16 vs
187
- 25 min). PPO is more stable
188
- at the final snapshot; SAC's final policy is also strong (8/8, 28.21 s).
189
- PPO eval t_can is intermittent during learning (0 <-> 26 s between successive
190
- 192k-step evals), so a single eval snapshot is not a reliable success
191
- criterion; both `_best.pt` and the success-snapshot count are reported.
192
-
193
- ### Q2. Angle-only vs full
194
-
195
- **Removing the explicit da/5 channel is a hard failure in this budget.**
196
-
197
- | exp | algo | obs | best t_can | final t_can | best robust |
198
- |---|---|---|---|---|---|
199
- | ppo_full_base_rand | PPO | full 36 | **26.85 s** | 26.61 s | 8/8 |
200
- | ppo_angle_base_rand | PPO | angle 24 | 0.97 s | 0.04 s | 0/8 |
201
- | sac_full_base_rand | SAC | full 36 | **28.75 s** | 28.21 s | 6/8 |
202
- | sac_angle_base_rand | SAC | angle 24 | 0.04 s | 0.00 s | 0/8 |
203
-
204
- PPO angle-only can swing up (ever_up=1, first up ~1.2 s) but cannot hold;
205
- its best up_frac is 3.8%. SAC angle-only only briefly touches upright
206
- (best t_can 0.04 s, a single 0.04 s window at ~9.23 s; final ever_up 0) and
207
- its final return is negative. H=4 cos/sin history does not substitute for
208
- the manually differentiated velocity. This is a budget
209
- statement, not an information-theoretic impossibility, but 40-50 min and
210
- 20-32M steps is a generous budget in this study.
211
-
212
- ### Q3. H=4 -> H=1 and reduced observations
213
-
214
- **H=1 destroys learnability even with explicit da; longer history only
215
- partially substitutes for da.**
216
-
217
- | exp | obs | dim | best t_can | final t_can | ever_up | best robust |
218
- |---|---|---|---|---|---|---|
219
- | ppo_full_base_rand | full H=4 | 36 | **26.85 s** | 26.61 s | yes | 8/8 |
220
- | ppo_full_h1_rand | full H=1 | 9 | 0.06 s | 0.00 s | no | 0/8 |
221
- | ppo_angle_base_rand | angle H=4 | 24 | 0.97 s | 0.04 s | yes | 0/8 |
222
- | ppo_angle_h8_rand | angle H=8 | 48 | 1.31 s | 0.05 s | yes | 0/8 |
223
- | ppo_angle_h1_rand | angle H=1 | 6 | 0.00 s | 0.00 s | no | 0/8 |
224
- | ppo_full_h1_mix | full H=1 + 50% upright | 9 | 0.02 s | 0.00 s | no | 0/8 |
225
-
226
- The 9D full_h1 observation has the instantaneous full state (cos/sin+da/5)
227
- but no temporal window. It never reaches upright in 25.4M steps. A
228
- curriculum with half the resets already near upright also fails (21.4M
229
- steps), so the H=1 failure is representational (no phase/acceleration
230
- history), not only exploration. Angle H=8 improves the best t_can from 0.97
231
- to 1.31 s but is still far from success; explicit da + H=4 is the only
232
- working combination.
233
-
234
- ### Q4. Reward preset
235
-
236
- | exp | reward | env steps | best t_can | final t_can | ever_up | note |
237
- |---|---|---|---|---|---|---|
238
- | ppo_full_base_rand | base | 35.98M | **26.85 s** | 26.61 s | yes | works |
239
- | ppo_full_sparse_rand | sparse | 19.12M | 0.00 s | 0.00 s | no | policy -> tiny actions |
240
- | ppo_full_energy_rand | energy v2 | 24.50M | 0.00 s | 0.00 s | no | spinning optimum |
241
- | (failed v1) | energy unbounded | 6.7M | 0.00 s | 0.00 s | no | value loss ~5e7 |
242
-
243
- **base** is the only working reward. **sparse** has no usable gradient from
244
- the near-down reset: `0.2 exp(-2 s2)` is ~1e-26 at s2~30, and the 0.15 rad
245
- bonus is never reached by exploration; the policy converges to mean |u|~0.01
246
- and return -0.39. This is an exploration failure, not a crash.
247
-
248
- **energy** failed in two designs. v1 used an unbounded energy error and
249
- blew up the value loss; v2 clamped it and kept the base angle terms but still
250
- never reached upright in 24.5M steps (0/24.5M, final return -1948). The
251
- reason is degenerate: total mechanical energy `E = T + V` can be driven to
252
- `E_up` by spinning fast at the wrong angles, and `T` computed from the
253
- manual `da` is noisy/large exactly there. A strong energy term rewards that
254
- spin instead of swing-up. The base reward keeps energy weight at 0.01;
255
- raising it is not a shortcut.
256
-
257
- ### Q5. Fixed-init vs random-init (algorithm-dependent)
258
-
259
- | exp | algo | init | env steps | best t_can | final t_can | best-checkpoint robustness |
260
- |---|---|---|---|---|---|---|
261
- | ppo_full_base_rand | PPO | random | 35.98M | **26.85 s** | 26.61 s | 8/8 (26.86 s) |
262
- | ppo_full_base_fixed | PPO | fixed | 21.93M | **1.19 s** | 0.00 s | 0/8 (mean return -99,380) |
263
- | sac_full_base_rand | SAC | random | 1.42M | **28.75 s** | 28.21 s | 6/8 (20.89 s) |
264
- | sac_full_base_fixed | SAC | fixed | 1.41M | **28.86 s** | 27.62 s | 8/8 (23.45 s) |
265
-
266
- PPO fixed-init **fails**, even at the exact evaluation state (best 1.19 s),
267
- and is catastrophic on the 8 distribution starts (mean return -99k). PPO's
268
- on-policy batch contains 64 copies of one state, so it never sees the
269
- balance-recovery states it needs.
270
-
271
- SAC fixed-init **succeeds** (best 28.86 s, final 27.62 s, 8/8 on the
272
- distribution starts, first success at 0.52M). SAC's replay buffer is filled
273
- with trajectories generated by its stochastic policy from that one start, so
274
- it does see off-state recovery data. This is the opposite of the old
275
- `(tau1,0,tau3)` round, where fixed-init SAC failed and fixed-init PPO looked
276
- better at the fixed state. The corrected internal-motor dynamics changes
277
- which algorithm can exploit a single start.
278
-
279
- ### Seed variance (PPO full/base/rand)
280
-
281
- | seed | env steps | first success | best t_can | final t_can | best-checkpoint robustness |
282
- |---|---|---|---|---|---|
283
- | 0 | 35.98M | 11.33M | 26.85 s | 26.61 s | 8/8 (26.86 s) |
284
- | 1 | 29.03M | 13.63M | 27.17 s | 0.23 s | 8/8 (26.78 s) |
285
- | 2 | 34.21M | 14.40M | 28.46 s | 0.00 s | 8/8 (28.03 s) |
286
-
287
- All three seeds solve the task at their best checkpoint (8/8 robust), but the
288
- final checkpoint is unreliable (seed 2 final 0.00 s). First success ranges
289
- 11.3-14.4M steps (16-20 min). **Always evaluate and ship `_best.pt`; the
290
- last model is not the policy.**
291
-
292
- ## 8. Non-RL feasibility reference
293
-
294
- `reference_controller.py` → `results/reference_controller.json`:
295
-
296
- * Linearise at upright, pole placement with poles -5..-10, full state
297
- (theta + simulator omega), torque command low-pass filtered with alpha=0.5.
298
- * Fixed start theta = pi + [0.013,-0.008,0.021], omega=0:
299
- **t_can = 29.99 s**, final angle error ~2e-14, saturation 0%.
300
- * 32 random upright offsets U(-0.05,0.05): **32/32 success**, mean t_can
301
- 24.79 s.
302
- * Without the low-pass filter the same controller chatters and holds only
303
- ~1.1 s; smooth torque commands matter for the 0.05 rad tolerance.
304
-
305
- This proves the upright hold is physically reachable with
306
- `(tau1,-tau3,tau3)` and |u|<=1. It uses privileged omega and starts near
307
- upright, so it is not comparable to the RL numbers; it is an existence check
308
- and a hint that action smoothness matters.
309
-
310
- ## 9. Failures / implementation notes (honest list)
311
-
312
- * PPO seed 0's results JSON was reconstructed by `finalize_run.py`. The
313
- trainer crashed **after** saving checkpoints and TB, in the post-training
314
- robustness code (passed `ActorCritic` instead of `ActorCritic.actor` to
315
- `make_ppo_policy`). Training was unaffected. The bug is fixed in
316
- `train_ppo.py`; all later PPO runs wrote JSON directly.
317
- * The first energy preset produced unbounded rewards and a value-loss blow-up
318
- (~5e7). It was killed at 6.7M steps and archived under
319
- `failed/energy_unbounded/`. The second energy design is the one in the
320
- matrix; it fails for a genuine reward-design reason, not a crash.
321
- * Sparse reward's no-op policy is a real exploration failure, not a logging
322
- artefact: final mean |u| ~0.01, return -0.39, ever_up 0.
323
- * Some runs show value-loss spikes (PPO fixed, PPO angle) without NaNs; the
324
- policies still train/plateau. These are recorded in TB.
325
- * No simulator physics was changed. The torque mapping was not reverted.
326
-
327
- ## 10. Artifacts
328
-
329
- * TensorBoard: `tb/<exp>/` (live event files, all 15 runs).
330
- * Logs: `logs/<exp>.log` (stdout, contains eval lines and DONE summary).
331
- * Results: `results/<exp>.json`, aggregate `results/summary.json`,
332
- `results/table.md`, `results/curves.png`, `results/curves_selected.png`.
333
- * Checkpoints: `checkpoints/<exp>_{best,last,final}.pt`.
334
- * Smoke tests: `smoke_archive/`; 6-min probe: `probes/`.
335
- * Failed/abandoned runs: `failed/energy_unbounded/`, `failed/energy_collapse/`.
336
- * Reference controller: `results/reference_controller.json`.
337
-
338
- ## 11. Reproduction
339
-
340
- ```bash
341
- cd feasibility/neural-pendulum-fixedenv
342
- export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 TORCH_THREADS=4
343
- python3 test_contract.py
344
- python3 train_ppo.py --exp ppo_full_base_rand --obs full --reward base \
345
- --init rand --envs 64 --horizon 600 --minutes 45 --eval-every 5 --seed 0
346
- python3 train_sac.py --exp sac_full_base_rand --obs full --reward base \
347
- --init rand --envs 32 --minutes 50 --eval-every 20000 --log-every 10 --seed 0
348
- python3 summarize.py
349
- python3 plot_selected.py
350
- ```
351
-
352
- ## 12. Recommendations / next steps
353
-
354
- 1. **For the actual C++ task, the controller should estimate velocity from
355
- angles and use a 4-frame history (or an explicit recurrent state).** The
356
- 3D observation is not enough by itself; the agent must reconstruct phase.
357
- `full` 36D is the strongest configuration in this study.
358
- 2. **Train from random near-down resets, not one fixed state.** For PPO this
359
- is the difference between success and failure; even for SAC, random init
360
- is more robust across the distribution.
361
- 3. **Use base reward; do not chase sparse or strong energy shaping.** If a
362
- sparse objective is required, add a curriculum or demonstration warm start;
363
- pure sparse PPO does nothing in 19M steps.
364
- 4. **Select checkpoints by eval t_can and ship the best, not the last.**
365
- Final models collapse in 2 of 3 PPO seeds.
366
- 5. **If more compute is available**, try (a) a recurrent/GRU policy on the 3D
367
- angle stream, (b) an action low-pass filter or action-rate penalty, and
368
- (c) a two-stage curriculum (balance near upright, then swing-up) with
369
- warm-started PPO. These target the two observed bottlenecks: velocity
370
- estimation and balance-phase coverage.
@@ -1,107 +0,0 @@
1
- """Deterministic evaluation at the fixed initial state (and optional starts).
2
-
3
- The evaluation uses the simulator API exactly like training (angles only), the
4
- same observation builder / obs mode, and the same trainer-side reward. There
5
- is no action noise.
6
-
7
- default fixed state: theta = [0.013, -0.008, 0.021] rad, omega = 0
8
- optional starts : drawn from the training reset distribution
9
-
10
- The episode always runs the full 3000 steps so that t_can, ever_up, return and
11
- the final angle error are comparable across algorithms.
12
- """
13
- from __future__ import annotations
14
-
15
- import numpy as np
16
- import torch
17
-
18
- from obs import DT, make_numpy_obs, wrap_to_pi
19
- from sim import N_ACT, N_LINKS, UP_TOL, PendulumSim
20
- from task import EVAL_OMEGA0, EVAL_THETA0, NumpyTask
21
-
22
-
23
- def evaluate(policy_fn, p, episode_steps=3000, reward_w=None, obs_mode="full"):
24
- """Run one full deterministic episode at the fixed initial state.
25
-
26
- policy_fn(obs: np.ndarray[obs_dim]) -> np.ndarray[2]
27
- """
28
- sim = PendulumSim(p, episode_steps=episode_steps)
29
- task = NumpyTask(p, reward_w=reward_w, obs_mode=obs_mode)
30
- theta = sim.reset(EVAL_THETA0, EVAL_OMEGA0)
31
- obs = task.reset(theta)
32
- acts = np.zeros((episode_steps, N_ACT), dtype=np.float64)
33
- for k in range(episode_steps):
34
- u = np.clip(np.asarray(policy_fn(obs), dtype=np.float64).reshape(N_ACT),
35
- -1.0, 1.0)
36
- acts[k] = u
37
- theta = sim.step(u)
38
- obs, _ = task.step(theta, u)
39
- summ = task.tracker.summary()
40
- a = wrap_to_pi(np.asarray(theta, dtype=np.float64) - np.pi)
41
- return dict(t_can=float(summ["t_can"]),
42
- success=float(summ["t_can"] >= 10.0),
43
- ever_up=float(summ["ever_up"]),
44
- first_up_t=float(summ["first_up_t"]),
45
- ep_return=float(summ["ep_return"]),
46
- final_ang_err=float(np.abs(a).max()),
47
- up_frac=float(summ["up_frac"]),
48
- mean_abs_action=float(np.mean(np.abs(acts))),
49
- action_std=float(np.std(acts)),
50
- mean_u1=float(acts[:, 0].mean()),
51
- mean_u3=float(acts[:, 1].mean()),
52
- steps=int(episode_steps))
53
-
54
-
55
- def evaluate_starts(policy_fn, p, starts, episode_steps=3000, reward_w=None,
56
- obs_mode="full"):
57
- """Deterministic rollouts from an explicit list of (theta, omega) starts."""
58
- rows = []
59
- for theta0, omega0 in starts:
60
- sim = PendulumSim(p, episode_steps=episode_steps)
61
- task = NumpyTask(p, reward_w=reward_w, obs_mode=obs_mode)
62
- theta = sim.reset(theta0, omega0)
63
- obs = task.reset(theta)
64
- for _ in range(episode_steps):
65
- u = np.clip(np.asarray(policy_fn(obs), dtype=np.float64).reshape(N_ACT),
66
- -1.0, 1.0)
67
- theta = sim.step(u)
68
- obs, _ = task.step(theta, u)
69
- summ = task.tracker.summary()
70
- a = wrap_to_pi(np.asarray(theta, dtype=np.float64) - np.pi)
71
- rows.append(dict(t_can=float(summ["t_can"]),
72
- success=float(summ["t_can"] >= 10.0),
73
- ever_up=float(summ["ever_up"]),
74
- ep_return=float(summ["ep_return"]),
75
- final_ang_err=float(np.abs(a).max())))
76
- tc = np.array([r["t_can"] for r in rows], dtype=np.float64)
77
- su = np.array([r["success"] for r in rows], dtype=np.float64)
78
- re = np.array([r["ep_return"] for r in rows], dtype=np.float64)
79
- ae = np.array([r["final_ang_err"] for r in rows], dtype=np.float64)
80
- eu = np.array([r["ever_up"] for r in rows], dtype=np.float64)
81
- return dict(n=int(len(rows)),
82
- success_rate=float(su.mean()) if len(rows) else 0.0,
83
- ever_up_rate=float(eu.mean()) if len(rows) else 0.0,
84
- mean_t_can=float(tc.mean()) if len(rows) else 0.0,
85
- median_t_can=float(np.median(tc)) if len(rows) else 0.0,
86
- min_t_can=float(tc.min()) if len(rows) else 0.0,
87
- max_t_can=float(tc.max()) if len(rows) else 0.0,
88
- mean_return=float(re.mean()) if len(rows) else 0.0,
89
- mean_final_ang_err=float(ae.mean()) if len(rows) else 0.0,
90
- rows=rows)
91
-
92
-
93
- def make_ppo_policy(actor):
94
- def policy(obs):
95
- with torch.no_grad():
96
- x = torch.as_tensor(obs, dtype=torch.float32).unsqueeze(0)
97
- return actor(x).squeeze(0).numpy()
98
- return policy
99
-
100
-
101
- def make_sac_policy(actor):
102
- def policy(obs):
103
- with torch.no_grad():
104
- x = torch.as_tensor(obs, dtype=torch.float32).unsqueeze(0)
105
- a, _ = actor.sample(x, det=True)
106
- return a.squeeze(0).numpy()
107
- return policy
@@ -1,168 +0,0 @@
1
- """Reconstruct results/<exp>.json for a finished run from its checkpoints,
2
- TensorBoard event file and log. Useful when the trainer crashed after saving
3
- checkpoints but before writing the JSON (e.g. the PPO robustness bug).
4
-
5
- Usage:
6
- python3 finalize_run.py --exp ppo_full_base_rand --algo ppo \
7
- --obs full --reward base --init rand --envs 64 --minutes 45
8
-
9
- The fixed-state eval and the 8-start robustness check are re-run here with the
10
- same code as the trainers, so the numbers are real, not copied from the log.
11
- The eval curve is parsed from logs/<exp>.log and the wall time from TB.
12
- """
13
- from __future__ import annotations
14
-
15
- import argparse
16
- import json
17
- import os
18
- import re
19
- from pathlib import Path
20
-
21
- import torch
22
-
23
- from evaluate import (evaluate, evaluate_starts, make_ppo_policy,
24
- make_sac_policy)
25
- from models import ActorCritic, SquashedGaussianActor
26
- from obs import obs_spec
27
- from sim import EPISODE_STEPS, Params
28
- from task import get_reward_preset, sample_train_init
29
-
30
-
31
- def build_policy(ck, algo, obs_dim):
32
- a = ck.get("args") or {}
33
- hidden = int(a.get("hidden", 128 if algo == "ppo" else 256))
34
- depth = int(a.get("depth", 2))
35
- if algo == "ppo":
36
- net = ActorCritic(obs_dim, act_dim=2, hidden=hidden, depth=depth)
37
- net.load_state_dict(ck["model"])
38
- return make_ppo_policy(net.actor), net
39
- net = SquashedGaussianActor(obs_dim, 2, hidden=hidden, depth=depth)
40
- net.load_state_dict(ck["model"])
41
- return make_sac_policy(net), net
42
-
43
-
44
- def parse_curve(log_path):
45
- rows = []
46
- if not os.path.exists(log_path):
47
- return rows
48
- pat = re.compile(
49
- r"iter\s+(\d+)\s+steps\s+([\d.]+)M.*?EVAL tc\s+([\d.]+)\s+"
50
- r"succ\s+(\d+)\s+everup\s+(\d+)\s+angerr\s+([\d.]+)\s+"
51
- r"ret\s+([-\d.]+)")
52
- pat_sac = re.compile(
53
- r"steps\s+([\d.]+)k\s+upd\s+(\d+).*?EVAL tc\s+([\d.]+)\s+"
54
- r"succ\s+(\d+)\s+everup\s+(\d+)\s+angerr\s+([\d.]+)\s+"
55
- r"ret\s+([-\d.]+)")
56
- for line in open(log_path, errors="ignore"):
57
- m = pat.search(line)
58
- if m:
59
- rows.append(dict(iter=int(m.group(1)),
60
- global_steps=int(float(m.group(2)) * 1e6),
61
- t_can=float(m.group(3)),
62
- success=float(m.group(4)),
63
- ever_up=float(m.group(5)),
64
- final_ang_err=float(m.group(6)),
65
- ep_return=float(m.group(7))))
66
- continue
67
- m = pat_sac.search(line)
68
- if m:
69
- rows.append(dict(global_steps=int(float(m.group(1)) * 1e3),
70
- n_updates=int(m.group(2)),
71
- t_can=float(m.group(3)),
72
- success=float(m.group(4)),
73
- ever_up=float(m.group(5)),
74
- final_ang_err=float(m.group(6)),
75
- ep_return=float(m.group(7))))
76
- return rows
77
-
78
-
79
- def tb_last(tb_root, exp, tag):
80
- from tensorboard.backend.event_processing.event_accumulator import (
81
- EventAccumulator)
82
- d = Path(tb_root) / exp
83
- if not d.is_dir():
84
- return None
85
- ea = EventAccumulator(str(d), size_guidance={"scalars": 0})
86
- ea.Reload()
87
- if tag not in ea.Tags().get("scalars", []):
88
- return None
89
- return ea.Scalars(tag)[-1].value
90
-
91
-
92
- def main():
93
- ap = argparse.ArgumentParser()
94
- ap.add_argument("--exp", required=True)
95
- ap.add_argument("--algo", required=True, choices=["ppo", "sac"])
96
- ap.add_argument("--obs", required=True)
97
- ap.add_argument("--reward", required=True)
98
- ap.add_argument("--init", required=True)
99
- ap.add_argument("--envs", type=int, required=True)
100
- ap.add_argument("--minutes", type=float, required=True)
101
- ap.add_argument("--seed", type=int, default=0)
102
- ap.add_argument("--ckpt-dir", default="checkpoints")
103
- ap.add_argument("--tb-root", default="tb")
104
- ap.add_argument("--out", default="results")
105
- ap.add_argument("--log-dir", default="logs")
106
- ap.add_argument("--robust-starts", type=int, default=8)
107
- args = ap.parse_args()
108
-
109
- ck_final = torch.load(os.path.join(args.ckpt_dir, args.exp + "_final.pt"),
110
- map_location="cpu")
111
- ck_best = torch.load(os.path.join(args.ckpt_dir, args.exp + "_best.pt"),
112
- map_location="cpu")
113
- obs_dim = ck_final["obs_dim"]
114
- spec = ck_final.get("obs") or obs_spec(args.obs)
115
- reward_w = ck_final.get("reward") or get_reward_preset(args.reward)
116
- p = Params()
117
- pol_final, _ = build_policy(ck_final, args.algo, obs_dim)
118
- pol_best, _ = build_policy(ck_best, args.algo, obs_dim)
119
- ev_final = evaluate(pol_final, p, EPISODE_STEPS, reward_w=reward_w,
120
- obs_mode=args.obs)
121
- ev_best = evaluate(pol_best, p, EPISODE_STEPS, reward_w=reward_w,
122
- obs_mode=args.obs)
123
-
124
- g = torch.Generator().manual_seed(args.seed * 1000 + 123)
125
- th, om = sample_train_init(args.robust_starts, gen=g)
126
- starts = list(zip(th.numpy(), om.numpy()))
127
- rob = evaluate_starts(pol_final, p, starts, EPISODE_STEPS,
128
- reward_w=reward_w, obs_mode=args.obs)
129
- rob_best = evaluate_starts(pol_best, p, starts, EPISODE_STEPS,
130
- reward_w=reward_w, obs_mode=args.obs)
131
-
132
- curve = parse_curve(os.path.join(args.log_dir, args.exp + ".log"))
133
- elapsed = tb_last(args.tb_root, args.exp, "time/elapsed_min")
134
- wall = float(elapsed) * 60.0 if elapsed is not None else 0.0
135
- steps = ck_final.get("global_steps")
136
- if not steps:
137
- steps = tb_last(args.tb_root, args.exp, "train/global_steps")
138
- out = dict(algo=args.algo, exp=args.exp, seed=args.seed,
139
- envs=args.envs, obs=spec, obs_dim=obs_dim,
140
- init=ck_final.get("init"), reward=reward_w,
141
- reward_preset=args.reward, args=ck_final.get("args"),
142
- minutes_budget=args.minutes, global_steps=int(steps or 0),
143
- wall_time_s=wall,
144
- steps_per_s=(float(steps) / wall) if wall > 0 else None,
145
- final_eval=ev_final, best_eval=ev_best,
146
- best_t_can=ev_best["t_can"], eval_curve=curve,
147
- robust=rob, robust_best=rob_best,
148
- checkpoints=dict(best=args.exp + "_best.pt",
149
- last=args.exp + "_last.pt",
150
- final=args.exp + "_final.pt"),
151
- reconstructed=True,
152
- reconstruct_note=("results JSON reconstructed by finalize_run.py "
153
- "after the trainer crashed post-checkpoint; "
154
- "fixed eval and robustness were re-run."))
155
- with open(os.path.join(args.out, args.exp + ".json"), "w") as f:
156
- json.dump(out, f, indent=2)
157
- print(json.dumps(dict(exp=args.exp, steps=out["global_steps"],
158
- wall_min=round(wall / 60.0, 1),
159
- final_t_can=ev_final["t_can"],
160
- best_t_can=ev_best["t_can"],
161
- final_success=ev_final["success"],
162
- best_success=ev_best["success"],
163
- robust_final=rob["success_rate"],
164
- robust_best=rob_best["success_rate"]), indent=2))
165
-
166
-
167
- if __name__ == "__main__":
168
- main()