File size: 17,535 Bytes
7ffaec7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
"""entry2_receiver.py: entry two's receiver R and its interface (reproduction/ENTRY-TWO-CHOICE-v3.md sections 1, 2 and 8;
review/ASTRA-ENTRY-TWO-CHOICE-V3-2026-10-13.md obligation 1). Pure Python and numpy: no MuJoCo, no torch, so the Mac tests it.

What it pins and derives:
  - the healthy walker XML, byte-exact as read on the box (dm_control 1.0.16, mujoco 3.1.2; suite/walker.xml SHA256 below);
  - R's XML, generated deterministically from it by a fixed list of edits whose numbers are DERIVED from four design
    parameters (thigh and shank half-lengths, torso density, shank tip radius), with the generated string's SHA256 pinned;
  - R's native observation (18) to MT30 slot (24) map, R's action slots, R's mask row [1, 1, 0, 1, 1, 0];
  - the scrambled-correspondence transport G: a signed permutation of the 18 ACTIVE observation coordinates and of the 4
    ACTIVE action coordinates, drawn once from default_rng(20261015), with its exact inverse (sign flips and index moves
    only, so P then P inverse is bitwise the identity).
Nothing here touches the box or a checkpoint. The generated XML keeps the suite's <include> lines, so it loads with
dm_control.suite.common.ASSETS exactly like the healthy walker.
"""
import hashlib
import json
import math
import xml.etree.ElementTree as ET

import numpy as np

# ---------------------------------------------------------------------------------------------------------------------
# Healthy walker, pinned (OBS 2026-10-12 and re-read 2026-10-12: ~/.venvs/tdmpc2/.../dm_control/suite/walker.xml).
WALKER_XML_SHA256 = "e8b6dd3bb40826dffed0faed978d9c5dd0aead7efaa28c27c4bb2df663af874c"
WALKER_PY_SHA256 = "826178d2a9a3299a5113c3d916a0469f44173143dd8561e4768d62a1e6ebf7db"   # suite/walker.py (reward, obs)
DM_CONTROL_VERSION = "1.0.16"
MUJOCO_VERSION = "3.1.2"
WALKER_XML = """<mujoco model="planar walker">
  <include file="./common/visual.xml"/>
  <include file="./common/skybox.xml"/>
  <include file="./common/materials.xml"/>

  <option timestep="0.0025"/>

  <statistic extent="2" center="0 0 1"/>

  <default>
    <joint damping=".1" armature="0.01" limited="true" solimplimit="0 .99 .01"/>
    <geom contype="1" conaffinity="0" friction=".7 .1 .1"/>
    <motor ctrlrange="-1 1" ctrllimited="true"/>
    <site size="0.01"/>
    <default class="walker">
      <geom material="self" type="capsule"/>
      <joint axis="0 -1 0"/>
    </default>
  </default>

  <worldbody>
    <geom name="floor" type="plane" conaffinity="1" pos="248 0 0" size="250 .8 .2" material="grid" zaxis="0 0 1"/>
    <body name="torso" pos="0 0 1.3" childclass="walker">
      <light name="light" pos="0 0 2" mode="trackcom"/>
      <camera name="side" pos="0 -2 .7" euler="60 0 0" mode="trackcom"/>
      <camera name="back" pos="-2 0 .5" xyaxes="0 -1 0 1 0 3" mode="trackcom"/>
      <joint name="rootz" axis="0 0 1" type="slide" limited="false" armature="0" damping="0"/>
      <joint name="rootx" axis="1 0 0" type="slide" limited="false" armature="0" damping="0"/>
      <joint name="rooty" axis="0 1 0" type="hinge" limited="false" armature="0" damping="0"/>
      <geom name="torso" size="0.07 0.3"/>
      <body name="right_thigh" pos="0 -.05 -0.3">
        <joint name="right_hip" range="-20 100"/>
        <geom name="right_thigh" pos="0 0 -0.225" size="0.05 0.225"/>
        <body name="right_leg" pos="0 0 -0.7">
          <joint name="right_knee" pos="0 0 0.25" range="-150 0"/>
          <geom name="right_leg" size="0.04 0.25"/>
          <body name="right_foot" pos="0.06 0 -0.25">
            <joint name="right_ankle" pos="-0.06 0 0" range="-45 45"/>
            <geom name="right_foot" zaxis="1 0 0" size="0.05 0.1"/>
          </body>
        </body>
      </body>
      <body name="left_thigh" pos="0 .05 -0.3" >
        <joint name="left_hip" range="-20 100"/>
        <geom name="left_thigh" pos="0 0 -0.225" size="0.05 0.225"/>
        <body name="left_leg" pos="0 0 -0.7">
          <joint name="left_knee" pos="0 0 0.25" range="-150 0"/>
          <geom name="left_leg" size="0.04 0.25"/>
          <body name="left_foot" pos="0.06 0 -0.25">
            <joint name="left_ankle" pos="-0.06 0 0" range="-45 45"/>
            <geom name="left_foot" zaxis="1 0 0" size="0.05 0.1"/>
          </body>
        </body>
      </body>
    </body>
  </worldbody>

  <sensor>
    <subtreelinvel name="torso_subtreelinvel" body="torso"/>
  </sensor>

  <actuator>
    <motor name="right_hip" joint="right_hip" gear="100"/>
    <motor name="right_knee" joint="right_knee" gear="50"/>
    <motor name="right_ankle" joint="right_ankle" gear="20"/>
    <motor name="left_hip" joint="left_hip" gear="100"/>
    <motor name="left_knee" joint="left_knee" gear="50"/>
    <motor name="left_ankle" joint="left_ankle" gear="20"/>
  </actuator>
</mujoco>
"""

