AmanC007 commited on
Commit
2eeee5a
·
verified ·
1 Parent(s): 5ccef49

Upload folder using huggingface_hub

Browse files
code/snow_rl/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """RL snow locomotion companion track."""
2
+
3
+ __version__ = "0.1.0"
code/snow_rl/belief.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local terrain belief map (ported from hackathon-everest's `mapping.py`).
2
+
3
+ This is the half of the problem the RL repo was missing. Without it the policy sees only
4
+ what is under its feet *right now*; with it, each foot's observation accumulates into a
5
+ spatial memory that the OTHER foot can read before it lands. That cross-foot transfer is
6
+ everest's central claim.
7
+
8
+ Notably, everest's own benchmark could not measure whether the map helped: decomposing its
9
+ 7 unsafe transfers showed all 7 were stance-capacity failures, which the bilateral gate
10
+ catches and the map has nothing to do with. Here the map is a separate observation channel
11
+ with its own ablation flag, so its contribution is directly measurable for the first time.
12
+
13
+ Differences from everest's version, all forced by running inside a 50 Hz JAX training loop:
14
+
15
+ * **Two channels, not six.** everest maps six quantities; only support and depth reach the
16
+ policy, so mapping the rest would cost memory for nothing.
17
+ * **Coarser.** 40x10 cells at 0.2 m over the corridor, versus everest's 40x40 at 0.05 m.
18
+ The map lives per-environment in `state.info`, so at 8192 envs this is ~52 MB; everest's
19
+ resolution would be ~26x that.
20
+ * **Reflect-tiled**, matching terrain.sample, so map and terrain stay in the same frame.
21
+ * Update is the same Gaussian-kernel Kalman step: a measurement at one point updates
22
+ neighbours with weight falling off over a correlation length.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ from typing import NamedTuple
27
+
28
+ import jax
29
+ import jax.numpy as jnp
30
+
31
+ from snow_rl.terrain import DEFAULT_CONFIG, TerrainConfig, _reflect
32
+
33
+ MAP_ROWS = 40 # along the corridor
34
+ MAP_COLS = 10 # across it
35
+ CORRELATION_LENGTH_M = 0.35
36
+ MIN_WEIGHT = 0.01 # below this a cell is left untouched
37
+
38
+ # Priors, matching everest's mapping.py defaults where they overlap.
39
+ PRIOR_SUPPORT_N = 330.0
40
+ PRIOR_SUPPORT_STD_N = 190.0
41
+ PRIOR_DEPTH_M = 0.08
42
+ PRIOR_DEPTH_STD_M = 0.07
43
+
44
+ SUPPORT_NORM_N = 900.0
45
+ DEPTH_NORM_M = 0.25
46
+
47
+ # Where the policy reads the map: offsets ahead of each foot, along the corridor.
48
+ LOOKAHEAD_M = (0.0, 0.25, 0.50)
49
+ READOUT_PER_FOOT = len(LOOKAHEAD_M) * 4 # mean+std for support and depth
50
+ READOUT_SIZE = 2 * READOUT_PER_FOOT # both feet
51
+
52
+
53
+ class BeliefMap(NamedTuple):
54
+ """Per-environment spatial memory. Leading axis is the env batch under vmap."""
55
+ support_mean: jax.Array # (MAP_ROWS, MAP_COLS) N
56
+ support_var: jax.Array
57
+ depth_mean: jax.Array # m
58
+ depth_var: jax.Array
59
+
60
+
61
+ def init() -> BeliefMap:
62
+ shape = (MAP_ROWS, MAP_COLS)
63
+ return BeliefMap(
64
+ support_mean=jnp.full(shape, PRIOR_SUPPORT_N),
65
+ support_var=jnp.full(shape, PRIOR_SUPPORT_STD_N**2),
66
+ depth_mean=jnp.full(shape, PRIOR_DEPTH_M),
67
+ depth_var=jnp.full(shape, PRIOR_DEPTH_STD_M**2),
68
+ )
69
+
70
+
71
+ def _fractional_cell(xy_m: jax.Array, cfg: TerrainConfig):
72
+ """World position -> fractional cell index, reflect-tiled.
73
+
74
+ Everything in this module works in CELL space and goes through this one function, so
75
+ `update` and `readout` cannot disagree. They previously did: update measured distances
76
+ with a periodic wrap while readout reflected, and the two used different half-cell
77
+ offsets. Beyond the corridor edge the map was written to one cell and read from another,
78
+ so a readout returned the untouched prior.
79
+ """
80
+ fx = _reflect((xy_m[..., 0] + cfg.length_m / 2) / (cfg.length_m / MAP_ROWS) - 0.5, MAP_ROWS)
81
+ fy = _reflect((xy_m[..., 1] + cfg.width_m / 2) / (cfg.width_m / MAP_COLS) - 0.5, MAP_COLS)
82
+ return fx, fy
83
+
84
+
85
+ def _kalman(mean, var, weight, observed, observed_std):
86
+ """Gaussian-kernel Kalman update: distant cells see a larger effective observation
87
+ variance, so a measurement informs its neighbourhood and not the whole map."""
88
+ effective_var = observed_std**2 / jnp.maximum(weight, 1e-6)
89
+ gain = jnp.where(weight >= MIN_WEIGHT, var / (var + effective_var), 0.0)
90
+ return mean + gain * (observed - mean), (1.0 - gain) * var
91
+
92
+
93
+ def update(
94
+ belief: BeliefMap,
95
+ xy_m: jax.Array, # (2,) where the measurement was taken
96
+ support_n: jax.Array, # ()
97
+ support_std_n: jax.Array,
98
+ depth_m: jax.Array,
99
+ depth_std_m: jax.Array,
100
+ cfg: TerrainConfig = DEFAULT_CONFIG,
101
+ ) -> BeliefMap:
102
+ """Fuse one foot's estimate into the map."""
103
+ fx, fy = _fractional_cell(xy_m, cfg)
104
+ rows = jnp.arange(MAP_ROWS)[:, None]
105
+ cols = jnp.arange(MAP_COLS)[None, :]
106
+ dx = (rows - fx) * (cfg.length_m / MAP_ROWS)
107
+ dy = (cols - fy) * (cfg.width_m / MAP_COLS)
108
+ weight = jnp.exp(-(dx**2 + dy**2) / (2.0 * CORRELATION_LENGTH_M**2))
109
+
110
+ sm, sv = _kalman(belief.support_mean, belief.support_var, weight,
111
+ support_n, jnp.maximum(support_std_n, 1.0))
112
+ dm, dv = _kalman(belief.depth_mean, belief.depth_var, weight,
113
+ depth_m, jnp.maximum(depth_std_m, 1e-3))
114
+ return BeliefMap(sm, sv, jnp.clip(dm, 0.0, DEPTH_NORM_M), dv)
115
+
116
+
117
+ def _index(xy_m: jax.Array, cfg: TerrainConfig):
118
+ """Nearest cell to a world position. Shares _fractional_cell with `update`."""
119
+ fx, fy = _fractional_cell(xy_m, cfg)
120
+ return (jnp.clip(jnp.round(fx), 0, MAP_ROWS - 1).astype(int),
121
+ jnp.clip(jnp.round(fy), 0, MAP_COLS - 1).astype(int))
122
+
123
+
124
+ def readout(belief: BeliefMap, feet_xy_m: jax.Array,
125
+ cfg: TerrainConfig = DEFAULT_CONFIG) -> jax.Array:
126
+ """What the policy sees: belief ahead of each foot, normalised.
127
+
128
+ Returns (READOUT_SIZE,) laid out per foot, per lookahead offset, as
129
+ [support_mean, support_std, depth_mean, depth_std].
130
+ """
131
+ out = []
132
+ for foot in range(feet_xy_m.shape[0]):
133
+ for ahead in LOOKAHEAD_M:
134
+ probe = feet_xy_m[foot] + jnp.array([ahead, 0.0])
135
+ i, j = _index(probe, cfg)
136
+ out.extend([
137
+ belief.support_mean[i, j] / SUPPORT_NORM_N,
138
+ jnp.sqrt(belief.support_var[i, j]) / SUPPORT_NORM_N,
139
+ belief.depth_mean[i, j] / DEPTH_NORM_M,
140
+ jnp.sqrt(belief.depth_var[i, j]) / DEPTH_NORM_M,
141
+ ])
142
+ return jnp.stack(out)
143
+
144
+
145
+ def lower_confidence_support_n(belief: BeliefMap, xy_m: jax.Array,
146
+ cfg: TerrainConfig = DEFAULT_CONFIG,
147
+ sigmas: float = 2.0) -> jax.Array:
148
+ """Conservative support at a point: mean minus `sigmas` standard deviations.
149
+
150
+ everest ranks candidate footholds on this rather than the mean, so uncertainty costs a
151
+ candidate rather than being averaged away.
152
+ """
153
+ i, j = _index(xy_m, cfg)
154
+ return belief.support_mean[i, j] - sigmas * jnp.sqrt(belief.support_var[i, j])
code/snow_rl/calibration.json ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "provenance": {
3
+ "everest_run": "/Users/amanchaturvedi/Downloads/hackathon-everest/artifacts/hackathon",
4
+ "split": "GroupShuffleSplit(test_size=0.2, random_state=7) on field_ids",
5
+ "test_rows": 1600,
6
+ "note": "Constants are MEASURED from held-out residuals, not read from metrics.json."
7
+ },
8
+ "channels": {
9
+ "depth": {
10
+ "target": "support_layer_depth_m",
11
+ "shrink_slope": 0.11488976992879023,
12
+ "shrink_intercept": 0.08103507116956066,
13
+ "conditional_sigma": 0.007665379221462171,
14
+ "marginal_resid_sigma": 0.040446905283101305,
15
+ "mae": 0.03405873929410382,
16
+ "r2_vs_truth": 0.1838656276345223,
17
+ "corr_pred_true": 0.5580474157879961,
18
+ "true_range": [
19
+ 0.0035311364258280116,
20
+ 0.17676305744572784
21
+ ],
22
+ "pred_range": [
23
+ 0.05175725721196922,
24
+ 0.13046398107648713
25
+ ],
26
+ "uncertainty_mean": 0.033883533334003735,
27
+ "uncertainty_resid_corr": 0.18187342955850128
28
+ },
29
+ "support": {
30
+ "target": "bearing_capacity_n",
31
+ "shrink_slope": 0.7777926775994604,
32
+ "shrink_intercept": 98.37118483237006,
33
+ "conditional_sigma": 54.42656827677319,
34
+ "marginal_resid_sigma": 64.69975570178208,
35
+ "mae": 47.53150995339508,
36
+ "r2_vs_truth": 0.8301844727273886,
37
+ "corr_pred_true": 0.9138006117791571,
38
+ "true_range": [
39
+ 131.55969690414213,
40
+ 880.3585953481258
41
+ ],
42
+ "pred_range": [
43
+ 175.0350035256734,
44
+ 802.3083153010995
45
+ ],
46
+ "uncertainty_mean": 51.312976119126816,
47
+ "uncertainty_resid_corr": 0.34593243745609764
48
+ },
49
+ "shear": {
50
+ "target": "shear_capacity_n",
51
+ "shrink_slope": 0.2741025418235506,
52
+ "shrink_intercept": 183.45698956678842,
53
+ "conditional_sigma": 49.041715227502706,
54
+ "marginal_resid_sigma": 89.34449980702163,
55
+ "mae": 72.23881704866716,
56
+ "r2_vs_truth": 0.24446201579531335,
57
+ "corr_pred_true": 0.49848685228679185,
58
+ "true_range": [
59
+ 41.39910438690268,
60
+ 560.0
61
+ ],
62
+ "pred_range": [
63
+ 133.5793557951209,
64
+ 448.09875115998557
65
+ ],
66
+ "uncertainty_mean": 67.30449921066794,
67
+ "uncertainty_resid_corr": 0.34267112305898634
68
+ }
69
+ },
70
+ "residual_correlation_depth_support": -0.11340331997482962,
71
+ "false_safe": {
72
+ "unsafe_threshold_n": 343.0,
73
+ "truly_unsafe_fraction": 0.373125,
74
+ "rate_conservative_lower_bound": 0.005025125628140704,
75
+ "rate_point_estimate": 0.30318257956448913
76
+ },
77
+ "void": {
78
+ "base_rate": 0.128125,
79
+ "recall": 1.0,
80
+ "precision": 1.0,
81
+ "false_positive_rate": 0.0
82
+ }
83
+ }
code/snow_rl/estimator.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """JAX support-estimate corruption model (Step 3).
2
+
3
+ Reproduces the *error behaviour* of hackathon-everest's sklearn ExtraTrees estimator so an
4
+ MJX/Brax training loop can consume a realistic support signal without ever calling sklearn.
5
+
6
+ Error structure is measured, not assumed (see scripts/calibrate_from_everest.py):
7
+
8
+ 1. Regression-to-the-mean shrinkage. The tree ensemble compresses its output range, so
9
+ `pred ~= intercept + slope * true`. This is the dominant error term and it is
10
+ *systematic* -- a policy cannot average it away the way it can average away noise.
11
+ Modelling it as zero-mean Gaussian would make the task substantially easier than reality.
12
+ 2. Conditional Gaussian noise around that shrunk value (smaller than the marginal residual
13
+ spread, because most of the marginal spread IS the shrinkage).
14
+ 3. False-safe events, latched per stance rather than per timestep -- see FALSE_SAFE_NOTE.
15
+ 4. Dropout that holds the last valid value and drops confidence.
16
+ 5. Per-environment noise scaling so no single calibration is memorised.
17
+
18
+ All functions are pure and vmap/jit-safe: no data-dependent Python control flow.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ from pathlib import Path
24
+ from typing import NamedTuple
25
+
26
+ import jax
27
+ import jax.numpy as jnp
28
+
29
+ CALIBRATION_PATH = Path(__file__).with_name("calibration.json")
30
+
31
+ DEPTH_NORM_M = 0.25 # RL terrain range 0..0.25 m
32
+ SUPPORT_NORM_N = 900.0 # material_priors bearing_capacity_n upper bound
33
+ N_FEET = 2
34
+ N_CHANNELS = 4 # depth_est, support_est, confidence, void_prob
35
+ OBS_SIZE = N_FEET * N_CHANNELS
36
+
37
+ # Fitted over the terrain generator's own distribution (see scripts/fit_support_to_depth.py).
38
+ # Valid only while bearing is derived from the sinkage law; regenerate if that changes.
39
+ SUPPORT_TO_DEPTH_SLOPE = -2.434e-4
40
+ SUPPORT_TO_DEPTH_INTERCEPT = 0.1649
41
+ # Chosen by measurement over the terrain distribution: corr(implied, true depth) is 0.776 at
42
+ # 0.75, 0.772 at 0.50, 0.767 depth-only, and only 0.375 support-only. Support contributes
43
+ # depth information mainly in shallow terrain -- once snow is deeper than the failure sinkage
44
+ # the substrate never carries load, so bearing stops distinguishing 12 cm from 25 cm.
45
+ DEPTH_CHANNEL_WEIGHT = 0.75
46
+
47
+ FALSE_SAFE_NOTE = """\
48
+ everest measures two very different false-safe rates on the same held-out split:
49
+ 0.005 when the consumer sees the CONSERVATIVE lower bound (mean - 2*sigma)
50
+ 0.303 when the consumer sees the POINT estimate
51
+ The brief's observation block hands the policy a point estimate plus a separate confidence,
52
+ which puts the honest rate near 0.303, not 0.005. Applying 0.005 would make the environment
53
+ ~60x more forgiving than the estimator it claims to model. Default here is the point-estimate
54
+ rate; set `false_safe_rate` explicitly to override."""
55
+
56
+
57
+ class Channel(NamedTuple):
58
+ slope: float
59
+ intercept: float
60
+ sigma: float
61
+
62
+
63
+ class EstimatorParams(NamedTuple):
64
+ depth: Channel
65
+ support: Channel
66
+ false_safe_rate: float
67
+ false_safe_support_n: float # what a false-safe estimate reports
68
+ dropout_prob: float
69
+ noise_scale_range: tuple[float, float]
70
+ confidence_resid_corr: float
71
+ void_false_positive_rate: float
72
+ void_false_negative_rate: float
73
+
74
+
75
+ class EstimatorState(NamedTuple):
76
+ """Per-environment carry. Leading axis is the env batch under vmap."""
77
+ last_obs: jax.Array # (N_FEET, N_CHANNELS) held values for dropout
78
+ false_safe: jax.Array # (N_FEET,) bool, latched for the current stance
79
+ noise_scale: jax.Array # () per-env multiplier on all sigmas
80
+
81
+
82
+ def load_params(
83
+ path: Path | str = CALIBRATION_PATH,
84
+ *,
85
+ false_safe_rate: float | None = None,
86
+ dropout_prob: float = 0.02,
87
+ void_false_positive_rate: float = 0.05,
88
+ void_false_negative_rate: float = 0.10,
89
+ ) -> EstimatorParams:
90
+ """Build params from measured calibration.
91
+
92
+ void_* rates default to non-zero on purpose. everest's void classifier scores a perfect
93
+ 1.0/1.0/0.0 on held-out data, which would hand the policy an oracle for voids and quietly
94
+ violate the "rewards never key off ground truth" constraint. Injecting realistic error
95
+ keeps void_prob an estimate rather than a truth channel.
96
+ """
97
+ cal = json.loads(Path(path).read_text())
98
+ ch = cal["channels"]
99
+ fs = cal["false_safe"]
100
+ rate = fs["rate_point_estimate"] if false_safe_rate is None else false_safe_rate
101
+ return EstimatorParams(
102
+ depth=Channel(ch["depth"]["shrink_slope"], ch["depth"]["shrink_intercept"],
103
+ ch["depth"]["conditional_sigma"]),
104
+ support=Channel(ch["support"]["shrink_slope"], ch["support"]["shrink_intercept"],
105
+ ch["support"]["conditional_sigma"]),
106
+ false_safe_rate=float(rate),
107
+ false_safe_support_n=float(fs["unsafe_threshold_n"] * 1.25),
108
+ dropout_prob=float(dropout_prob),
109
+ noise_scale_range=(0.7, 1.4),
110
+ confidence_resid_corr=float(ch["support"]["uncertainty_resid_corr"]),
111
+ void_false_positive_rate=float(void_false_positive_rate),
112
+ void_false_negative_rate=float(void_false_negative_rate),
113
+ )
114
+
115
+
116
+ def init_state(key: jax.Array, params: EstimatorParams) -> EstimatorState:
117
+ """Initialise one environment's carry. vmap over keys for a batch."""
118
+ lo, hi = params.noise_scale_range
119
+ return EstimatorState(
120
+ last_obs=jnp.zeros((N_FEET, N_CHANNELS)),
121
+ false_safe=jnp.zeros((N_FEET,), dtype=bool),
122
+ noise_scale=jax.random.uniform(key, (), minval=lo, maxval=hi),
123
+ )
124
+
125
+
126
+ def _shrink(true_value: jax.Array, ch: Channel) -> jax.Array:
127
+ return ch.intercept + ch.slope * true_value
128
+
129
+
130
+ def estimate(
131
+ key: jax.Array,
132
+ state: EstimatorState,
133
+ true_depth_m: jax.Array, # (N_FEET,)
134
+ true_support_n: jax.Array, # (N_FEET,)
135
+ true_void: jax.Array, # (N_FEET,) bool
136
+ new_stance: jax.Array, # (N_FEET,) bool -- foot just made contact
137
+ params: EstimatorParams,
138
+ ) -> tuple[jax.Array, EstimatorState]:
139
+ """One 50 Hz estimator tick for one environment.
140
+
141
+ Returns (obs, state) where obs is (OBS_SIZE,) laid out per foot as
142
+ [depth_est_norm, support_est_norm, confidence, void_prob].
143
+ """
144
+ k_d, k_s, k_fs, k_drop, k_conf, k_void = jax.random.split(key, 6)
145
+ scale = state.noise_scale
146
+
147
+ depth = _shrink(true_depth_m, params.depth) + params.depth.sigma * scale * jax.random.normal(
148
+ k_d, true_depth_m.shape
149
+ )
150
+ support = _shrink(true_support_n, params.support) + params.support.sigma * scale * jax.random.normal(
151
+ k_s, true_support_n.shape
152
+ )
153
+
154
+ # False-safe: resampled only on a NEW STANCE, then held for that stance's duration.
155
+ # Sampling per 50 Hz timestep instead would fire ~20x per 0.4 s stance and inflate the
156
+ # effective per-footstep rate by more than an order of magnitude.
157
+ unsafe = true_support_n < params.false_safe_support_n / 1.25
158
+ draw = jax.random.uniform(k_fs, true_support_n.shape) < params.false_safe_rate
159
+ fresh = jnp.where(new_stance, unsafe & draw, state.false_safe)
160
+ support = jnp.where(fresh, params.false_safe_support_n, support)
161
+
162
+ # Confidence: weakly informative, matching the measured |resid| vs uncertainty correlation.
163
+ # A false-safe estimate looks CONFIDENT -- that is what makes it dangerous.
164
+ resid_proxy = jnp.abs(support - _shrink(true_support_n, params.support)) / (
165
+ params.support.sigma * 3.0
166
+ )
167
+ # A false-safe is exactly the case where the tree ensemble AGREES and is wrong -- tight
168
+ # spread is why it cleared everest's 2-sigma gate. So it reports near-zero apparent
169
+ # residual, i.e. high confidence. That is what makes it dangerous rather than merely noisy.
170
+ resid_proxy = jnp.where(fresh, 0.0, resid_proxy)
171
+ noise_c = jax.random.uniform(k_conf, true_support_n.shape, minval=-0.3, maxval=0.3)
172
+ rho = params.confidence_resid_corr
173
+ confidence = jnp.clip(1.0 - rho * resid_proxy + noise_c, 0.0, 1.0)
174
+
175
+ flip = jax.random.uniform(k_void, true_void.shape)
176
+ void_prob = jnp.where(
177
+ true_void,
178
+ jnp.where(flip < params.void_false_negative_rate, 0.15, 0.85),
179
+ jnp.where(flip < params.void_false_positive_rate, 0.75, 0.10),
180
+ )
181
+
182
+ obs = jnp.stack(
183
+ [
184
+ jnp.clip(depth / DEPTH_NORM_M, 0.0, 1.5),
185
+ jnp.clip(support / SUPPORT_NORM_N, 0.0, 1.5),
186
+ confidence,
187
+ void_prob,
188
+ ],
189
+ axis=-1,
190
+ ) # (N_FEET, N_CHANNELS)
191
+
192
+ # Dropout: hold the last valid sample and collapse confidence.
193
+ dropped = jax.random.uniform(k_drop, (N_FEET,)) < params.dropout_prob
194
+ held = state.last_obs.at[:, 2].multiply(0.3)
195
+ obs = jnp.where(dropped[:, None], held, obs)
196
+
197
+ return obs.reshape(OBS_SIZE), EstimatorState(
198
+ last_obs=obs, false_safe=fresh, noise_scale=scale
199
+ )
200
+
201
+
202
+ def deshrink(value: jax.Array, ch: Channel) -> jax.Array:
203
+ """Invert the measured shrinkage to recover a correctly-SCALED estimate.
204
+
205
+ The raw estimate is compressed toward the training mean (depth slope 0.115), so as an
206
+ absolute number it is worse than a constant (R^2 -0.06) even though it still TRACKS truth
207
+ (corr +0.45). A learned policy could rescale such an input itself, but a fixed reward
208
+ formula cannot -- `depth_est + 0.05` would be a near-constant target.
209
+
210
+ De-shrinking restores the scale at the cost of amplifying noise by 1/slope. The result is
211
+ noisy but unbiased and correctly scaled, which is what a reward target needs.
212
+
213
+ Note this is only legitimate because the shrinkage was MEASURED on held-out data. It uses
214
+ no per-timestep ground truth and is applied to the corrupted estimate, so it does not leak.
215
+ """
216
+ return (value - ch.intercept) / ch.slope
217
+
218
+
219
+ def implied_depth_m(obs: jax.Array, params: EstimatorParams) -> jax.Array:
220
+ """Clearance-relevant snow depth implied by the estimator block, per foot.
221
+
222
+ Blends the de-shrunk depth channel with the depth implied by support. In terrain where
223
+ bearing is derived from the sinkage law the two are coupled (corr -0.50), so support
224
+ carries independent information about how deep the snow is.
225
+ """
226
+ depth_raw = obs[..., 0] * DEPTH_NORM_M
227
+ support_raw = obs[..., 1] * SUPPORT_NORM_N
228
+ from_depth = deshrink(depth_raw, params.depth)
229
+ from_support = SUPPORT_TO_DEPTH_SLOPE * deshrink(support_raw, params.support) + SUPPORT_TO_DEPTH_INTERCEPT
230
+ blended = DEPTH_CHANNEL_WEIGHT * from_depth + (1.0 - DEPTH_CHANNEL_WEIGHT) * from_support
231
+ return jnp.clip(blended, 0.0, DEPTH_NORM_M)
232
+
233
+
234
+ batched_estimate = jax.vmap(estimate, in_axes=(0, 0, 0, 0, 0, 0, None))
235
+ batched_init = jax.vmap(init_state, in_axes=(0, None))
code/snow_rl/evaluate.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 6 evaluation: roll out policies on a fixed strip and produce the comparison plots.
2
+
3
+ Written before training so the analysis exists when checkpoints land. Works with any policy
4
+ callable, including a zero/random policy, so the plumbing is testable with no GPU.
5
+
6
+ The four measurements from the brief:
7
+
8
+ * **swing clearance vs. implied depth** -- the headline. Baseline flat (no depth signal to
9
+ condition on), trained rising.
10
+ * **falls per N runs** -- the blunt outcome.
11
+ * **velocity held through the deep section** -- the trained policy should keep moving where
12
+ the baseline bogs down.
13
+ * **cost of transport** -- proof it is not simply high-stepping everywhere.
14
+
15
+ The honest caveat that belongs on any plot produced here: a baseline-vs-trained gap is
16
+ attributable to the sensor channel ONLY via the ablation env (`make_ablation_env`), because
17
+ the trained policy also saw snow. See docs/PIPELINE.md section 8.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass, field
23
+
24
+ import jax
25
+ import jax.numpy as jnp
26
+ import numpy as np
27
+
28
+ from snow_rl import estimator
29
+
30
+ Policy = Callable[[dict, jax.Array], jax.Array]
31
+
32
+ G1_MASS_KG = 35.0
33
+ GRAVITY = 9.81
34
+
35
+
36
+ @dataclass
37
+ class RolloutLog:
38
+ """Per-step traces from one episode."""
39
+ swing_peak_m: list = field(default_factory=list) # (T, 2)
40
+ landed: list = field(default_factory=list) # (T, 2) foot touched down
41
+ implied_depth_m: list = field(default_factory=list) # (T, 2)
42
+ true_depth_m: list = field(default_factory=list) # (T, 2)
43
+ velocity_mps: list = field(default_factory=list) # (T,)
44
+ commanded_mps: list = field(default_factory=list) # (T,)
45
+ x_position_m: list = field(default_factory=list) # (T,)
46
+ torque_power_w: list = field(default_factory=list) # (T,)
47
+ fell: bool = False
48
+
49
+ def stack(self) -> dict[str, np.ndarray]:
50
+ return {
51
+ "swing_peak_m": np.asarray(self.swing_peak_m),
52
+ "landed": np.asarray(self.landed),
53
+ "implied_depth_m": np.asarray(self.implied_depth_m),
54
+ "true_depth_m": np.asarray(self.true_depth_m),
55
+ "velocity_mps": np.asarray(self.velocity_mps),
56
+ "commanded_mps": np.asarray(self.commanded_mps),
57
+ "x_position_m": np.asarray(self.x_position_m),
58
+ "torque_power_w": np.asarray(self.torque_power_w),
59
+ "fell": self.fell,
60
+ }
61
+
62
+
63
+ def zero_policy(obs: dict, rng: jax.Array) -> jax.Array:
64
+ """Placeholder used to exercise the pipeline before a checkpoint exists."""
65
+ return None # replaced by caller-supplied action size
66
+
67
+
68
+ def rollout(env, policy: Policy, rng: jax.Array, steps: int = 400) -> dict[str, np.ndarray]:
69
+ """One episode. `policy(obs, rng) -> action`."""
70
+ step_fn = jax.jit(env.step)
71
+ state = jax.jit(env.reset)(rng)
72
+ log = RolloutLog()
73
+ prev_contact = np.zeros(2, dtype=bool)
74
+
75
+ for _ in range(steps):
76
+ rng, act_rng = jax.random.split(rng)
77
+ action = policy(state.obs, act_rng)
78
+ if action is None:
79
+ action = jnp.zeros(env.action_size)
80
+ state = step_fn(state, action)
81
+
82
+ obs8 = state.info["snow_obs"].reshape(estimator.N_FEET, estimator.N_CHANNELS)
83
+ implied = estimator.implied_depth_m(obs8, env._est_params)
84
+ truth = state.info["snow_truth"]
85
+
86
+ log.swing_peak_m.append(np.asarray(state.info["swing_peak"]))
87
+ # swing_peak resets on contact, so it is only MEANINGFUL at a landing. Recording the
88
+ # landing mask lets clearance_vs_depth use those samples instead of every step, where
89
+ # the value is mid-swing or freshly zeroed.
90
+ log.landed.append(np.asarray(state.info["last_contact"]) & ~prev_contact)
91
+ prev_contact = np.asarray(state.info["last_contact"])
92
+ log.implied_depth_m.append(np.asarray(implied))
93
+ log.true_depth_m.append(np.asarray(truth[: estimator.N_FEET]))
94
+ log.velocity_mps.append(float(state.data.qvel[0]))
95
+ log.commanded_mps.append(float(state.info["command"][0]))
96
+ log.x_position_m.append(float(state.data.qpos[0]))
97
+ log.torque_power_w.append(
98
+ float(jnp.sum(jnp.abs(state.data.actuator_force * state.data.qvel[6:])))
99
+ )
100
+ if float(state.done) > 0.5:
101
+ log.fell = True
102
+ break
103
+ return log.stack()
104
+
105
+
106
+ def cost_of_transport(trace: dict[str, np.ndarray]) -> float:
107
+ """Dimensionless: energy per unit weight per unit distance."""
108
+ distance = abs(trace["x_position_m"][-1] - trace["x_position_m"][0])
109
+ if distance < 1e-3:
110
+ return float("nan")
111
+ energy = float(np.sum(trace["torque_power_w"])) * 0.02 # ctrl_dt
112
+ return energy / (G1_MASS_KG * GRAVITY * distance)
113
+
114
+
115
+ def summarise(traces: list[dict[str, np.ndarray]], deep_threshold_m: float = 0.10) -> dict:
116
+ """Aggregate one policy's runs into the four headline numbers."""
117
+ falls = sum(int(t["fell"]) for t in traces)
118
+ deep_speeds, cots = [], []
119
+ for t in traces:
120
+ deep = t["true_depth_m"].mean(axis=1) > deep_threshold_m
121
+ if deep.any():
122
+ deep_speeds.append(float(np.mean(t["velocity_mps"][deep])))
123
+ cot = cost_of_transport(t)
124
+ if np.isfinite(cot):
125
+ cots.append(cot)
126
+ return {
127
+ "runs": len(traces),
128
+ "falls": falls,
129
+ "fall_rate": falls / max(len(traces), 1),
130
+ "deep_section_velocity_mps": float(np.mean(deep_speeds)) if deep_speeds else float("nan"),
131
+ "cost_of_transport": float(np.mean(cots)) if cots else float("nan"),
132
+ }
133
+
134
+
135
+ def clearance_vs_depth(traces: list[dict[str, np.ndarray]], bins: int = 10):
136
+ """The headline relationship: swing clearance as a function of implied depth.
137
+
138
+ Returns (bin_centres, mean_clearance, std_clearance, slope). A flat line means the policy
139
+ is not conditioning on the estimate.
140
+ """
141
+ depth = np.concatenate([t["implied_depth_m"].ravel() for t in traces])
142
+ peak = np.concatenate([t["swing_peak_m"].ravel() for t in traces])
143
+ if all("landed" in t and t["landed"].size for t in traces):
144
+ mask = np.concatenate([t["landed"].ravel() for t in traces]).astype(bool)
145
+ else:
146
+ mask = peak > 0
147
+ ok = np.isfinite(depth) & np.isfinite(peak) & mask
148
+ depth, peak = depth[ok], peak[ok]
149
+
150
+ # Say WHY there is no curve rather than returning empty arrays. This is the headline
151
+ # plot; a silent blank here reads as "the policy does not condition on the estimate",
152
+ # which is a very different claim from "the rollout produced too few landings".
153
+ if depth.size < 2 * bins:
154
+ raise ValueError(
155
+ f"only {depth.size} landing samples across {len(traces)} rollouts; need "
156
+ f"{2 * bins}. Run longer episodes or more of them."
157
+ )
158
+ if depth.std() < 1e-9:
159
+ raise ValueError(
160
+ "the implied-depth estimate does not vary across these rollouts, so no "
161
+ "relationship can be measured -- check the terrain regime mix"
162
+ )
163
+
164
+ bins = min(bins, max(2, depth.size // 5))
165
+ edges = np.linspace(depth.min(), depth.max(), bins + 1)
166
+ idx = np.clip(np.digitize(depth, edges) - 1, 0, bins - 1)
167
+ centres, means, stds = [], [], []
168
+ for b in range(bins):
169
+ m = idx == b
170
+ if m.sum() >= 2:
171
+ centres.append(0.5 * (edges[b] + edges[b + 1]))
172
+ means.append(float(peak[m].mean()))
173
+ stds.append(float(peak[m].std()))
174
+ slope = float(np.cov(depth, peak)[0, 1] / np.var(depth))
175
+ return np.asarray(centres), np.asarray(means), np.asarray(stds), slope
176
+
177
+
178
+ def sensor_dependence_check(env, policy: Policy, rng: jax.Array,
179
+ fabricated_depth_m: float = 0.18, steps: int = 200) -> dict:
180
+ """Feed a fabricated high depth estimate while the ground is genuinely firm.
181
+
182
+ If the policy steps high over nothing, the sensor channel really drives the gait. If it
183
+ walks normally, the policy learned to feel terrain through its own joints -- interesting,
184
+ but not the claimed result. Report either outcome.
185
+
186
+ Sweep WITHIN the range seen in training: fabricating a value the policy never saw is out
187
+ of distribution and a null result there would be ambiguous.
188
+ """
189
+ normal = rollout(env, policy, rng, steps=steps)
190
+ faked = rollout(env, _spoofing_policy(policy, fabricated_depth_m, env), rng, steps=steps)
191
+ return {
192
+ "fabricated_depth_m": fabricated_depth_m,
193
+ "clearance_normal_m": float(np.nanmean(normal["swing_peak_m"])),
194
+ "clearance_fabricated_m": float(np.nanmean(faked["swing_peak_m"])),
195
+ }
196
+
197
+
198
+ def _spoofing_policy(policy: Policy, depth_m: float, env) -> Policy:
199
+ """Overwrite the depth channel in the observation before the policy sees it."""
200
+ block = estimator.OBS_SIZE * 3
201
+ normalised = depth_m / estimator.DEPTH_NORM_M
202
+
203
+ def spoofed(obs: dict, rng: jax.Array) -> jax.Array:
204
+ state = obs["state"]
205
+ start = state.shape[-1] - block
206
+ idx = jnp.arange(start, state.shape[-1], estimator.N_CHANNELS)
207
+ state = state.at[idx].set(normalised)
208
+ return policy({**obs, "state": state}, rng)
209
+
210
+ return spoofed
code/snow_rl/sinkage.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Snow sinkage force (Step 2, part 2).
2
+
3
+ Follows the resistance law in hackathon-everest's `physics.py::_resistance_n`:
4
+
5
+ F = k_eff * d^1.12 + c * max(v_down, 0) + 3 * k_eff * max(d - d_support, 0)
6
+
7
+ with a void band that collapses resistance to 8%. Term by term:
8
+
9
+ * `k_eff * d^1.12` progressive compaction -- snow stiffens as it packs.
10
+ * `c * v_down` rate dependence -- snow resists a fast foot harder than a slow one.
11
+ Only the downward half; snow does not pull a lifting foot back.
12
+ * `3 * k_eff * (...)` bottoming out on the hard substrate once the foot passes through
13
+ the snow layer. The factor 3 makes that transition sharp.
14
+ * void a hollow under a crust: the foot meets almost nothing, then the
15
+ substrate term catches it. This is the breakthrough the policy must survive.
16
+
17
+ Applied to the feet as `xfrc_applied`, not as contact geometry -- see terrain.py for why.
18
+ The brief calls for depth-and-velocity dependence and explicitly not granular physics.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import jax
23
+ import jax.numpy as jnp
24
+
25
+ COMPACTION_EXPONENT = 1.12
26
+ SUBSTRATE_STIFFNESS_GAIN = 3.0
27
+ VOID_RESISTANCE_FACTOR = 0.08
28
+ MAX_FORCE_N = 2_000.0 # numerical guard; ~6x G1 body weight
29
+
30
+ # Ploughing. Vertical support alone is NOT enough to make deep snow hard: under uniform
31
+ # stiffness a foot reaches the same equilibrium sinkage in 0.07 m and 0.19 m of snow, so
32
+ # the two regimes would feel identical and the policy would have nothing to learn.
33
+ # What actually punishes deep snow is dragging the swing foot through it. Resistance scales
34
+ # with submerged frontal area (~ depth x foot width) and snow strength, saturating in speed.
35
+ # Sized so a foot swung through deep snow at walking speed meets ~30 N -- roughly 9% of body
36
+ # weight, enough to alter gait without immobilising the robot. The learning signal comes from
37
+ # clearance: a foot lifted clear of the surface ploughs nothing, so deeper snow demands a
38
+ # higher swing to escape the same drag.
39
+ PLOUGH_COEFF = 0.25
40
+ FOOT_WIDTH_M = 0.09 # G1 foot, approximate
41
+ PLOUGH_REFERENCE_SPEED_MPS = 0.4
42
+
43
+
44
+ def resistance_n(
45
+ penetration_m: jax.Array,
46
+ vertical_velocity_mps: jax.Array,
47
+ snow_depth_m: jax.Array,
48
+ stiffness_n_per_m: jax.Array,
49
+ damping_ns_per_m: jax.Array,
50
+ void: jax.Array,
51
+ include_substrate: bool = True,
52
+ ) -> jax.Array:
53
+ """Upward resisting force on a foot. Zero when the foot is above the snow surface.
54
+
55
+ penetration_m: depth below the snow surface, negative when clear of it.
56
+ vertical_velocity_mps: foot velocity, negative downward.
57
+
58
+ include_substrate: whether to add the bottoming-out term. TRUE when deriving bearing
59
+ capacity as a label (everest has no geometry, so the term is the only hard ground there).
60
+ FALSE when computing a force to APPLY in MuJoCo, where the substrate is a real plane with
61
+ a real contact solver -- adding it there double-counts the floor and fights the solver,
62
+ which produced spikes to 1530 N (~4.5x body weight) against the 2000 N clamp.
63
+ """
64
+ d = jnp.maximum(penetration_m, 0.0)
65
+ v_down = jnp.maximum(-vertical_velocity_mps, 0.0)
66
+
67
+ force = stiffness_n_per_m * d**COMPACTION_EXPONENT + damping_ns_per_m * v_down
68
+ # Void collapses the snow-column term only; the substrate below still stops the foot.
69
+ force = jnp.where(void, force * VOID_RESISTANCE_FACTOR, force)
70
+ if include_substrate:
71
+ force = force + SUBSTRATE_STIFFNESS_GAIN * stiffness_n_per_m * jnp.maximum(
72
+ d - snow_depth_m, 0.0
73
+ )
74
+ return jnp.clip(jnp.where(d > 0.0, force, 0.0), 0.0, MAX_FORCE_N)
75
+
76
+
77
+ def plough_force_n(
78
+ penetration_m: jax.Array,
79
+ horizontal_speed_mps: jax.Array,
80
+ stiffness_n_per_m: jax.Array,
81
+ void: jax.Array,
82
+ ) -> jax.Array:
83
+ """Magnitude of the horizontal drag on a foot moving through snow.
84
+
85
+ Opposes horizontal motion. Zero above the surface; a void offers almost nothing to plough.
86
+ """
87
+ submerged = jnp.maximum(penetration_m, 0.0)
88
+ strength = jnp.where(void, stiffness_n_per_m * VOID_RESISTANCE_FACTOR, stiffness_n_per_m)
89
+ force = (
90
+ PLOUGH_COEFF * strength * submerged * FOOT_WIDTH_M
91
+ * jnp.tanh(horizontal_speed_mps / PLOUGH_REFERENCE_SPEED_MPS)
92
+ )
93
+ return jnp.clip(force, 0.0, MAX_FORCE_N)
94
+
95
+
96
+ def foot_force_world_n(
97
+ foot_pos_z_m: jax.Array,
98
+ foot_vel_xyz_mps: jax.Array,
99
+ ground_z_m: jax.Array,
100
+ snow_depth_m: jax.Array,
101
+ stiffness_n_per_m: jax.Array,
102
+ damping_ns_per_m: jax.Array,
103
+ void: jax.Array,
104
+ ) -> jax.Array:
105
+ """World-frame (fx, fy, fz) per foot, ready for `data.xfrc_applied[body, :3]`.
106
+
107
+ The snow surface sits at `ground_z_m + snow_depth_m`; the hard substrate at `ground_z_m`.
108
+ Vertical term supports the foot; horizontal term ploughs against its motion.
109
+ """
110
+ penetration = ground_z_m + snow_depth_m - foot_pos_z_m
111
+ # include_substrate=False: MuJoCo's floor plane already stops the foot.
112
+ fz = resistance_n(penetration, foot_vel_xyz_mps[..., 2], snow_depth_m,
113
+ stiffness_n_per_m, damping_ns_per_m, void, include_substrate=False)
114
+ v_h = foot_vel_xyz_mps[..., :2]
115
+ speed = jnp.linalg.norm(v_h, axis=-1)
116
+ drag = plough_force_n(penetration, speed, stiffness_n_per_m, void)
117
+ direction = v_h / jnp.maximum(speed, 1e-6)[..., None]
118
+ return jnp.concatenate([-drag[..., None] * direction, fz[..., None]], axis=-1)
119
+
120
+
121
+ def equilibrium_sinkage_m(
122
+ load_n: jax.Array,
123
+ snow_depth_m: jax.Array,
124
+ stiffness_n_per_m: jax.Array,
125
+ void: jax.Array,
126
+ *,
127
+ iterations: int = 40,
128
+ ) -> jax.Array:
129
+ """Static sinkage where resistance balances `load_n`, by bisection.
130
+
131
+ Diagnostic and test helper -- the training loop integrates the force instead.
132
+ """
133
+ def body(bounds, _):
134
+ lo, hi = bounds
135
+ mid = 0.5 * (lo + hi)
136
+ f = resistance_n(mid, jnp.zeros_like(mid), snow_depth_m, stiffness_n_per_m,
137
+ jnp.zeros_like(mid), void)
138
+ too_soft = f < load_n
139
+ return (jnp.where(too_soft, mid, lo), jnp.where(too_soft, hi, mid)), None
140
+
141
+ lo = jnp.zeros_like(snow_depth_m)
142
+ hi = jnp.full_like(snow_depth_m, 1.0)
143
+ (lo, hi), _ = jax.lax.scan(body, (lo, hi), None, length=iterations)
144
+ return 0.5 * (lo + hi)
code/snow_rl/snow_env.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Snow locomotion environment (Step 4).
2
+
3
+ Wraps MuJoCo Playground's G1 joystick env. Three changes, nothing else:
4
+
5
+ 1. **Snow forces.** Each step, the per-environment depth field is sampled at both feet and a
6
+ sinkage + ploughing force is written into `data.xfrc_applied`. The MuJoCo ground stays a
7
+ flat plane representing the hard substrate -- snow is never geometry (see terrain.py).
8
+ 2. **Observations.** The 8 estimator values plus a 3-step history are appended to the actor's
9
+ `state` observation. The critic's `privileged_state` additionally receives true depth and
10
+ true bearing per foot -- training only, discarded at deployment.
11
+ 3. **Rewards.** Three terms on top of Playground's stock G1 terms, all scaled by confidence.
12
+
13
+ The design rule, from the brief: **the reward reads the estimate, never the truth.** Truth is
14
+ permitted only as the corruption function's input, in the critic, and in physics-consequence
15
+ terms (stumble). If the clearance target read true depth, the policy could succeed while
16
+ ignoring the sensor entirely and the experiment would prove nothing.
17
+
18
+ Terrain is stored as a shared BANK of pre-generated fields with a per-environment index,
19
+ rather than a field per environment. A field in `state.info` would be carried through every
20
+ rollout transition -- 160x40 floats x 8192 envs x unroll 20 is several GB. The bank costs
21
+ ~1.6 MB total and an int per environment.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from typing import Any
26
+
27
+ import jax
28
+ import jax.numpy as jnp
29
+ from ml_collections import config_dict
30
+ from mujoco import mjx
31
+ from mujoco_playground._src import mjx_env
32
+ from mujoco_playground._src.locomotion.g1 import joystick
33
+
34
+ from snow_rl import belief, estimator, sinkage, support
35
+ from snow_rl.terrain import DEFAULT_CONFIG as TERRAIN_CFG
36
+ from snow_rl.terrain import SnowField, batched_generate, sample
37
+
38
+ TERRAIN_BANK_SIZE = 64
39
+ HISTORY_STEPS = 3
40
+ CLEARANCE_MARGIN_M = 0.05
41
+ CLEARANCE_TOLERANCE = 0.01 # Gaussian width on the clearance target
42
+ FLAT_DEPTH_THRESHOLD_M = 0.03 # below this the estimate is calling the ground firm
43
+ FLAT_NOMINAL_CLEARANCE_M = 0.07
44
+ STUMBLE_FORCE_RATIO = 2.0
45
+ # A foot is "in contact" when snow carries this much load -- ~6% of body weight. Floor
46
+ # contact alone is not enough once snow is a force rather than geometry (see
47
+ # _stepped_with_snow_contact).
48
+ SNOW_CONTACT_FORCE_N = 20.0
49
+ # Uncertainty the belief map attaches to one contact observation. The estimator's own
50
+ # ensemble spread is only weakly informative (corr with true error +0.35), so a fixed
51
+ # conservative value is more honest than pretending the spread is calibrated.
52
+ MAP_OBS_STD_N = 70.0
53
+ MAP_OBS_STD_M = 0.05
54
+
55
+
56
+ def default_config() -> config_dict.ConfigDict:
57
+ """Playground's G1 config plus the snow terms. Stock values are untouched."""
58
+ cfg = joystick.default_config()
59
+ cfg.reward_config.scales.snow_clearance = 0.8
60
+ cfg.reward_config.scales.snow_stumble = -1.0
61
+ cfg.reward_config.scales.snow_flat_efficiency = -0.5
62
+ cfg.reward_config.scales.snow_overload = -0.4
63
+ cfg.snow = config_dict.create(
64
+ enable_forces=True,
65
+ # Zeroing this blanks the estimator block in the observation while leaving snow
66
+ # physics and rewards intact. This is the Step 6 ablation that isolates the sensor
67
+ # channel -- see docs/PIPELINE.md section 8.
68
+ estimator_channel=1.0,
69
+ # Separate flags so each half's contribution is measurable on its own. everest's
70
+ # benchmark could not separate its map from its support gate; this can.
71
+ map_channel=1.0,
72
+ support_channel=1.0,
73
+ false_safe_rate=-1.0, # <0 means "use the calibrated point-estimate rate"
74
+ terrain_bank_size=TERRAIN_BANK_SIZE,
75
+ terrain_seed=0,
76
+ )
77
+ return cfg
78
+
79
+
80
+ class SnowJoystick(joystick.Joystick):
81
+ """G1 joystick locomotion over variable-depth snow."""
82
+
83
+ def __init__(
84
+ self,
85
+ task: str = "flat_terrain",
86
+ config: config_dict.ConfigDict | None = None,
87
+ config_overrides: dict[str, Any] | None = None,
88
+ ):
89
+ super().__init__(task=task, config=config or default_config(),
90
+ config_overrides=config_overrides)
91
+
92
+ def _post_init(self) -> None:
93
+ super()._post_init()
94
+ self._terrain_cfg = TERRAIN_CFG
95
+ rate = self._config.snow.false_safe_rate
96
+ self._est_params = estimator.load_params(
97
+ false_safe_rate=None if rate < 0 else rate
98
+ )
99
+ # Feet bodies carry the snow force; site ids come from the parent env.
100
+ self._feet_body_id = jnp.asarray(self._mj_model.site_bodyid[self._feet_site_id])
101
+ self._terrain_bank: SnowField = batched_generate(
102
+ jax.random.split(jax.random.key(self._config.snow.terrain_seed),
103
+ self._config.snow.terrain_bank_size),
104
+ self._terrain_cfg,
105
+ )
106
+
107
+ # ---------------- terrain ----------------
108
+
109
+ def _field_at(self, index: jax.Array) -> SnowField:
110
+ return jax.tree_util.tree_map(lambda leaf: leaf[index], self._terrain_bank)
111
+
112
+ def _sample_feet(self, field: SnowField, feet_xyz: jax.Array):
113
+ """Snow state under each foot. Returns (depth, bearing, stiffness, damping, void)."""
114
+ return sample(field, self._terrain_cfg, feet_xyz[:, :2])
115
+
116
+ # ---------------- episode ----------------
117
+
118
+ def reset(self, rng: jax.Array) -> mjx_env.State:
119
+ rng, terrain_rng, est_rng = jax.random.split(rng, 3)
120
+ state = super().reset(rng)
121
+
122
+ index = jax.random.randint(terrain_rng, (), 0, self._config.snow.terrain_bank_size)
123
+ est_state = estimator.init_state(est_rng, self._est_params)
124
+ feet_xyz = state.data.site_xpos[self._feet_site_id]
125
+ field = self._field_at(index)
126
+ depth, bearing, _, _, void = self._sample_feet(field, feet_xyz)
127
+
128
+ obs8, est_state = estimator.estimate(
129
+ est_rng, est_state, depth, bearing, void > 0.5,
130
+ jnp.ones((2,), dtype=bool), self._est_params,
131
+ )
132
+ belief_map = belief.init()
133
+ state.info["snow_belief"] = belief_map
134
+ state.info["snow_map_readout"] = belief.readout(belief_map, feet_xyz[:, :2])
135
+ state.info["snow_support_obs"] = support.observation(
136
+ support.evaluate(bearing * 0.0 + support.G1_WEIGHT_N,
137
+ jnp.zeros(2), jnp.zeros(2))
138
+ )
139
+ state.info["snow_overload"] = jnp.zeros(())
140
+ state.info["snow_terrain_index"] = index
141
+ state.info["snow_obs"] = obs8
142
+ state.info["snow_history"] = jnp.tile(obs8, HISTORY_STEPS)
143
+ state.info["snow_truth"] = jnp.concatenate([depth, bearing])
144
+ state.info["snow_force"] = jnp.zeros((2, 3))
145
+ state.info["snow_last_feet_pos"] = feet_xyz
146
+ state.info["snow_est_last_obs"] = est_state.last_obs
147
+ state.info["snow_est_false_safe"] = est_state.false_safe
148
+ state.info["snow_est_noise_scale"] = est_state.noise_scale
149
+
150
+ state = state.replace(obs=self._get_obs(state.data, state.info,
151
+ state.info["last_contact"]))
152
+ for key in ("snow_clearance", "snow_stumble", "snow_flat_efficiency",
153
+ "snow_overload"):
154
+ state.metrics[f"reward/{key}"] = jnp.zeros(())
155
+ state.metrics["snow_depth_under_feet"] = jnp.mean(depth)
156
+ state.metrics["snow_contact_fraction"] = jnp.zeros(())
157
+ return state
158
+
159
+ def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
160
+ field = self._field_at(state.info["snow_terrain_index"])
161
+ feet_xyz = state.data.site_xpos[self._feet_site_id]
162
+ # Finite-difference foot velocity; MJX site velocities are not directly exposed.
163
+ feet_vel = (feet_xyz - state.info["snow_last_feet_pos"]) / self.dt
164
+ depth, bearing, stiffness, damping, void = self._sample_feet(field, feet_xyz)
165
+ void_b = void > 0.5
166
+
167
+ # Force for the estimator/reward at this control instant. The force actually applied
168
+ # to the physics is recomputed each substep inside _physics_with_snow.
169
+ force = sinkage.foot_force_world_n(
170
+ feet_xyz[:, 2], feet_vel, jnp.zeros((2,)), depth, stiffness, damping, void_b
171
+ )
172
+ force = force * self._config.snow.enable_forces
173
+
174
+ # A foot that has just landed starts a new stance -- the false-safe latch resamples
175
+ # here rather than every tick, which would inflate the per-footstep rate ~20x.
176
+ state.info["rng"], est_rng = jax.random.split(state.info["rng"])
177
+ new_stance = self._bearing_load(force) & ~state.info["last_contact"].astype(bool)
178
+ est_state = estimator.EstimatorState(
179
+ last_obs=state.info["snow_est_last_obs"],
180
+ false_safe=state.info["snow_est_false_safe"],
181
+ noise_scale=state.info["snow_est_noise_scale"],
182
+ )
183
+ obs8, est_state = estimator.estimate(
184
+ est_rng, est_state, depth, bearing, void_b, new_stance, self._est_params
185
+ )
186
+
187
+ # Fuse each foot's estimate into the spatial memory. Reads the ESTIMATE, not truth.
188
+ est = obs8.reshape(estimator.N_FEET, estimator.N_CHANNELS)
189
+ support_est_n = est[:, 1] * estimator.SUPPORT_NORM_N
190
+ implied = estimator.implied_depth_m(est, self._est_params)
191
+ belief_map = state.info["snow_belief"]
192
+ for foot in range(estimator.N_FEET):
193
+ belief_map = belief.update(
194
+ belief_map, feet_xyz[foot, :2], support_est_n[foot],
195
+ jnp.asarray(MAP_OBS_STD_N), implied[foot], jnp.asarray(MAP_OBS_STD_M),
196
+ )
197
+ state.info["snow_belief"] = belief_map
198
+ state.info["snow_map_readout"] = belief.readout(belief_map, feet_xyz[:, :2])
199
+
200
+ sup = support.evaluate(support_est_n, jnp.full((2,), MAP_OBS_STD_N), force[:, 2])
201
+ state.info["snow_support_obs"] = support.observation(sup)
202
+ state.info["snow_overload"] = support.overload_cost(
203
+ sup, self._bearing_load(force)
204
+ )
205
+
206
+ state.info["snow_obs"] = obs8
207
+ state.info["snow_history"] = jnp.concatenate(
208
+ [obs8, state.info["snow_history"][: estimator.OBS_SIZE * (HISTORY_STEPS - 1)]]
209
+ )
210
+ state.info["snow_truth"] = jnp.concatenate([depth, bearing])
211
+ state.info["snow_force"] = force
212
+ state.info["snow_last_feet_pos"] = feet_xyz
213
+ state.info["snow_est_last_obs"] = est_state.last_obs
214
+ state.info["snow_est_false_safe"] = est_state.false_safe
215
+ state.info["snow_est_noise_scale"] = est_state.noise_scale
216
+
217
+ state = self._stepped_with_snow_contact(state, action, field)
218
+ state.metrics["snow_depth_under_feet"] = jnp.mean(depth)
219
+ return state
220
+
221
+ def _snow_force_at(self, data, prev_feet_xyz, field, dt: float):
222
+ """Snow force on both feet given the current physics state."""
223
+ feet_xyz = data.site_xpos[self._feet_site_id]
224
+ feet_vel = (feet_xyz - prev_feet_xyz) / dt
225
+ depth, _, stiffness, damping, void = self._sample_feet(field, feet_xyz)
226
+ force = sinkage.foot_force_world_n(
227
+ feet_xyz[:, 2], feet_vel, jnp.zeros((2,)), depth, stiffness, damping, void > 0.5
228
+ )
229
+ return force * self._config.snow.enable_forces, feet_xyz
230
+
231
+ def _physics_with_snow(self, data, motor_targets: jax.Array, field):
232
+ """Substep the physics, recomputing the snow force at EVERY substep.
233
+
234
+ Playground's `mjx_env.step` holds `xfrc_applied` constant across all 10 substeps.
235
+ For a stiff spring applied as an external force that zero-order hold is an explicit
236
+ integrator, and it is unstable above k ~ m/ctrl_dt^2 ~ 5000 N/m with a ~2 kg effective
237
+ foot mass. The terrain generates stiffness up to 45000 N/m, so most of the range
238
+ diverged: measured growth 4.0x at k=12000 and 9.1x at k=45000, which showed up in
239
+ rollouts as the force pinned at its 2000 N clamp and swing feet launched to 0.67 m.
240
+
241
+ Recomputing inside the substep loop moves the limit to m/sim_dt^2 ~ 500000 N/m,
242
+ comfortably above the terrain's maximum. Measured growth is 1.0x at every stiffness.
243
+
244
+ The estimator, belief map and reward stay at the 50 Hz control rate -- those are
245
+ sensor-rate quantities and nothing about them is unstable.
246
+ """
247
+ def substep(carry, _):
248
+ d, prev = carry
249
+ force, feet_xyz = self._snow_force_at(d, prev, field, self.sim_dt)
250
+ xfrc = jnp.zeros_like(d.xfrc_applied).at[self._feet_body_id, :3].set(force)
251
+ d = d.replace(ctrl=motor_targets, xfrc_applied=xfrc)
252
+ d = mjx.step(self.mjx_model, d)
253
+ return (d, feet_xyz), force
254
+
255
+ feet0 = data.site_xpos[self._feet_site_id]
256
+ (data, _), forces = jax.lax.scan(
257
+ substep, (data, feet0), None, length=self.n_substeps
258
+ )
259
+ # Report the last substep's force: what the feet are feeling as control resumes.
260
+ return data, forces[-1]
261
+
262
+ def _bearing_load(self, snow_force: jax.Array) -> jax.Array:
263
+ """Feet whose vertical snow force is carrying meaningful load."""
264
+ return snow_force[:, 2] > SNOW_CONTACT_FORCE_N
265
+
266
+ def _stepped_with_snow_contact(self, state: mjx_env.State, action: jax.Array,
267
+ field) -> mjx_env.State:
268
+ """Playground's Joystick.step with ONE change: what counts as foot contact.
269
+
270
+ Playground reads a floor-contact sensor at z=0. Once snow is a force rather than
271
+ geometry that sensor stops meaning "the foot is standing on something": measured on
272
+ deep terrain it fired on 2 of 35 steps, because the snow held the foot at z~0.156 m
273
+ and it never reached the plane. Everything keyed to it broke -- `first_contact` never
274
+ fired so the clearance reward was dead exactly where the signal lives, `swing_peak`
275
+ never reset, and `feet_air_time` grew without bound.
276
+
277
+ Contact here means BEARING LOAD: the floor sensor OR snow carrying real weight.
278
+
279
+ This mirrors the upstream step body; re-check it when bumping mujoco_playground.
280
+ """
281
+ state.info["rng"], push1_rng, push2_rng = jax.random.split(state.info["rng"], 3)
282
+ push_theta = jax.random.uniform(push1_rng, maxval=2 * jnp.pi)
283
+ push_magnitude = jax.random.uniform(
284
+ push2_rng,
285
+ minval=self._config.push_config.magnitude_range[0],
286
+ maxval=self._config.push_config.magnitude_range[1],
287
+ )
288
+ push = jnp.array([jnp.cos(push_theta), jnp.sin(push_theta)])
289
+ push *= (
290
+ jnp.mod(state.info["push_step"] + 1, state.info["push_interval_steps"]) == 0
291
+ )
292
+ push *= self._config.push_config.enable
293
+ qvel = state.data.qvel
294
+ qvel = qvel.at[:2].set(push * push_magnitude + qvel[:2])
295
+ state = state.replace(data=state.data.replace(qvel=qvel))
296
+
297
+ motor_targets = self._default_pose + action * self._config.action_scale
298
+ data, applied_force = self._physics_with_snow(state.data, motor_targets, field)
299
+ state.info["motor_targets"] = motor_targets
300
+ state.info["snow_force"] = applied_force
301
+
302
+ floor_contact = jnp.array([
303
+ data.sensordata[self._mj_model.sensor_adr[sensorid]] > 0
304
+ for sensorid in self._feet_floor_found_sensor
305
+ ])
306
+ # >>> the one deviation from upstream <<<
307
+ contact = floor_contact | self._bearing_load(state.info["snow_force"])
308
+
309
+ contact_filt = contact | state.info["last_contact"]
310
+ first_contact = (state.info["feet_air_time"] > 0.0) * contact_filt
311
+ state.info["feet_air_time"] += self.dt
312
+ p_fz = data.site_xpos[self._feet_site_id][..., -1]
313
+ state.info["swing_peak"] = jnp.maximum(state.info["swing_peak"], p_fz)
314
+
315
+ obs = self._get_obs(data, state.info, contact)
316
+ done = self._get_termination(data)
317
+
318
+ rewards = self._get_reward(
319
+ data, action, state.info, state.metrics, done, first_contact, contact
320
+ )
321
+ rewards = {k: v * self._config.reward_config.scales[k] for k, v in rewards.items()}
322
+ reward = sum(rewards.values()) * self.dt
323
+
324
+ state.info["push"] = push
325
+ state.info["step"] += 1
326
+ state.info["push_step"] += 1
327
+ phase_tp1 = state.info["phase"] + state.info["phase_dt"]
328
+ state.info["phase"] = jnp.fmod(phase_tp1 + jnp.pi, 2 * jnp.pi) - jnp.pi
329
+ state.info["last_last_act"] = state.info["last_act"]
330
+ state.info["last_act"] = action
331
+ state.info["rng"], cmd_rng = jax.random.split(state.info["rng"])
332
+ state.info["command"] = jnp.where(
333
+ state.info["step"] > 500, self.sample_command(cmd_rng), state.info["command"]
334
+ )
335
+ state.info["step"] = jnp.where(done | (state.info["step"] > 500), 0,
336
+ state.info["step"])
337
+ state.info["feet_air_time"] *= ~contact
338
+ state.info["last_contact"] = contact
339
+ state.info["swing_peak"] *= ~contact
340
+ for k, v in rewards.items():
341
+ state.metrics[f"reward/{k}"] = v
342
+ state.metrics["swing_peak"] = jnp.mean(state.info["swing_peak"])
343
+ state.metrics["snow_contact_fraction"] = jnp.mean(contact.astype(float))
344
+
345
+ done = done.astype(reward.dtype)
346
+ return state.replace(data=data, obs=obs, reward=reward, done=done)
347
+
348
+ # ---------------- observations ----------------
349
+
350
+ def _snow_block(self, info: dict[str, Any]) -> jax.Array:
351
+ # The parent's reset() calls _get_obs before this env has populated its info keys.
352
+ # reset() recomputes the observation once they exist, so zeros here are transient.
353
+ history = info.get("snow_history")
354
+ if history is None:
355
+ return jnp.zeros(estimator.OBS_SIZE * HISTORY_STEPS)
356
+ return history * self._config.snow.estimator_channel
357
+
358
+ def _assurance_block(self, info: dict[str, Any]) -> jax.Array:
359
+ """everest's half: spatial memory plus bilateral support reserve."""
360
+ readout = info.get("snow_map_readout")
361
+ if readout is None:
362
+ readout = jnp.zeros(belief.READOUT_SIZE)
363
+ sup = info.get("snow_support_obs")
364
+ if sup is None:
365
+ sup = jnp.zeros(5)
366
+ return jnp.hstack([
367
+ readout * self._config.snow.map_channel,
368
+ sup * self._config.snow.support_channel,
369
+ ])
370
+
371
+ def _get_obs(self, data, info: dict[str, Any], contact: jax.Array):
372
+ obs = super()._get_obs(data, info, contact)
373
+ block = jnp.hstack([self._snow_block(info), self._assurance_block(info)])
374
+ return {
375
+ "state": jnp.hstack([obs["state"], block]),
376
+ # Privileged: the critic sees ground truth, the actor never does.
377
+ "privileged_state": jnp.hstack([
378
+ obs["privileged_state"], block,
379
+ info.get("snow_truth", jnp.zeros(2 * estimator.N_FEET)),
380
+ ]),
381
+ }
382
+
383
+ # ---------------- rewards ----------------
384
+
385
+ def _get_reward(self, data, action, info, metrics, done, first_contact, contact):
386
+ rewards = super()._get_reward(data, action, info, metrics, done,
387
+ first_contact, contact)
388
+ obs8 = info["snow_obs"].reshape(estimator.N_FEET, estimator.N_CHANNELS)
389
+ implied_depth = estimator.implied_depth_m(obs8, self._est_params)
390
+ confidence = obs8[:, 2]
391
+
392
+ rewards["snow_clearance"] = self._reward_snow_clearance(
393
+ info["swing_peak"], implied_depth, confidence, first_contact
394
+ )
395
+ rewards["snow_stumble"] = self._cost_snow_stumble(info["snow_force"], contact)
396
+ rewards["snow_flat_efficiency"] = self._cost_snow_flat_efficiency(
397
+ info["swing_peak"], implied_depth, confidence, first_contact
398
+ )
399
+ # everest's bilateral gate. It cannot halt a locomotion policy, so it becomes a cost
400
+ # for standing on a foothold the estimate says will not hold.
401
+ rewards["snow_overload"] = info["snow_overload"]
402
+ return rewards
403
+
404
+ def _reward_snow_clearance(self, swing_peak, implied_depth, confidence, first_contact):
405
+ """Score the swing foot's peak height against the depth the ESTIMATE implies.
406
+
407
+ Targets a value rather than rewarding 'higher is better' -- unbounded lifting is its
408
+ own failure mode. Scored once per step, when the swing ends.
409
+ """
410
+ target = implied_depth + CLEARANCE_MARGIN_M
411
+ score = jnp.exp(-((swing_peak - target) ** 2) / CLEARANCE_TOLERANCE)
412
+ return jnp.sum(score * confidence * first_contact)
413
+
414
+ def _cost_snow_stumble(self, snow_force, contact):
415
+ """Horizontal force on a foot exceeding twice the vertical -- ploughing through snow.
416
+
417
+ A physics consequence, so it may read the real force rather than the estimate.
418
+ """
419
+ horizontal = jnp.linalg.norm(snow_force[:, :2], axis=-1)
420
+ vertical = jnp.abs(snow_force[:, 2])
421
+ stumbling = horizontal > STUMBLE_FORCE_RATIO * vertical
422
+ return jnp.sum(stumbling & ~contact.astype(bool))
423
+
424
+ def _cost_snow_flat_efficiency(self, swing_peak, implied_depth, confidence, first_contact):
425
+ """Penalise lifting high when the estimate says the ground is firm.
426
+
427
+ Without this the policy prances everywhere, which technically satisfies the clearance
428
+ term and is obviously wrong.
429
+ """
430
+ on_flat = implied_depth < FLAT_DEPTH_THRESHOLD_M
431
+ excess = jnp.maximum(swing_peak - FLAT_NOMINAL_CLEARANCE_M, 0.0)
432
+ return jnp.sum(excess * on_flat * confidence * first_contact)
433
+
434
+
435
+ def make_snow_env(config_overrides: dict[str, Any] | None = None) -> SnowJoystick:
436
+ return SnowJoystick(config_overrides=config_overrides)
437
+
438
+
439
+ def make_no_map_env(config_overrides: dict[str, Any] | None = None) -> SnowJoystick:
440
+ """Spatial memory blanked, everything else intact.
441
+
442
+ This is the run everest could never do. Its own benchmark conflated the map with the
443
+ bilateral gate, and the decomposition showed the gate did all the work -- so the map's
444
+ contribution has never actually been measured. Against the full env, this isolates it.
445
+ """
446
+ overrides = dict(config_overrides or {})
447
+ overrides["snow.map_channel"] = 0.0
448
+ return SnowJoystick(config_overrides=overrides)
449
+
450
+
451
+ def make_no_support_env(config_overrides: dict[str, Any] | None = None) -> SnowJoystick:
452
+ """Bilateral reserve blanked, everything else intact."""
453
+ overrides = dict(config_overrides or {})
454
+ overrides["snow.support_channel"] = 0.0
455
+ return SnowJoystick(config_overrides=overrides)
456
+
457
+
458
+ def make_ablation_env(config_overrides: dict[str, Any] | None = None) -> SnowJoystick:
459
+ """Identical environment with the estimator block zeroed.
460
+
461
+ This is the comparison that isolates the sensor channel. Baseline-vs-trained differs in
462
+ three ways -- channel, rewards, AND snow training experience -- so only this run can
463
+ attribute a gap to the sensor.
464
+ """
465
+ overrides = dict(config_overrides or {})
466
+ overrides["snow.estimator_channel"] = 0.0
467
+ overrides["snow.map_channel"] = 0.0
468
+ overrides["snow.support_channel"] = 0.0
469
+ return SnowJoystick(config_overrides=overrides)
code/snow_rl/support.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bilateral support reserve (ported from hackathon-everest's `control.py`).
2
+
3
+ everest's central quantity: how much load each foot has left before its foothold fails.
4
+
5
+ reserve = lower_confidence_bearing - current_load
6
+
7
+ Worth porting specifically because it is the part of everest that demonstrably *worked*.
8
+ Decomposing everest's benchmark showed all 7 unsafe transfers were stance-capacity failures
9
+ -- the bilateral gate caught them, and the belief map contributed nothing measurable to that
10
+ number. So this is the load-bearing idea, and the map is the unproven one.
11
+
12
+ The translation to RL is not one-to-one. everest's controller emits a discrete decision
13
+ (COMMIT / HOLD_DOUBLE_SUPPORT / REPLANT) and can refuse to move. A locomotion policy is
14
+ handed a velocity command and must produce joint targets 50 times a second -- it cannot
15
+ refuse. So the gate becomes two continuous things instead:
16
+
17
+ * an **observation**: the policy sees each foot's reserve and can act on it;
18
+ * a **penalty**: loading a foot beyond its conservatively-estimated support is punished.
19
+
20
+ Both read the ESTIMATE, never the truth, so the policy cannot succeed by ignoring the sensor.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ from typing import NamedTuple
25
+
26
+ import jax
27
+ import jax.numpy as jnp
28
+
29
+ G1_WEIGHT_N = 343.0
30
+ SAFETY_BUFFER_N = 10.0
31
+ RESERVE_NORM_N = 400.0 # observation scaling
32
+ UNCERTAINTY_SIGMAS = 2.0 # everest uses mean - 2*sigma
33
+
34
+
35
+ class SupportState(NamedTuple):
36
+ """Per-foot support accounting. All values derived from the estimate."""
37
+ reserve_n: jax.Array # (2,) lower-confidence support minus current load
38
+ load_n: jax.Array # (2,) vertical load the snow is currently carrying
39
+ total_margin_n: jax.Array # () sum of both reserves
40
+
41
+
42
+ def evaluate(
43
+ support_est_n: jax.Array, # (2,) estimated bearing capacity per foot
44
+ support_std_n: jax.Array, # (2,) estimator uncertainty
45
+ load_n: jax.Array, # (2,) vertical snow force per foot
46
+ ) -> SupportState:
47
+ """Reserve on each foot, using the conservative lower bound rather than the mean."""
48
+ lower = support_est_n - UNCERTAINTY_SIGMAS * support_std_n
49
+ reserve = lower - load_n
50
+ return SupportState(
51
+ reserve_n=reserve,
52
+ load_n=load_n,
53
+ total_margin_n=jnp.sum(reserve),
54
+ )
55
+
56
+
57
+ def observation(state: SupportState) -> jax.Array:
58
+ """(5,) normalised: per-foot reserve, per-foot load, and total margin."""
59
+ return jnp.concatenate([
60
+ state.reserve_n / RESERVE_NORM_N,
61
+ state.load_n / RESERVE_NORM_N,
62
+ jnp.atleast_1d(state.total_margin_n / RESERVE_NORM_N),
63
+ ])
64
+
65
+
66
+ def overload_cost(state: SupportState, contact: jax.Array) -> jax.Array:
67
+ """Penalty for standing on a foothold the estimate says cannot hold you.
68
+
69
+ everest's gate as a continuous cost: a negative reserve on a loaded foot means the
70
+ conservative estimate of what this foothold carries is already exceeded. Counted only on
71
+ feet actually bearing load -- a swinging foot with no support underneath is not a fault.
72
+ """
73
+ deficit = jnp.maximum(-state.reserve_n, 0.0) / RESERVE_NORM_N
74
+ return jnp.sum(deficit * contact.astype(float))
75
+
76
+
77
+ def transfer_is_safe(state: SupportState, swing_index: int) -> jax.Array:
78
+ """everest's `transfer_is_safe`, kept for evaluation and diagnostics.
79
+
80
+ True when the stance foot's reserve covers the load about to move onto it. Not used as a
81
+ gate in training -- the policy cannot halt -- but reported so a rollout can be scored
82
+ against everest's own criterion.
83
+ """
84
+ stance = 1 - swing_index
85
+ return state.reserve_n[stance] >= state.load_n[swing_index] + SAFETY_BUFFER_N
code/snow_rl/terrain.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-environment correlated snow-depth fields (Step 2, part 1).
2
+
3
+ Ported from hackathon-everest's `terrain.py`, with two deliberate changes:
4
+
5
+ * **Snow is not geometry.** everest bakes terrain into a spatial grid it samples on the CPU;
6
+ Playground's rough-terrain env bakes it into a MuJoCo heightfield. Neither works here.
7
+ A heightfield models bumpy *solid* ground, but snow depth is a surface you sink *into* --
8
+ different physics. So the depth field lives as a plain JAX array and never becomes a geom.
9
+ The MuJoCo ground stays flat and represents the hard substrate under the snow.
10
+ * **Fixed correlation length.** everest draws a per-field correlation length. Doing that per
11
+ environment would need a per-env (H,H) blur matrix (~419 MB at 4096 envs x 160 cells).
12
+ The blur matrices here are shared constants and per-env variety comes from the noise,
13
+ the regime, and the amplitude instead. Contiguity -- the property the brief actually
14
+ requires -- is preserved.
15
+
16
+ Memory: a 160x40 corridor at 4096 envs is ~105 MB, versus ~1.07 GB for per-env heightfields.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from typing import NamedTuple
21
+
22
+ import jax
23
+ import jax.numpy as jnp
24
+
25
+ from snow_rl import sinkage
26
+
27
+ # Regime mixture from the brief: 30% flat, 40% shallow, 30% deep, mixed WITHIN each batch
28
+ # so the policy learns a conditional response rather than an averaged gait.
29
+ REGIME_EDGES = (0.30, 0.70)
30
+ REGIME_DEPTH_RANGE_M = (
31
+ (0.000, 0.010), # flat
32
+ (0.000, 0.100), # shallow
33
+ (0.100, 0.250), # deep
34
+ )
35
+ MAX_DEPTH_M = 0.25
36
+
37
+
38
+ class TerrainConfig(NamedTuple):
39
+ length_m: float = 8.0 # along the walking corridor (x)
40
+ width_m: float = 2.0 # across it (y)
41
+ cell_size_m: float = 0.05
42
+ correlation_length_m: float = 0.6
43
+
44
+ @property
45
+ def n_rows(self) -> int:
46
+ return round(self.length_m / self.cell_size_m)
47
+
48
+ @property
49
+ def n_cols(self) -> int:
50
+ return round(self.width_m / self.cell_size_m)
51
+
52
+
53
+ DEFAULT_CONFIG = TerrainConfig()
54
+
55
+
56
+ class SnowField(NamedTuple):
57
+ """One environment's snow. Leading axis is the env batch under vmap."""
58
+ depth_m: jax.Array # (H, W) snow thickness above the hard substrate
59
+ bearing_n: jax.Array # (H, W) load the patch supports before failing
60
+ stiffness_n_per_m: jax.Array # (H, W)
61
+ damping_ns_per_m: jax.Array # (H, W)
62
+ void: jax.Array # (H, W) bool, hollow under a crust
63
+ regime: jax.Array # () 0 flat, 1 shallow, 2 deep -- diagnostics only
64
+
65
+
66
+ # --- bearing capacity, derived from the sinkage law rather than generated independently ---
67
+ #
68
+ # An earlier version drew `bearing_n` from its own material noise, which made it statistically
69
+ # INDEPENDENT of snow depth (measured corr = -0.01). That contradicted this module's own
70
+ # physics: snow_rl.sinkage already gives shallow snow far more support, because the foot
71
+ # bottoms out on the substrate (the `3k(d - d_snow)` term). The label did not describe the
72
+ # force law it was labelling, and a support estimate therefore carried no information about
73
+ # how high to lift a foot.
74
+ #
75
+ # Bearing is now defined as the resisting force at a reference sinkage -- "the load this
76
+ # foothold carries before the foot has sunk 3 cm". That is consistent with the physics by
77
+ # construction, and reproduces the real coupling: thin snow over a hard substrate is strong,
78
+ # deep powder is weak.
79
+ #
80
+ # The log map is fitted so the distribution stays commensurate with the bearing_capacity_n
81
+ # everest's estimator was calibrated against (median 363 N vs everest's 383 N, no clipping).
82
+ FAILURE_SINKAGE_M = 0.03
83
+ BEARING_LOG_GAIN = 175.0
84
+ BEARING_LOG_OFFSET_N = 50.0
85
+ BEARING_RANGE_N = (100.0, 860.0)
86
+
87
+
88
+ def bearing_capacity_n(depth_m: jax.Array, stiffness_n_per_m: jax.Array) -> jax.Array:
89
+ """Load a foothold carries before sinking past FAILURE_SINKAGE_M."""
90
+ raw = sinkage.resistance_n(
91
+ jnp.full_like(depth_m, FAILURE_SINKAGE_M), jnp.zeros_like(depth_m),
92
+ depth_m, stiffness_n_per_m, jnp.zeros_like(depth_m),
93
+ jnp.zeros_like(depth_m, dtype=bool),
94
+ )
95
+ scaled = BEARING_LOG_GAIN * jnp.log1p(raw / BEARING_LOG_OFFSET_N)
96
+ return jnp.clip(scaled, *BEARING_RANGE_N)
97
+
98
+
99
+ def _blur_matrix(n: int, sigma_cells: float) -> jax.Array:
100
+ """Row-normalised Gaussian smoothing operator. Shared across envs, so it costs nothing."""
101
+ i = jnp.arange(n)
102
+ w = jnp.exp(-0.5 * ((i[:, None] - i[None, :]) / max(sigma_cells, 0.5)) ** 2)
103
+ return w / jnp.sum(w, axis=1, keepdims=True)
104
+
105
+
106
+ def _correlated_unit_field(key: jax.Array, cfg: TerrainConfig) -> jax.Array:
107
+ """Spatially correlated noise mapped to [0, 1] by quantile stretch (as everest does)."""
108
+ sigma = cfg.correlation_length_m / cfg.cell_size_m
109
+ raw = jax.random.normal(key, (cfg.n_rows, cfg.n_cols))
110
+ smooth = _blur_matrix(cfg.n_rows, sigma) @ raw @ _blur_matrix(cfg.n_cols, sigma).T
111
+ lo, hi = jnp.quantile(smooth, jnp.array([0.02, 0.98]))
112
+ return jnp.clip((smooth - lo) / jnp.maximum(hi - lo, 1e-9), 0.0, 1.0)
113
+
114
+
115
+ def generate(key: jax.Array, cfg: TerrainConfig = DEFAULT_CONFIG) -> SnowField:
116
+ """Generate one environment's snow field. vmap over keys for a batch."""
117
+ k_reg, k_depth, k_stiff, k_dens, k_wet, k_void = jax.random.split(key, 6)
118
+
119
+ u = jax.random.uniform(k_reg, ())
120
+ regime = (u >= REGIME_EDGES[0]).astype(jnp.int32) + (u >= REGIME_EDGES[1]).astype(jnp.int32)
121
+ lows = jnp.array([r[0] for r in REGIME_DEPTH_RANGE_M])
122
+ highs = jnp.array([r[1] for r in REGIME_DEPTH_RANGE_M])
123
+ depth = lows[regime] + _correlated_unit_field(k_depth, cfg) * (highs[regime] - lows[regime])
124
+
125
+ log_stiff = jnp.log(2_500.0) + _correlated_unit_field(k_stiff, cfg) * (
126
+ jnp.log(45_000.0) - jnp.log(2_500.0)
127
+ )
128
+ stiffness = jnp.exp(log_stiff)
129
+ density = 180.0 + _correlated_unit_field(k_dens, cfg) * (650.0 - 180.0)
130
+ wetness = _correlated_unit_field(k_wet, cfg) * 0.55
131
+ damping = jnp.clip(18.0 + 0.07 * density + 85.0 * wetness, 20.0, 140.0)
132
+ bearing = bearing_capacity_n(depth, stiffness)
133
+
134
+ # Voids only exist under snow deep enough to bridge one.
135
+ void = (_correlated_unit_field(k_void, cfg) > 0.88) & (depth > 0.08)
136
+
137
+ return SnowField(depth, bearing, stiffness, damping, void, regime)
138
+
139
+
140
+ def crossing_strip(cfg: TerrainConfig = DEFAULT_CONFIG) -> SnowField:
141
+ """Deterministic flat -> shallow -> deep corridor for Step 6 evaluation.
142
+
143
+ Fixed and seedless so every eval run crosses identical ground.
144
+ """
145
+ x = jnp.linspace(0.0, 1.0, cfg.n_rows)[:, None]
146
+ profile = jnp.where(x < 0.33, 0.005, jnp.where(x < 0.66, 0.07, 0.19))
147
+ depth = jnp.broadcast_to(profile, (cfg.n_rows, cfg.n_cols))
148
+ stiffness = jnp.full_like(depth, 12_000.0)
149
+ bearing = bearing_capacity_n(depth, stiffness)
150
+ damping = jnp.full_like(depth, 60.0)
151
+ return SnowField(depth, bearing, stiffness, damping,
152
+ jnp.zeros_like(depth, bool), jnp.int32(1))
153
+
154
+
155
+ def _reflect(index: jax.Array, n: int) -> jax.Array:
156
+ """Fold an unbounded cell index into [0, n-1] by reflection, so the field tiles seamlessly."""
157
+ period = 2.0 * (n - 1)
158
+ folded = jnp.mod(index, period)
159
+ return jnp.where(folded > n - 1, period - folded, folded)
160
+
161
+
162
+ def sample(field: SnowField, cfg: TerrainConfig, xy_m: jax.Array) -> tuple[jax.Array, ...]:
163
+ """Bilinearly sample the field at world positions.
164
+
165
+ xy_m: (..., 2) with x along the corridor, y across it, origin at the corridor centre.
166
+ Returns (depth_m, bearing_n, stiffness, damping, void_prob) each shaped (...,).
167
+ """
168
+ # Reflect-tile rather than clamp. A 20 s episode at up to 1.0 m/s covers ~20 m, but the
169
+ # corridor is 8 m -- clamping pinned a walking policy to the boundary row for most of every
170
+ # episode, feeding it one frozen depth value. Reflection (triangle wave) makes the field
171
+ # effectively infinite with no seam discontinuity, which plain modulo tiling would create.
172
+ fx = _reflect((xy_m[..., 0] + cfg.length_m / 2) / cfg.cell_size_m - 0.5, cfg.n_rows)
173
+ fy = _reflect((xy_m[..., 1] + cfg.width_m / 2) / cfg.cell_size_m - 0.5, cfg.n_cols)
174
+ i0, j0 = jnp.floor(fx).astype(int), jnp.floor(fy).astype(int)
175
+ i1 = jnp.minimum(i0 + 1, cfg.n_rows - 1)
176
+ j1 = jnp.minimum(j0 + 1, cfg.n_cols - 1)
177
+ tx, ty = fx - i0, fy - j0
178
+
179
+ def bilinear(grid: jax.Array) -> jax.Array:
180
+ g = grid.astype(float)
181
+ return (
182
+ g[i0, j0] * (1 - tx) * (1 - ty) + g[i1, j0] * tx * (1 - ty)
183
+ + g[i0, j1] * (1 - tx) * ty + g[i1, j1] * tx * ty
184
+ )
185
+
186
+ return tuple(bilinear(g) for g in
187
+ (field.depth_m, field.bearing_n, field.stiffness_n_per_m,
188
+ field.damping_ns_per_m, field.void))
189
+
190
+
191
+ batched_generate = jax.vmap(generate, in_axes=(0, None))
192
+ batched_sample = jax.vmap(sample, in_axes=(0, None, 0))
code/snow_rl/warmstart.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Warm-start surgery: widen a flat-ground checkpoint to fit the snow policy.
2
+
3
+ Step 1 trains stock `G1JoystickFlatTerrain`, whose actor sees 103 observations. The snow env
4
+ adds three blocks -- 24 estimator, 24 belief-map readout, 5 bilateral reserve -- so the actor
5
+ sees 156 and the critic 273. The first-layer weight matrices therefore differ:
6
+
7
+ actor (103, 512) -> (156, 512)
8
+ critic (216, 512) -> (273, 512)
9
+
10
+ Brax will not reconcile that. Loading the baseline directly either errors or silently
11
+ reinitialises, and silent reinitialisation is the dangerous outcome: training proceeds, curves
12
+ look plausible, and the warm start -- the entire reason Step 5 is affordable -- did nothing.
13
+
14
+ The fix is to **zero-pad the new input rows**. Zeros mean the expanded policy is initially
15
+ *exactly* the baseline: the new channels are multiplied by zero and cannot affect the output.
16
+ PPO then grows those weights from zero as the channels prove useful. That gives a clean
17
+ reading of the experiment -- the policy starts by ignoring the sensor and has to learn to use
18
+ it, rather than starting from a random dependence on it.
19
+
20
+ The observation normaliser needs the same treatment, and is easy to get wrong. It stores
21
+ mean, std and summed_variance per observation key. New entries are padded with mean 0 and
22
+ summed_variance equal to `count`, so the derived std is exactly 1 and the new channels pass
23
+ through unscaled. Our added blocks are already roughly unit-scaled by construction.
24
+
25
+ Layers after the first are untouched -- only the input width changes.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ from typing import Any
30
+
31
+ import jax
32
+ import jax.numpy as jnp
33
+
34
+ STATE_KEY = "state"
35
+ PRIVILEGED_KEY = "privileged_state"
36
+
37
+
38
+ def _pad_rows(kernel: jax.Array, target_rows: int) -> jax.Array:
39
+ """Grow a (in, out) weight matrix to (target_rows, out), new rows zeroed."""
40
+ current = kernel.shape[0]
41
+ if current == target_rows:
42
+ return kernel
43
+ if current > target_rows:
44
+ raise ValueError(
45
+ f"checkpoint first layer has {current} inputs but the target env expects "
46
+ f"{target_rows}; shrinking is not supported"
47
+ )
48
+ return jnp.concatenate(
49
+ [kernel, jnp.zeros((target_rows - current, kernel.shape[1]), kernel.dtype)], axis=0
50
+ )
51
+
52
+
53
+ def _expand_first_layer(params: Any, target_rows: int) -> Any:
54
+ """Zero-pad `hidden_0`'s kernel. Every later layer is unaffected."""
55
+ inner = params.get("params", params)
56
+ kernel = inner["hidden_0"]["kernel"]
57
+ padded = _pad_rows(kernel, target_rows)
58
+ new_inner = dict(inner)
59
+ new_inner["hidden_0"] = dict(inner["hidden_0"])
60
+ new_inner["hidden_0"]["kernel"] = padded
61
+ if "params" in params:
62
+ out = dict(params)
63
+ out["params"] = new_inner
64
+ return out
65
+ return new_inner
66
+
67
+
68
+ def _expand_normaliser(norm: Any, targets: dict[str, int]) -> Any:
69
+ """Pad running statistics so new channels start at mean 0, std 1.
70
+
71
+ summed_variance is padded with `count` rather than zero, because brax derives
72
+ std = sqrt(summed_variance / count). Padding with zeros would give std 0 and produce
73
+ divide-by-zero or infinite normalised values on the new channels.
74
+ """
75
+ count = jnp.asarray(norm.count)
76
+
77
+ def pad(tree, fill):
78
+ out = {}
79
+ for key, value in tree.items():
80
+ target = targets.get(key)
81
+ if target is None or value.shape[-1] == target:
82
+ out[key] = value
83
+ continue
84
+ extra = target - value.shape[-1]
85
+ if extra < 0:
86
+ raise ValueError(
87
+ f"normaliser '{key}' has {value.shape[-1]} entries but the target env "
88
+ f"expects {target}; shrinking is not supported"
89
+ )
90
+ out[key] = jnp.concatenate(
91
+ [value, jnp.full((extra,), fill, value.dtype)], axis=-1
92
+ )
93
+ return out
94
+
95
+ return norm.replace(
96
+ mean=pad(norm.mean, 0.0),
97
+ std=pad(norm.std, 1.0),
98
+ summed_variance=pad(norm.summed_variance, float(count)),
99
+ )
100
+
101
+
102
+ def expand_params(params: Any, actor_obs_size: int, critic_obs_size: int) -> Any:
103
+ """Widen a saved brax PPO checkpoint to a larger observation.
104
+
105
+ Accepts either the 2-tuple `(normaliser, policy)` used for inference or the 3-tuple
106
+ `(normaliser, policy, value)` from a training checkpoint, and returns the same shape.
107
+ """
108
+ if not isinstance(params, (tuple, list)) or len(params) not in (2, 3):
109
+ raise TypeError(
110
+ f"expected a (normaliser, policy[, value]) tuple, got {type(params).__name__}"
111
+ )
112
+ targets = {STATE_KEY: actor_obs_size, PRIVILEGED_KEY: critic_obs_size}
113
+ normaliser = _expand_normaliser(params[0], targets)
114
+ policy = _expand_first_layer(params[1], actor_obs_size)
115
+ if len(params) == 2:
116
+ return (normaliser, policy)
117
+ value = _expand_first_layer(params[2], critic_obs_size)
118
+ return (normaliser, policy, value)
119
+
120
+
121
+ def expand_for_env(params: Any, env) -> Any:
122
+ """Widen a baseline checkpoint to fit a snow env's observation sizes."""
123
+ return expand_params(
124
+ params,
125
+ actor_obs_size=int(env.observation_size[STATE_KEY][0]),
126
+ critic_obs_size=int(env.observation_size[PRIVILEGED_KEY][0]),
127
+ )
128
+
129
+
130
+ def added_channel_slice(baseline_actor_size: int, env) -> slice:
131
+ """Where the added blocks sit in the actor observation.
132
+
133
+ Useful for asserting that a freshly expanded policy ignores them.
134
+ """
135
+ return slice(baseline_actor_size, int(env.observation_size[STATE_KEY][0]))
136
+
137
+
138
+ def assert_behaviourally_identical(
139
+ baseline_apply,
140
+ expanded_apply,
141
+ baseline_params,
142
+ expanded_params,
143
+ baseline_obs: dict[str, jax.Array],
144
+ expanded_obs: dict[str, jax.Array],
145
+ tolerance: float = 1e-5,
146
+ ) -> float:
147
+ """Check the expansion changed nothing, and return the max deviation.
148
+
149
+ The whole point of zero-padding is that the expanded policy reproduces the baseline
150
+ exactly on any observation whose leading entries match. If this fails, the warm start is
151
+ not a warm start.
152
+ """
153
+ a = baseline_apply(baseline_params, baseline_obs)
154
+ b = expanded_apply(expanded_params, expanded_obs)
155
+ deviation = float(jnp.max(jnp.abs(jnp.asarray(a) - jnp.asarray(b))))
156
+ if deviation > tolerance:
157
+ raise AssertionError(
158
+ f"expanded policy deviates from the baseline by {deviation:.2e} "
159
+ f"(tolerance {tolerance:.0e}); the warm start would not be faithful"
160
+ )
161
+ return deviation
162
+
163
+
164
+ def summarise(params: Any, env) -> dict[str, Any]:
165
+ """Human-readable report of what an expansion will do."""
166
+ norm, policy = params[0], params[1]
167
+ actor_now = policy["params"]["hidden_0"]["kernel"].shape[0]
168
+ actor_target = int(env.observation_size[STATE_KEY][0])
169
+ out = {
170
+ "actor_inputs": (actor_now, actor_target, actor_target - actor_now),
171
+ "normaliser_state": (
172
+ int(jax.tree_util.tree_leaves(norm.mean[STATE_KEY])[0].shape[-1]), actor_target
173
+ ),
174
+ }
175
+ if len(params) == 3:
176
+ critic_now = params[2]["params"]["hidden_0"]["kernel"].shape[0]
177
+ critic_target = int(env.observation_size[PRIVILEGED_KEY][0])
178
+ out["critic_inputs"] = (critic_now, critic_target, critic_target - critic_now)
179
+ return out