# ---------------------------------------------------------------------------------------------------------------------
# R's design parameters (section 1). Everything else in R's XML is derived from these and the healthy file.
THIGH_HALF = 0.175            # healthy 0.225
SHANK_HALF = 0.35             # healthy 0.25
TORSO_DENSITY = 1500.0        # healthy: MuJoCo default 1000
SHANK_TIP_RADIUS = 0.04       # the shank capsule radius, unchanged from the healthy walker
DEFAULT_DENSITY = 1000.0      # MuJoCo's default geom density (walker.xml sets none)
HIP_DROP = 0.3                # hips at torso z -0.3 (unchanged)
LEG_BODY_DROP = 0.7           # leg body at thigh -0.7 (unchanged; asserted to equal 2 x THIGH_HALF + SHANK_HALF)
HEALTHY_STRAIGHT_HEIGHT = 1.30
STAND_HEIGHT_HEALTHY = 1.2    # suite walker _STAND_HEIGHT
SIDES = ("right", "left")


def _fmt(x):
    """Numbers written into the XML: shortest exact decimal, no trailing zeros (0.35 not 0.35000000000000003)."""
    s = f"{round(x, 10):.10f}".rstrip("0").rstrip(".")
    return "0" if s in ("-0", "") else s


def derived():
    """R's derived numbers (section 1): joint and body positions, straight-leg torso height, masses, stand height."""
    knee_pos = 2 * THIGH_HALF                                   # knee at thigh -0.35, i.e. leg body origin + 0.35
    leg_body_drop = 2 * THIGH_HALF + SHANK_HALF                 # 0.7: the shank's top sits at the knee
    straight_height = HIP_DROP + 2 * THIGH_HALF + 2 * SHANK_HALF + SHANK_TIP_RADIUS   # tips touch z = 0
    stand_height = STAND_HEIGHT_HEALTHY * straight_height / HEALTHY_STRAIGHT_HEIGHT
    torso = capsule_mass(0.07, 0.3, TORSO_DENSITY)
    thigh = capsule_mass(0.05, THIGH_HALF, DEFAULT_DENSITY)
    shank = capsule_mass(SHANK_TIP_RADIUS, SHANK_HALF, DEFAULT_DENSITY)
    return {"knee_pos": knee_pos, "leg_body_drop": leg_body_drop, "torso_z": straight_height,
            "straight_leg_torso_height": straight_height, "stand_height": stand_height, "stand_margin": stand_height / 2,
            "upright_height_threshold": 0.5 * straight_height,
            "mass_kg": {"torso": torso, "thigh": thigh, "shank": shank, "total": torso + 2 * (thigh + shank)},
            "nq": 7, "nv": 7, "nu": 4}


def capsule_mass(radius, half_length, density):
    """MuJoCo capsule mass: cylinder of length 2 x half plus two hemispheres."""
    return density * (math.pi * radius ** 2 * 2 * half_length + 4.0 / 3.0 * math.pi * radius ** 3)


def healthy_xml():
    """The pinned healthy XML, refusing if the embedded text no longer matches the pinned hash."""
    got = sha256_text(WALKER_XML)
    if got != WALKER_XML_SHA256:
        raise RuntimeError(f"embedded walker.xml SHA256 {got} is not the pinned {WALKER_XML_SHA256}")
    return WALKER_XML


def sha256_text(text):
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def _one(root, path):
    found = root.findall(path)
    if len(found) != 1:
        raise RuntimeError(f"expected exactly one match for {path}, found {len(found)}")
    return found[0]


def _expect(elem, attr, value):
    if elem.get(attr) != value:
        raise RuntimeError(f"{elem.tag} {elem.get('name')}: {attr} is {elem.get(attr)!r}, expected {value!r} (source changed?)")


def receiver_xml(source=None):
    """R's XML string, generated from the healthy XML by a fixed list of edits. Deterministic: same source, same string.
    Each edited attribute is first checked against the pinned healthy value, so a changed source fails loudly."""
    d = derived()
    if abs(d["leg_body_drop"] - LEG_BODY_DROP) > 1e-12:
        raise RuntimeError(f"leg body drop {d['leg_body_drop']} no longer equals the unchanged {LEG_BODY_DROP}")
    root = ET.fromstring(healthy_xml() if source is None else source)
    torso = _one(root, "./worldbody/body[@name='torso']")
    _expect(torso, "pos", "0 0 1.3")
    torso.set("pos", f"0 0 {_fmt(d['torso_z'])}")
    torso_geom = _one(torso, "./geom[@name='torso']")
    _expect(torso_geom, "size", "0.07 0.3")
    torso_geom.set("density", _fmt(TORSO_DENSITY))
    for side in SIDES:
        thigh = _one(torso, f"./body[@name='{side}_thigh']")
        thigh_geom = _one(thigh, f"./geom[@name='{side}_thigh']")
        _expect(thigh_geom, "size", "0.05 0.225")
        _expect(thigh_geom, "pos", "0 0 -0.225")
        thigh_geom.set("size", f"0.05 {_fmt(THIGH_HALF)}")
        thigh_geom.set("pos", f"0 0 {_fmt(-THIGH_HALF)}")
        leg = _one(thigh, f"./body[@name='{side}_leg']")
        _expect(leg, "pos", f"0 0 {_fmt(-LEG_BODY_DROP)}")          # stays
        knee = _one(leg, f"./joint[@name='{side}_knee']")
        _expect(knee, "pos", "0 0 0.25")
        knee.set("pos", f"0 0 {_fmt(d['leg_body_drop'] - d['knee_pos'])}")   # 0.35 above the leg body origin
        leg_geom = _one(leg, f"./geom[@name='{side}_leg']")
        _expect(leg_geom, "size", "0.04 0.25")
        leg_geom.set("size", f"{_fmt(SHANK_TIP_RADIUS)} {_fmt(SHANK_HALF)}")
        foot = _one(leg, f"./body[@name='{side}_foot']")
        leg.remove(foot)
    actuator = _one(root, "./actuator")
    for side in SIDES:
        ankle = _one(actuator, f"./motor[@name='{side}_ankle']")
        actuator.remove(ankle)
    return ET.tostring(root, encoding="unicode") + "\n"


# The generated string's hash, committed before stage 0 (section 1). Computed by receiver_xml() on the Mac (Python 3.14,
# ElementTree); entry2_stage0.sh and the runner refuse when the box generates a different string.
RECEIVER_XML_SHA256 = "79c64f2b53d61b4ae27a2baacb41b1e47f3e653f74c63b78113b714b7b59bd2c"


def receiver_xml_checked():
    xml = receiver_xml()
    got = sha256_text(xml)
    if got != RECEIVER_XML_SHA256:
        raise RuntimeError(f"generated receiver XML SHA256 {got} is not the committed {RECEIVER_XML_SHA256}")
    return xml


def bodies_in_order(xml):
    """Body names in MuJoCo's depth-first order (the order of xmat[1:], so of the walker's orientations)."""
    root = ET.fromstring(xml)
    return [b.get("name") for b in _one(root, "./worldbody").iter("body")]


def joints_in_order(xml):
    root = ET.fromstring(xml)
    return [j.get("name") for j in _one(root, "./worldbody").iter("joint")]


def actuators_in_order(xml):
    root = ET.fromstring(xml)
    return [m.get("name") for m in _one(root, "./actuator")]


def observation_names(xml):
    """The suite walker's flat observation, by name: orientations (xx, xz) per body, torso height, qvel per joint
    (suite/walker.py get_observation; TD-MPC2 concatenates the OrderedDict values in this order)."""
    names = []
    for b in bodies_in_order(xml):
        names += [f"{b}.xx", f"{b}.xz"]
    names.append("height")
    names += [f"qvel.{j}" for j in joints_in_order(xml)]
    return names


# ---------------------------------------------------------------------------------------------------------------------
# Interface (section 2). MT30 pads observations to 24 and actions to 6.
MT30_OBS_DIM = 24
MT30_ACTION_DIM = 6
R_OBS_DIM = 18
R_ACTION_DIM = 4
R_OBS_TO_SLOT = (0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 21, 22)   # R native index -> MT30 slot
INACTIVE_OBS_SLOTS = (6, 7, 12, 13, 20, 23)                                        # always 0.0
R_ACTION_SLOTS = (0, 1, 3, 4)                                                       # r_hip, r_knee, l_hip, l_knee
IGNORED_ACTION_SLOTS = (2, 5)
MASK_ROW = (1.0, 1.0, 0.0, 1.0, 1.0, 0.0)                                           # non-prefix; sum 4
R_TASK_INDEX = 30                                                                   # _task_emb grows to 31 rows
R_EMBEDDING_SOURCE_ROW = 1                                                          # row 30 copies walker-walk
R_EPISODE_LENGTH = 500
S_EMBEDDING_ROWS = {"walker-walk": 1, "walker-stand": 0, "hopper-hop": 18}           # section 8
HOPPER_NATIVE_MASK = (1.0, 1.0, 1.0, 1.0, 0.0, 0.0)                                 # named, NOT used (section 8)


def obs_to_slots(obs18):
    """R's native observation (..., 18) to the MT30 slot vector (..., 24); inactive slots exactly 0.0. A new array."""
    obs18 = np.asarray(obs18)
    if obs18.shape[-1] != R_OBS_DIM:
        raise ValueError(f"R observation must have {R_OBS_DIM} entries, got shape {obs18.shape}")
    out = np.zeros(obs18.shape[:-1] + (MT30_OBS_DIM,), dtype=obs18.dtype)
    out[..., list(R_OBS_TO_SLOT)] = obs18
    return out


def slots_to_action(a6):
    """The model's 6-slot action to R's 4 actuator commands (r_hip, r_knee, l_hip, l_knee); slots 2 and 5 ignored."""
    a6 = np.asarray(a6)
    if a6.shape[-1] != MT30_ACTION_DIM:
        raise ValueError(f"model action must have {MT30_ACTION_DIM} entries, got shape {a6.shape}")
    return a6[..., list(R_ACTION_SLOTS)].copy()


def slot_map_from_names():
    """The slot map recomputed from names (R's generated XML against the healthy XML), for the slot unit test."""
    healthy, r = observation_names(healthy_xml()), observation_names(receiver_xml())
    return tuple(healthy.index(n) for n in r)


# ---------------------------------------------------------------------------------------------------------------------
# G: scrambled correspondence on ACTIVE coordinates (section 2). Drawn once; the draw is pinned so a numpy that draws
# differently is refused rather than silently giving another G.
G_SEED = 20261015
G_PINNED = {"P_o": [10, 15, 7, 12, 6, 5, 9, 4, 3, 13, 2, 1, 16, 14, 11, 0, 8, 17],
            "s_o": [1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, 1],
            "P_a": [0, 3, 2, 1],
            "s_a": [1, -1, -1, 1]}


def draw_g(seed=G_SEED):
    """The frozen draw order: permutation(18), choice([-1, 1], 18), permutation(4), choice([-1, 1], 4)."""
    rng = np.random.default_rng(seed)
    return {"P_o": rng.permutation(R_OBS_DIM).tolist(), "s_o": rng.choice([-1, 1], R_OBS_DIM).tolist(),
            "P_a": rng.permutation(R_ACTION_DIM).tolist(), "s_a": rng.choice([-1, 1], R_ACTION_DIM).tolist()}


def g_checked():
    g = draw_g()
    if g != G_PINNED:
        raise RuntimeError(f"default_rng({G_SEED}) drew {g}, not the pinned G {G_PINNED} (numpy stream changed?)")
    return g


def g_sha256(g=None):
    g = G_PINNED if g is None else g
    return hashlib.sha256(json.dumps(g, sort_keys=True, separators=(",", ":")).encode()).hexdigest()


def _signed_perm(x, perm, signs, dim):
    x = np.asarray(x)
    if x.shape[-1] != dim:
        raise ValueError(f"expected last dimension {dim}, got shape {x.shape}")
    return x[..., list(perm)] * np.asarray(signs, dtype=x.dtype)


def _signed_perm_inverse(y, perm, signs, dim):
    y = np.asarray(y)
    if y.shape[-1] != dim:
        raise ValueError(f"expected last dimension {dim}, got shape {y.shape}")
    out = np.empty_like(y)
    out[..., list(perm)] = y * np.asarray(signs, dtype=y.dtype)     # signs are +-1, their own inverse
    return out


def g_obs(obs18, g=G_PINNED):
    """What the scrambled model sees on R's active coordinates: y_i = s_o[i] x obs[P_o[i]]."""
    return _signed_perm(obs18, g["P_o"], g["s_o"], R_OBS_DIM)


def g_obs_inverse(y18, g=G_PINNED):
    return _signed_perm_inverse(y18, g["P_o"], g["s_o"], R_OBS_DIM)


def g_action(m4, g=G_PINNED):
    """The command R executes from the scrambled model's 4 active action coordinates: u_i = s_a[i] x m[P_a[i]]."""
    return _signed_perm(m4, g["P_a"], g["s_a"], R_ACTION_DIM)


def g_action_inverse(u4, g=G_PINNED):
    return _signed_perm_inverse(u4, g["P_a"], g["s_a"], R_ACTION_DIM)


def g_obs_slots(obs18, g=G_PINNED):
    """G's full observation path: permute the ACTIVE coordinates, then place them in R's slots (inactive stay 0)."""
    return obs_to_slots(g_obs(obs18, g))


def g_slots_to_action(a6, g=G_PINNED):
    """G's full action path: R's active slots, then the signed permutation; mask row unchanged."""
    return g_action(slots_to_action(a6), g)


def binding():
    """Everything this module pins, for the stage-0 record (obligation 1)."""
    return {"walker_xml_sha256": WALKER_XML_SHA256, "walker_py_sha256": WALKER_PY_SHA256,
            "dm_control": DM_CONTROL_VERSION, "mujoco": MUJOCO_VERSION,
            "receiver_xml_sha256": RECEIVER_XML_SHA256, "receiver_params": {
                "thigh_half": THIGH_HALF, "shank_half": SHANK_HALF, "torso_density": TORSO_DENSITY,
                "shank_tip_radius": SHANK_TIP_RADIUS},
            "derived": derived(), "obs_to_slot": list(R_OBS_TO_SLOT), "inactive_obs_slots": list(INACTIVE_OBS_SLOTS),
            "action_slots": list(R_ACTION_SLOTS), "mask_row": list(MASK_ROW), "task_index": R_TASK_INDEX,
            "embedding_source_row": R_EMBEDDING_SOURCE_ROW, "g_seed": G_SEED, "g": G_PINNED, "g_sha256": g_sha256()}


if __name__ == "__main__":
    print(json.dumps(binding(), indent=1))