nablaengine 1.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nablaengine/__init__.py +4 -0
- nablaengine/_fixtures/README.md +19 -0
- nablaengine/_fixtures/data/mf_s0.npz +0 -0
- nablaengine/_fixtures/mjlab/LICENSE +27 -0
- nablaengine/_fixtures/mjlab/README.md +113 -0
- nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
- nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
- nablaengine/_optional.py +30 -0
- nablaengine/_paths.py +38 -0
- nablaengine/actuators/__init__.py +169 -0
- nablaengine/actuators/bam.py +306 -0
- nablaengine/actuators/bam_params/LICENSE +202 -0
- nablaengine/actuators/bam_params/xl330/m6.json +19 -0
- nablaengine/boxbox.py +259 -0
- nablaengine/ccd.py +1122 -0
- nablaengine/checks.py +376 -0
- nablaengine/cuda.py +483 -0
- nablaengine/dist_query.py +628 -0
- nablaengine/dual.py +223 -0
- nablaengine/dyn_query.py +685 -0
- nablaengine/engines.py +114 -0
- nablaengine/envs/__init__.py +24 -0
- nablaengine/envs/brax.py +165 -0
- nablaengine/envs/convert.py +771 -0
- nablaengine/envs/dmc.py +523 -0
- nablaengine/envs/env.py +233 -0
- nablaengine/envs/kin.py +371 -0
- nablaengine/envs/ops.py +134 -0
- nablaengine/envs/rewards.py +57 -0
- nablaengine/fixtures.py +243 -0
- nablaengine/forest_engine/__init__.py +0 -0
- nablaengine/forest_engine/adjoint.py +1726 -0
- nablaengine/forest_engine/adjoint_contact.py +493 -0
- nablaengine/forest_engine/bam_hooks.py +248 -0
- nablaengine/forest_engine/body_params.py +1007 -0
- nablaengine/forest_engine/capacity_diag.py +116 -0
- nablaengine/forest_engine/ccd_coop.py +250 -0
- nablaengine/forest_engine/chol_blk.py +80 -0
- nablaengine/forest_engine/contact_forces.py +142 -0
- nablaengine/forest_engine/contact_vjp.py +462 -0
- nablaengine/forest_engine/convex.py +1331 -0
- nablaengine/forest_engine/cylinder.py +73 -0
- nablaengine/forest_engine/dist_device.py +923 -0
- nablaengine/forest_engine/dyn_device.py +696 -0
- nablaengine/forest_engine/ellipsoid.py +179 -0
- nablaengine/forest_engine/elliptic.py +272 -0
- nablaengine/forest_engine/equality.py +842 -0
- nablaengine/forest_engine/floss.py +148 -0
- nablaengine/forest_engine/foot_offset.py +368 -0
- nablaengine/forest_engine/free_gyro.py +288 -0
- nablaengine/forest_engine/host.py +530 -0
- nablaengine/forest_engine/kdof64.py +127 -0
- nablaengine/forest_engine/kinematics.py +320 -0
- nablaengine/forest_engine/margin.py +167 -0
- nablaengine/forest_engine/margin_convex.py +326 -0
- nablaengine/forest_engine/midphase.py +439 -0
- nablaengine/forest_engine/model_hooks.py +913 -0
- nablaengine/forest_engine/motor_hooks.py +50 -0
- nablaengine/forest_engine/muscle.py +485 -0
- nablaengine/forest_engine/nb128.py +118 -0
- nablaengine/forest_engine/nb64.py +163 -0
- nablaengine/forest_engine/noslip.py +1124 -0
- nablaengine/forest_engine/nv128.py +1944 -0
- nablaengine/forest_engine/object_size.py +283 -0
- nablaengine/forest_engine/replay_guard.py +40 -0
- nablaengine/forest_engine/root_spread.py +126 -0
- nablaengine/forest_engine/solref.py +74 -0
- nablaengine/forest_engine/source.py +1464 -0
- nablaengine/forest_engine/sparse_pattern.py +527 -0
- nablaengine/forest_engine/spatial.py +1045 -0
- nablaengine/forest_engine/step.py +3083 -0
- nablaengine/forest_engine/surrogate.py +498 -0
- nablaengine/forest_engine/tape.py +199 -0
- nablaengine/forest_engine/tendon.py +845 -0
- nablaengine/forest_engine/terrain.py +1059 -0
- nablaengine/forest_engine/world_forces.py +166 -0
- nablaengine/forest_engine/world_params.py +230 -0
- nablaengine/g1_engine/__init__.py +0 -0
- nablaengine/g1_engine/adjoint.py +1661 -0
- nablaengine/g1_engine/adjoint_contact.py +577 -0
- nablaengine/g1_engine/bam_hooks.py +596 -0
- nablaengine/g1_engine/condim4.py +245 -0
- nablaengine/g1_engine/contact_forces.py +500 -0
- nablaengine/g1_engine/cylccd.py +1158 -0
- nablaengine/g1_engine/cylinder.py +216 -0
- nablaengine/g1_engine/elliptic.py +565 -0
- nablaengine/g1_engine/exact_replay.py +61 -0
- nablaengine/g1_engine/host.py +358 -0
- nablaengine/g1_engine/kinematics.py +320 -0
- nablaengine/g1_engine/mesh.py +305 -0
- nablaengine/g1_engine/mesh_tables.py +79 -0
- nablaengine/g1_engine/model_hooks.py +919 -0
- nablaengine/g1_engine/motor_hooks.py +70 -0
- nablaengine/g1_engine/replay_guard.py +55 -0
- nablaengine/g1_engine/source.py +1107 -0
- nablaengine/g1_engine/sphbox.py +93 -0
- nablaengine/g1_engine/step.py +3716 -0
- nablaengine/g1_engine/tape.py +173 -0
- nablaengine/g1_engine/world_params.py +447 -0
- nablaengine/identity.py +401 -0
- nablaengine/jax_ffi.py +2536 -0
- nablaengine/model/__init__.py +1 -0
- nablaengine/model/capability.py +694 -0
- nablaengine/model/fields.py +317 -0
- nablaengine/model/gravcomp.py +64 -0
- nablaengine/model/invweight.py +145 -0
- nablaengine/motor.py +143 -0
- nablaengine/object_geometry.py +609 -0
- nablaengine/params.py +258 -0
- nablaengine/provenance.py +196 -0
- nablaengine/reference/__init__.py +0 -0
- nablaengine/reference/adjoint_groups.py +226 -0
- nablaengine/reference/jax64.py +690 -0
- nablaengine/reference/warp_physics.py +262 -0
- nablaengine/sensors/__init__.py +4 -0
- nablaengine/sensors/cameras.py +285 -0
- nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
- nablaengine/sensors/data/livox_mid360.npz +0 -0
- nablaengine/sensors/g1.py +521 -0
- nablaengine/sensors/jax_rays.py +364 -0
- nablaengine/sensors/optix_rays.py +725 -0
- nablaengine/sensors/raycore.py +630 -0
- nablaengine/sensors/raygrad.py +374 -0
- nablaengine/sensors/raygrad_cuda.py +191 -0
- nablaengine/sensors/robot_mesh.py +273 -0
- nablaengine/sensors/torch_rays.py +275 -0
- nablaengine/terrain.py +424 -0
- nablaengine/torch_ffi.py +1328 -0
- nablaengine/workdir.py +37 -0
- nablaengine-1.0.2.dist-info/METADATA +236 -0
- nablaengine-1.0.2.dist-info/RECORD +136 -0
- nablaengine-1.0.2.dist-info/WHEEL +5 -0
- nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
- nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
- nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
- nablaengine-1.0.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""The forward tape of the G1 engine: one record per world and substep, the residuals of the analytic adjoint."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from nablaengine.g1_engine import step
|
|
6
|
+
|
|
7
|
+
ALIGN = 32
|
|
8
|
+
FLAG_UNSUPPORTED = 31
|
|
9
|
+
FLAG_REFACT = 1 << 8
|
|
10
|
+
FLAG_NONCONV = 1 << 9
|
|
11
|
+
FLAG_SINGULAR = 1 << 10
|
|
12
|
+
FLAG_VERIFY_DIFF = 1 << 11
|
|
13
|
+
SINGULAR_NU = 5e-3
|
|
14
|
+
CON_NONE = 0xFFFF
|
|
15
|
+
CON_NONE_WIDE = 0xFFFFFFFF
|
|
16
|
+
|
|
17
|
+
_FIELDS = (
|
|
18
|
+
("hdr", "OFF_HDR", 1),
|
|
19
|
+
("flags", "OFF_FLAGS", 1),
|
|
20
|
+
("min_nu", "OFF_MIN_NU", 1),
|
|
21
|
+
("reserved", "OFF_RESERVED", 1),
|
|
22
|
+
("clamp", "OFF_CLAMP", lambda nq, nv, ntri, nc: -(-nv // 32)),
|
|
23
|
+
("zone", "OFF_ZONE", lambda nq, nv, ntri, nc: -(-step.NEFC // 32)),
|
|
24
|
+
("con", "OFF_CON", lambda nq, nv, ntri, nc: -(-nc // 2)),
|
|
25
|
+
("qpos", "OFF_QPOS", lambda nq, nv, ntri, nc: nq),
|
|
26
|
+
("qvel", "OFF_QVEL", lambda nq, nv, ntri, nc: nv),
|
|
27
|
+
("qacc", "OFF_QACC", lambda nq, nv, ntri, nc: nv),
|
|
28
|
+
("qacc_adv", "OFF_QADV", lambda nq, nv, ntri, nc: nv),
|
|
29
|
+
("kvw", "OFF_KVW", lambda nq, nv, ntri, nc: nv),
|
|
30
|
+
("mslope", "OFF_MSLOPE", lambda nq, nv, ntri, nc: nv),
|
|
31
|
+
(None, None, ALIGN),
|
|
32
|
+
("L_H", "OFF_LH", lambda nq, nv, ntri, nc: ntri),
|
|
33
|
+
(None, None, ALIGN),
|
|
34
|
+
("L_Q", "OFF_LQ", lambda nq, nv, ntri, nc: ntri),
|
|
35
|
+
(None, None, ALIGN),
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
_TERRAIN_FIELDS = (("telem", "OFF_TELEM", lambda nq, nv, ntri, nc: -(-nc // 2)),)
|
|
40
|
+
_NATIVE_FIELDS = (("taux", "OFF_TAUX", lambda nq, nv, ntri, nc: nc),)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def kind(terrain):
|
|
44
|
+
"""The record kind of a build: None (no terrain), "analytic" or "native" (terrain: (TerrainConfig, geoms), a
|
|
45
|
+
TerrainConfig, or None)."""
|
|
46
|
+
if terrain is None:
|
|
47
|
+
return None
|
|
48
|
+
cfg = terrain[0] if isinstance(terrain, tuple) else terrain
|
|
49
|
+
return cfg.mode
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _wide(m, terrain):
|
|
53
|
+
return not terrain and m.npair >= step.WIDE_PAIRS
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _table(m, max_contacts=None, terrain=False, max_rows=None, motor=False):
|
|
57
|
+
nc = max_contacts or step.maxcon(m)
|
|
58
|
+
nv, ntri, nefc, wide = m.nv, m.nv * (m.nv + 1) // 2, step.nefc(max_rows), _wide(m, terrain)
|
|
59
|
+
npmax = 1024 if terrain else (65536 if wide else 512)
|
|
60
|
+
assert nv <= 64 and m.npair < npmax and nc <= 255 and nefc <= step.MAX_ROWS, \
|
|
61
|
+
"field widths (clamp u64, pair bits, ncon u8, zone words)"
|
|
62
|
+
fields = _FIELDS
|
|
63
|
+
if step.clamp_implicit()[0] != 2:
|
|
64
|
+
fields = tuple(f for f in fields if f[0] != "kvw")
|
|
65
|
+
if not motor:
|
|
66
|
+
fields = tuple(f for f in fields if f[0] != "mslope")
|
|
67
|
+
if terrain:
|
|
68
|
+
i = [f[0] for f in _FIELDS].index("con") + 1
|
|
69
|
+
base = tuple(f for f in _FIELDS if motor or f[0] != "mslope")
|
|
70
|
+
fields = base[:i] + _TERRAIN_FIELDS + (_NATIVE_FIELDS if terrain == "native" else ()) + base[i:]
|
|
71
|
+
out, off = [], 0
|
|
72
|
+
for name, define, n in fields:
|
|
73
|
+
if name is None:
|
|
74
|
+
off = -(-off // n) * n
|
|
75
|
+
continue
|
|
76
|
+
n = n(m.nq, nv, ntri, nc) if callable(n) else n
|
|
77
|
+
if name == "zone":
|
|
78
|
+
n = -(-nefc // 32)
|
|
79
|
+
elif name == "con" and wide:
|
|
80
|
+
n = nc
|
|
81
|
+
out.append((name, define, off, n))
|
|
82
|
+
off += n
|
|
83
|
+
return out, off
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def layout(m, max_contacts=None, terrain=False, max_rows=None, motor=False):
|
|
87
|
+
"""{name: (offset, length)} of a record in 32-bit words (mjlab model: L_H at 192, L_Q at 832, 1472 words).
|
|
88
|
+
terrain: a terrain build's record kind (kind(): "analytic" or "native"; _TERRAIN_FIELDS, _NATIVE_FIELDS). motor:
|
|
89
|
+
a motor-limit build (nablaengine.motor: the mslope field)."""
|
|
90
|
+
return {name: (off, n) for name, _, off, n in _table(m, max_contacts, terrain, max_rows, motor)[0]}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def rec_words(m, max_contacts=None, terrain=False, max_rows=None, motor=False):
|
|
94
|
+
"""Record length in words (a multiple of ALIGN)."""
|
|
95
|
+
return _table(m, max_contacts, terrain, max_rows, motor)[1]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def header(m, max_contacts=None, terrain=False, max_rows=None, motor=False):
|
|
99
|
+
"""#define OFF_* / REC_WORDS / TAPE_* for the engine's CUDA code (step.py)."""
|
|
100
|
+
tab, total = _table(m, max_contacts, terrain, max_rows, motor)
|
|
101
|
+
lines = [f"#define REC_WORDS {total} // tape record (tape.py): words per world and substep"]
|
|
102
|
+
lines += [f"#define {define} {off} // {name}, {n} words" for name, define, off, n in tab]
|
|
103
|
+
lines += [f"#define TAPE_REFACT {FLAG_REFACT}u", f"#define TAPE_NONCONV {FLAG_NONCONV}u",
|
|
104
|
+
f"#define TAPE_SINGULAR {FLAG_SINGULAR}u", f"#define TAPE_VERIFY_DIFF {FLAG_VERIFY_DIFF}u",
|
|
105
|
+
f"#define TAPE_SINGULAR_NU {SINGULAR_NU}f",
|
|
106
|
+
f"#define TAPE_CON_NONE {CON_NONE_WIDE if _wide(m, terrain) else CON_NONE}u"]
|
|
107
|
+
return "\n" + "\n".join(lines) + "\n"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def tri_unpack(packed, n):
|
|
111
|
+
"""(..., n (n + 1) / 2) packed lower triangles TRI(i, j) -> (..., n, n) lower-triangular matrices."""
|
|
112
|
+
packed = np.asarray(packed)
|
|
113
|
+
i, j = np.tril_indices(n)
|
|
114
|
+
out = np.zeros(packed.shape[:-1] + (n, n), packed.dtype)
|
|
115
|
+
out[..., i, j] = packed[..., i * (i + 1) // 2 + j]
|
|
116
|
+
return out
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def factor_forms(m):
|
|
120
|
+
"""{"L_Q": form, "L_H": form} of model m's records under $DK_TREE_CHOL (step.tree_chol_stages): "dense" (A = L L',
|
|
121
|
+
the default) or "tree" (A = R' R, R on the tree pattern; the same packed storage)."""
|
|
122
|
+
st = step.tree_chol_stages(m)
|
|
123
|
+
return {"L_Q": "tree" if st else "dense", "L_H": "tree" if st and st["newton"] else "dense"}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def factor_product(L, form):
|
|
127
|
+
"""The matrix of factors L (..., n, n) (tri_unpack) of form factor_forms(): L L' (dense) or L' L (tree)."""
|
|
128
|
+
Lt = np.swapaxes(L, -1, -2)
|
|
129
|
+
return L @ Lt if form == "dense" else Lt @ L
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def decode(arr, m, max_contacts=None, terrain=False, max_rows=None, motor=False):
|
|
133
|
+
"""Records (..., REC_WORDS) float32 -> dict of arrays (leading shape kept): ncon, nefc, nlim, niter, flags (and
|
|
134
|
+
unsupported / refact / nonconv / singular / verify_diff), min_nu, clamp (u64 dof mask) and clamp_dof (bool, nv),
|
|
135
|
+
zone (bool, the row capacity), pair / slot (int, maxcon; pair -1 past ncon), qpos, qvel, qacc, qacc_adv, L_H, L_Q
|
|
136
|
+
(packed); terrain: a terrain build's record, with elem (the contact's terrain element); max_contacts, max_rows: the
|
|
137
|
+
build's capacities (None: the defaults); motor: a motor-limit build's record, with mslope (-df/dqdot per dof)."""
|
|
138
|
+
a = np.ascontiguousarray(arr, np.float32)
|
|
139
|
+
nw = rec_words(m, max_contacts, terrain, max_rows, motor)
|
|
140
|
+
assert a.shape[-1] == nw, (a.shape, nw)
|
|
141
|
+
u = a.view(np.uint32)
|
|
142
|
+
lay = layout(m, max_contacts, terrain, max_rows, motor)
|
|
143
|
+
nefc = step.nefc(max_rows)
|
|
144
|
+
sl = lambda name: slice(lay[name][0], lay[name][0] + lay[name][1])
|
|
145
|
+
hdr, flags = u[..., lay["hdr"][0]].astype(np.int64), u[..., lay["flags"][0]].astype(np.int64)
|
|
146
|
+
out = dict(ncon=hdr & 255, nefc=(hdr >> 8) & 255, nlim=(hdr >> 16) & 255, niter=hdr >> 24, flags=flags,
|
|
147
|
+
unsupported=flags & FLAG_UNSUPPORTED, refact=(flags & FLAG_REFACT) != 0,
|
|
148
|
+
nonconv=(flags & FLAG_NONCONV) != 0, singular=(flags & FLAG_SINGULAR) != 0,
|
|
149
|
+
verify_diff=(flags & FLAG_VERIFY_DIFF) != 0, min_nu=a[..., lay["min_nu"][0]])
|
|
150
|
+
if nefc > 255:
|
|
151
|
+
out["nefc"] = u[..., lay["reserved"][0]].astype(np.int64)
|
|
152
|
+
cw = u[..., sl("clamp")].astype(np.uint64)
|
|
153
|
+
out["clamp"] = sum(cw[..., k] << np.uint64(32 * k) for k in range(cw.shape[-1]))
|
|
154
|
+
out["clamp_dof"] = ((cw[..., :, None] >> np.arange(32, dtype=np.uint64)) & np.uint64(1)).astype(bool).reshape(
|
|
155
|
+
cw.shape[:-1] + (-1,))[..., :m.nv]
|
|
156
|
+
zw = u[..., sl("zone")].astype(np.uint64)
|
|
157
|
+
out["zone"] = ((zw[..., :, None] >> np.arange(32, dtype=np.uint64)) & np.uint64(1)).astype(bool).reshape(
|
|
158
|
+
zw.shape[:-1] + (-1,))[..., :nefc]
|
|
159
|
+
nc = max_contacts or step.maxcon(m)
|
|
160
|
+
if _wide(m, terrain):
|
|
161
|
+
e = u[..., sl("con")].astype(np.int64)
|
|
162
|
+
pb = 16
|
|
163
|
+
else:
|
|
164
|
+
e = np.ascontiguousarray(u[..., sl("con")]).view(np.uint16)[..., :nc].astype(np.int64)
|
|
165
|
+
pb = 10 if terrain else 9
|
|
166
|
+
past = np.arange(nc) >= out["ncon"][..., None]
|
|
167
|
+
out["pair"], out["slot"] = np.where(past, -1, e & ((1 << pb) - 1)), np.where(past, -1, e >> pb)
|
|
168
|
+
if terrain:
|
|
169
|
+
x = np.ascontiguousarray(u[..., sl("telem")]).view(np.uint16)[..., :nc].astype(np.int64)
|
|
170
|
+
out["elem"] = np.where(past, -1, x)
|
|
171
|
+
for name in ("qpos", "qvel", "qacc", "qacc_adv", "L_H", "L_Q") + (("mslope",) if motor else ()):
|
|
172
|
+
out[name] = a[..., sl(name)]
|
|
173
|
+
return out
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
"""Per-world physics parameters (nablaengine.params.PhysicsParams) in the G1 engine's text: apply() edits the engine
|
|
2
|
+
(adjoint.cuda_source), the host kernels (host.KERNEL) and the kinematics (kinematics.KIN_DEVICE) of a build with
|
|
3
|
+
parameters; a build without them is unchanged."""
|
|
4
|
+
from nablaengine.g1_engine import model_hooks, source
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def header(m, params, pw_off):
|
|
8
|
+
"""#defines of a build with parameters (prepended to the engine's text)."""
|
|
9
|
+
lay = params.layout(m.nv)
|
|
10
|
+
off = lambda f: lay[f][0] if f in lay else -1
|
|
11
|
+
return (f"#define NPARAM {params.width(m.nv)} // per-world parameters (nablaengine.params: {', '.join(lay)})\n"
|
|
12
|
+
f"#define PW_OFF {pw_off} // their offset in a world's com row\n"
|
|
13
|
+
f"#define COM_STRIDE (PW_OFF + NPARAM) // floats per world of the com input\n"
|
|
14
|
+
f"#define PW_SOLREF {off('foot_solref')}\n#define PW_SOLIMP {off('foot_solimp')}\n"
|
|
15
|
+
f"#define PW_DAMP {off('dof_damping')}\n#define PW_ARM {off('dof_armature')}\n"
|
|
16
|
+
+ (f"#define PW_TMASS {off('torso_mass')}\n#define PW_TINERT {off('torso_inertia')}\n"
|
|
17
|
+
if "torso_mass" in lay or "torso_inertia" in lay else "")
|
|
18
|
+
+ (f"#define PW_TORS {off('foot_torsional')}\n" if "foot_torsional" in lay else ""))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
STRIDE = (
|
|
22
|
+
("com[w * 3 + lane]", "com[(size_t)w * COM_STRIDE + lane]"),
|
|
23
|
+
("com[(size_t)w * 3 + lane]", "com[(size_t)w * COM_STRIDE + lane]"),
|
|
24
|
+
("com[(size_t)w * COM_WORDS + lane]", "com[(size_t)w * COM_STRIDE + lane]"),
|
|
25
|
+
("com + (size_t)w * COM_WORDS + 3", "com + (size_t)w * COM_STRIDE + 3"),
|
|
26
|
+
)
|
|
27
|
+
LOAD = (" if (lane < 3) s.com[lane] = com[(size_t)w * COM_STRIDE + lane];\n",
|
|
28
|
+
" if (lane < 3) s.com[lane] = com[(size_t)w * COM_STRIDE + lane];\n"
|
|
29
|
+
" for (int i = lane; i < NPARAM; i += 32) s.pw[i] = com[(size_t)w * COM_STRIDE + PW_OFF + i]; // (world_params)\n"
|
|
30
|
+
" if (lane == 0) s.dampw = s.pw + (PW_DAMP >= 0 ? PW_DAMP : 0);\n")
|
|
31
|
+
STATE = (
|
|
32
|
+
(" float com[3], fric;\n",
|
|
33
|
+
" float com[3], fric;\n float pw[NPARAM]; // the world's parameters (world_params)\n const float* dampw;\n", 3),
|
|
34
|
+
(" float *qpos, *qvel; // the kernel's outputs (implicitfast only)\n",
|
|
35
|
+
" float *qpos, *qvel; // the kernel's outputs (implicitfast only)\n const float* dampw; // in Hand (world_params)\n",
|
|
36
|
+
1),
|
|
37
|
+
("struct Hand {\n float M[NTRI], qsm[NV], qacc0[NV];\n",
|
|
38
|
+
"struct Hand {\n float M[NTRI], qsm[NV], qacc0[NV];\n float dampw[NV]; // the world's damping (world_params)\n", 1),
|
|
39
|
+
)
|
|
40
|
+
SPLIT = (
|
|
41
|
+
(" for (int i = lane; i < NV; i += 32) { g.qsm[i] = s.qsm[i]; g.qacc0[i] = s.qacc0[i]; }\n",
|
|
42
|
+
" for (int i = lane; i < NV; i += 32) { g.qsm[i] = s.qsm[i]; g.qacc0[i] = s.qacc0[i]; g.dampw[i] = s.dampw[i]; }\n",
|
|
43
|
+
1),
|
|
44
|
+
(" s.qpos = q; s.qvel = v; s.qsm = g.qsm;", " s.qpos = q; s.qvel = v; s.qsm = g.qsm; s.dampw = g.dampw;", 1),
|
|
45
|
+
)
|
|
46
|
+
FOOT = (
|
|
47
|
+
(" pos = s.con_dist[c]; sref = PSOLREF(pr); simp = PSOLIMP(pr);\n",
|
|
48
|
+
" pos = s.con_dist[c]; sref = PSOLREF(pr); simp = PSOLIMP(pr);\n"
|
|
49
|
+
" if (PFOOT(pr)) { // the world's foot-pair impedance (world_params)\n"
|
|
50
|
+
" if (PW_SOLREF >= 0) sref = s.pw + (PW_SOLREF >= 0 ? PW_SOLREF : 0);\n"
|
|
51
|
+
" if (PW_SOLIMP >= 0) {\n"
|
|
52
|
+
" for (int k = 0; k < 4; k++) fsi[k] = s.pw[(PW_SOLIMP >= 0 ? PW_SOLIMP : 0) + k];\n"
|
|
53
|
+
" fsi[4] = PSOLIMP(pr)[4];\n"
|
|
54
|
+
" simp = fsi;\n"
|
|
55
|
+
" }\n"
|
|
56
|
+
" }\n", 1),
|
|
57
|
+
(" const float *sref, *simp;\n float iw, pos = 0.f, mu = 0.f;\n",
|
|
58
|
+
" const float *sref, *simp;\n float iw, pos = 0.f, mu = 0.f, fsi[5];\n", 1),
|
|
59
|
+
(" adj_row_impedance(PSOLREF(pair), PSOLIMP(pair), d, contact_invw(pair, mu), ri);\n",
|
|
60
|
+
" const float *sref = PSOLREF(pair), *simp = PSOLIMP(pair);\n"
|
|
61
|
+
" float fsi[5];\n"
|
|
62
|
+
" if (PFOOT(pair)) { // the world's foot-pair impedance (world_params)\n"
|
|
63
|
+
" if (PW_SOLREF >= 0) sref = s.pw + (PW_SOLREF >= 0 ? PW_SOLREF : 0);\n"
|
|
64
|
+
" if (PW_SOLIMP >= 0) {\n"
|
|
65
|
+
" for (int k = 0; k < 4; k++) fsi[k] = s.pw[(PW_SOLIMP >= 0 ? PW_SOLIMP : 0) + k];\n"
|
|
66
|
+
" fsi[4] = PSOLIMP(pair)[4];\n"
|
|
67
|
+
" simp = fsi;\n"
|
|
68
|
+
" }\n"
|
|
69
|
+
" }\n"
|
|
70
|
+
" adj_row_impedance(sref, simp, d, contact_invw(pair, mu), ri);\n", 1),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
LOAD_ADJ = (LOAD[0], LOAD[1] + " for (int i = lane; i <= NPARAM; i += 32) s.gpw[i] = 0.f; // (world_params)\n")
|
|
75
|
+
ADJ = (
|
|
76
|
+
(" unsigned clamp[(NV + 31) / 32]; // the record's actuator clamp mask (dof bits)\n",
|
|
77
|
+
" float gpw[NPARAM + 1]; // the parameters' cotangents and the foot friction's, summed over the substeps (world_params)\n"
|
|
78
|
+
" unsigned clamp[(NV + 31) / 32]; // the record's actuator clamp mask (dof bits)\n", 1),
|
|
79
|
+
("__device__ void adj_compose(Adj& s, int lane) {\n",
|
|
80
|
+
"""__device__ void adj_compose(Adj& s, int lane) {
|
|
81
|
+
{ // the parameters' cotangents of this substep (world_params)
|
|
82
|
+
const float h = c_misc[0];
|
|
83
|
+
for (int i = lane; i < NV; i += 32) {
|
|
84
|
+
const float y = -s.ny[i], aadv = s.a[i] - s.at[i];
|
|
85
|
+
(void)y; (void)aadv; (void)h;
|
|
86
|
+
if (PW_DAMP >= 0) s.gpw[(PW_DAMP >= 0 ? PW_DAMP : 0) + i] += -s.v[i] * s.lam[i] - h * y * aadv;
|
|
87
|
+
if (PW_ARM >= 0) s.gpw[(PW_ARM >= 0 ? PW_ARM : 0) + i] += y * s.at[i] - s.a[i] * s.lam[i];
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
""", 1),
|
|
91
|
+
(" for (int i = lane; i < NV - 6; i += 32) gctrl[(size_t)w * (NV - 6) + i] = s.ubar[i];",
|
|
92
|
+
" for (int i = lane; i < NV - 6; i += 32) gctrl[(size_t)w * (NV - 5 + NPARAM) + i] = s.ubar[i]; // (world_params)\n"
|
|
93
|
+
" __syncwarp();\n"
|
|
94
|
+
" for (int i = lane; i <= NPARAM; i += 32) gctrl[(size_t)w * (NV - 5 + NPARAM) + NV - 6 + i] = s.gpw[i];", 1),
|
|
95
|
+
)
|
|
96
|
+
PARTIALS_DEVICE = r"""
|
|
97
|
+
// world_params: d Psi / d theta of one foot contact's quadratic rows, theta = (time constant, damping ratio, dmin, dmax,
|
|
98
|
+
// width, midpoint, mu) into pp[7] (added); the rows and their terms as contact_psi_vjp's dist cotangent
|
|
99
|
+
__device__ __noinline__ void contact_param_vjp(const float* Vv, const float* Va, const float* Vl, const float* fr,
|
|
100
|
+
float mu, int dim, unsigned zone, float d, float D, float k, float b,
|
|
101
|
+
float imp, float invw, const float* solref, const float* solimp,
|
|
102
|
+
float* pp) {
|
|
103
|
+
float vf[3], af[3], lf[3];
|
|
104
|
+
for (int j = 0; j < 3; j++) { vf[j] = dot3(fr + 3 * j, Vv); af[j] = dot3(fr + 3 * j, Va); lf[j] = dot3(fr + 3 * j, Vl); }
|
|
105
|
+
const float h = c_misc[0], tc = fmaxf(solref[0], RMUL(2.f, h)), dr = solref[1];
|
|
106
|
+
const float dmin = fminf(fmaxf(solimp[0], 1e-4f), 0.9999f), dmax = fminf(fmaxf(solimp[1], 1e-4f), 0.9999f);
|
|
107
|
+
const float width = fmaxf(1e-15f, solimp[2]), mid = fminf(fmaxf(solimp[3], 1e-4f), 0.9999f);
|
|
108
|
+
#ifdef ADJ_SOLIMP_POWER
|
|
109
|
+
const float power = ADJ_SOLIMP_POWER;
|
|
110
|
+
#else
|
|
111
|
+
const float power = fmaxf(1.f, solimp[4]);
|
|
112
|
+
#endif
|
|
113
|
+
const float fmin_ = solimp[0] > 1e-4f && solimp[0] < 0.9999f ? 1.f : 0.f; // dmin / dmax / mid not clamped
|
|
114
|
+
const float fmax_ = solimp[1] > 1e-4f && solimp[1] < 0.9999f ? 1.f : 0.f;
|
|
115
|
+
const float fmid = solimp[3] > 1e-4f && solimp[3] < 0.9999f ? 1.f : 0.f;
|
|
116
|
+
float dk[6] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f}, db[6] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f}, di[6] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
|
|
117
|
+
// the standard form k = 1 / (dmax tc dr)^2, b = 2 / (dmax tc) (tc above its 2 h floor); the direct form, each entry on
|
|
118
|
+
// its own as MuJoCo Warp's _contact_kbimp: solref[0] <= 0: k = -solref[0] / dmax^2, solref[1] <= 0: b = -solref[1] / dmax
|
|
119
|
+
const bool kdir = solref[0] <= 0.f, bdir = solref[1] <= 0.f;
|
|
120
|
+
if (kdir) dk[0] = -1.f / fmaxf(1e-15f, dmax * dmax);
|
|
121
|
+
else {
|
|
122
|
+
if (solref[0] > RMUL(2.f, h)) dk[0] = -2.f * k / tc;
|
|
123
|
+
dk[1] = -2.f * k / dr;
|
|
124
|
+
}
|
|
125
|
+
if (bdir) db[1] = -1.f / fmaxf(1e-15f, dmax);
|
|
126
|
+
else if (solref[0] > RMUL(2.f, h)) db[0] = -b / tc;
|
|
127
|
+
dk[3] = -2.f * k / dmax * fmax_; db[3] = -b / dmax * fmax_;
|
|
128
|
+
const float x = fabsf(d) / width;
|
|
129
|
+
if (dmin == dmax || solimp[2] <= 1e-15f) { di[2] = 0.5f * fmin_; di[3] = 0.5f * fmax_; }
|
|
130
|
+
else if (x <= 0.f) di[2] = fmin_;
|
|
131
|
+
else if (x >= 1.f) di[3] = fmax_;
|
|
132
|
+
else if (power == 1.f) { di[2] = (1.f - x) * fmin_; di[3] = x * fmax_; di[4] = -(dmax - dmin) * x / width; }
|
|
133
|
+
else {
|
|
134
|
+
const bool lo = x <= mid;
|
|
135
|
+
const float raw = imp_raw(x, dmin, dmax, mid, power, lo);
|
|
136
|
+
if (raw <= dmin) di[2] = fmin_;
|
|
137
|
+
else if (raw >= dmax) di[3] = fmax_;
|
|
138
|
+
else {
|
|
139
|
+
const float yv = (raw - dmin) / (dmax - dmin), y_ = lo ? x : 1.f - x, ym = lo ? mid : 1.f - mid;
|
|
140
|
+
const float dydx = power * powf(y_, power - 1.f) / powf(ym, power - 1.f);
|
|
141
|
+
const float dydm = -(power - 1.f) * powf(y_, power) / powf(ym, power) * (lo ? 1.f : 1.f);
|
|
142
|
+
di[2] = (1.f - yv) * fmin_; di[3] = yv * fmax_;
|
|
143
|
+
di[4] = (dmax - dmin) * dydx * (-x / width);
|
|
144
|
+
di[5] = (dmax - dmin) * dydm * fmid;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const float om = 1.f - imp, R = invw * om / imp;
|
|
148
|
+
const float dDdi = R > 1e-15f ? 1.f / (invw * om * om) : 0.f;
|
|
149
|
+
const float dDdmu = (R > 1e-15f && dim == 3) ? -D * (2.f / mu + 2.f * mu / (1.f + mu * mu)) : 0.f;
|
|
150
|
+
for (int e = 0; e < 4; e++) {
|
|
151
|
+
if (!((zone >> e) & 1u) || (e > 0 && dim != 3)) continue;
|
|
152
|
+
const int t = 1 + (e >> 1);
|
|
153
|
+
const float se = dim == 3 ? ((e & 1) ? -1.f : 1.f) : 0.f, sm = se * mu;
|
|
154
|
+
const float uv = vf[0] + sm * vf[t], ua = af[0] + sm * af[t], ul = lf[0] + sm * lf[t];
|
|
155
|
+
const float xe = ua + k * imp * d + b * uv;
|
|
156
|
+
for (int q = 0; q < 6; q++) pp[q] += ul * (dDdi * di[q] * xe + D * (d * (dk[q] * imp + k * di[q]) + db[q] * uv));
|
|
157
|
+
pp[6] += dDdmu * xe * ul + D * se * ((af[t] + b * vf[t]) * ul + xe * lf[t]);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
"""
|
|
161
|
+
PARTIALS = (
|
|
162
|
+
("__device__ __forceinline__ float adj_contact_one(Adj& s, int c, int pair, int slot, unsigned zone, float* cs,\n"
|
|
163
|
+
" float* dbg) {",
|
|
164
|
+
PARTIALS_DEVICE + "__device__ __forceinline__ float adj_contact_one(Adj& s, int c, int pair, int slot, unsigned zone,"
|
|
165
|
+
" float* cs,\n float* dbg, float* pp) {", 1),
|
|
166
|
+
(" contact_psi_vjp(Vv, Va, Vl, fr, mu, dim, zone, d, D, dD, k, b, imp, dimp, Wv, Wa, Wl, cot, cot + 4);\n",
|
|
167
|
+
" contact_psi_vjp(Vv, Va, Vl, fr, mu, dim, zone, d, D, dD, k, b, imp, dimp, Wv, Wa, Wl, cot, cot + 4);\n"
|
|
168
|
+
" if (PFOOT(pair) && zone) // the foot pair's parameters (world_params)\n"
|
|
169
|
+
" contact_param_vjp(Vv, Va, Vl, fr, mu, dim, zone, d, D, k, b, imp, contact_invw(pair, mu), sref, simp, pp);\n", 1),
|
|
170
|
+
(" float cw[CS_N]; // the lane's contact (adj_contact_one), read by the body lanes by shuffles\n",
|
|
171
|
+
" float cw[CS_N]; // the lane's contact (adj_contact_one), read by the body lanes by shuffles\n"
|
|
172
|
+
" float pp[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; // its foot-pair parameter terms (world_params)\n", 1),
|
|
173
|
+
(" bad = !(adj_contact_one(s, c, pair, slot, zone, cw, dbg) < 0.f);\n",
|
|
174
|
+
" bad = !(adj_contact_one(s, c, pair, slot, zone, cw, dbg, pp) < 0.f);\n", 1),
|
|
175
|
+
(" const unsigned skip = __ballot_sync(0xffffffffu, on && !use), mis = __ballot_sync(0xffffffffu, bad);\n",
|
|
176
|
+
" for (int q = 0; q < 7; q++) { // the batch's foot-pair terms, summed in a fixed order (world_params)\n"
|
|
177
|
+
" const float v = -warp_sum(pp[q]); // (Psi's derivatives are the adjoint's P: the gradient is -P)\n"
|
|
178
|
+
" if (lane == 0) {\n"
|
|
179
|
+
" if (q < 2 && PW_SOLREF >= 0) s.gpw[(PW_SOLREF >= 0 ? PW_SOLREF : 0) + q] += v;\n"
|
|
180
|
+
" else if (q >= 2 && q < 6 && PW_SOLIMP >= 0) s.gpw[(PW_SOLIMP >= 0 ? PW_SOLIMP : 0) + q - 2] += v;\n"
|
|
181
|
+
" else if (q == 6) s.gpw[NPARAM] += v;\n"
|
|
182
|
+
" }\n"
|
|
183
|
+
" }\n"
|
|
184
|
+
" const unsigned skip = __ballot_sync(0xffffffffu, on && !use), mis = __ballot_sync(0xffffffffu, bad);\n", 1),
|
|
185
|
+
)
|
|
186
|
+
PARTIALS4_DEVICE = (PARTIALS_DEVICE
|
|
187
|
+
.replace("__device__ __noinline__ void contact_param_vjp(", "__device__ __noinline__ void contact_param_vjp4(")
|
|
188
|
+
.replace(" float* pp) {",
|
|
189
|
+
" float* pp, const float* Ov, const float* Oa,\n"
|
|
190
|
+
" const float* Ol, float mus) {")
|
|
191
|
+
.replace("(R > 1e-15f && dim == 3)", "(R > 1e-15f && dim >= 3)")
|
|
192
|
+
.replace("if (!((zone >> e) & 1u) || (e > 0 && dim != 3)) continue;",
|
|
193
|
+
"if (!((zone >> e) & 1u) || (e > 0 && dim < 3)) continue;")
|
|
194
|
+
.replace("const float se = dim == 3 ? ((e & 1) ? -1.f : 1.f) : 0.f, sm = se * mu;",
|
|
195
|
+
"const float se = dim >= 3 ? ((e & 1) ? -1.f : 1.f) : 0.f, sm = se * mu;")
|
|
196
|
+
.replace(""" pp[6] += dDdmu * xe * ul + D * se * ((af[t] + b * vf[t]) * ul + xe * lf[t]);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
""", """ pp[6] += dDdmu * xe * ul + D * se * ((af[t] + b * vf[t]) * ul + xe * lf[t]);
|
|
200
|
+
}
|
|
201
|
+
if (dim == 4) { // the spin rows (condim 4): D and the impedance as the pyramid rows', u = n +- mus r
|
|
202
|
+
const float wv = dot3(fr, Ov), wa = dot3(fr, Oa), wl = dot3(fr, Ol);
|
|
203
|
+
for (int e = 4; e < 6; e++) {
|
|
204
|
+
if (!((zone >> e) & 1u)) continue;
|
|
205
|
+
const float se = (e & 1) ? -1.f : 1.f, sm = se * mus;
|
|
206
|
+
const float uv = vf[0] + sm * wv, ua = af[0] + sm * wa, ul = lf[0] + sm * wl;
|
|
207
|
+
const float xe = ua + k * imp * d + b * uv;
|
|
208
|
+
for (int q = 0; q < 6; q++) pp[q] += ul * (dDdi * di[q] * xe + D * (d * (dk[q] * imp + k * di[q]) + db[q] * uv));
|
|
209
|
+
pp[6] += dDdmu * xe * ul;
|
|
210
|
+
pp[7] += D * se * ((wa + b * wv) * ul + xe * wl);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
"""))
|
|
215
|
+
assert PARTIALS4_DEVICE.count("contact_param_vjp4(") == 1 and PARTIALS4_DEVICE.count("pp[7] +=") == 1
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def partials4(tors):
|
|
219
|
+
"""PARTIALS for a condim-4 model (pp[8]; tors: foot_torsional, the foot pairs' mus from the world's parameters)."""
|
|
220
|
+
mus = "(PFOOT(pair) ? s.pw[PW_TORS >= 0 ? PW_TORS : 0] : PMUS(pair))" if tors else "PMUS(pair)"
|
|
221
|
+
call = (" contact_psi_vjp4(Vv, Va, Vl, fr, mu, dim, zone, d, D, dD, k, b, imp, dimp, Wv, Wa, Wl, cot, cot + 4, Ov, Oa,"
|
|
222
|
+
" Ol, dim == 4 ? PMUS(pair) : 0.f, AWv, AWa, AWl);\n")
|
|
223
|
+
return (
|
|
224
|
+
(PARTIALS[0][0], PARTIALS[0][1].replace(PARTIALS_DEVICE, PARTIALS4_DEVICE), 1),
|
|
225
|
+
(call, call.replace("PMUS(pair)", mus)
|
|
226
|
+
+ " if (PFOOT(pair) && zone) // the foot pair's parameters (world_params)\n"
|
|
227
|
+
" contact_param_vjp4(Vv, Va, Vl, fr, mu, dim, zone, d, D, k, b, imp, contact_invw(pair, mu), sref, simp, pp,"
|
|
228
|
+
f" Ov, Oa, Ol, dim == 4 ? {mus} : 0.f);\n", 1),
|
|
229
|
+
(PARTIALS[2][0], PARTIALS[2][1].replace("float pp[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};",
|
|
230
|
+
"float pp[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};"), 1),
|
|
231
|
+
PARTIALS[3],
|
|
232
|
+
(PARTIALS[4][0], PARTIALS[4][1].replace("for (int q = 0; q < 7; q++)", "for (int q = 0; q < 8; q++)")
|
|
233
|
+
.replace(" else if (q == 6) s.gpw[NPARAM] += v;\n",
|
|
234
|
+
" else if (q == 6) s.gpw[NPARAM] += v;\n"
|
|
235
|
+
+ (" else if (q == 7) s.gpw[PW_TORS >= 0 ? PW_TORS : 0] += v; // (foot_torsional)\n"
|
|
236
|
+
if tors else "")), 1),
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
TORS_ENGINE = (
|
|
241
|
+
("con_frame[MAXCON][9], con_mu[MAXCON];", "con_frame[MAXCON][9], con_mu[MAXCON], con_mus[MAXCON];", 1),
|
|
242
|
+
(" float con_mu[MAXCON];\n", " float con_mu[MAXCON];\n float con_mus[MAXCON]; // (world_params: foot_torsional)\n", 2),
|
|
243
|
+
(" const float *qsm, *qacc0, *con_mu, *efc_aref; // in Hand", " const float *qsm, *qacc0, *con_mu, *con_mus, *efc_aref; // in Hand", 1),
|
|
244
|
+
(" s.con_mu[c] = PFOOT(pair) ? s.fric : PMU(pair);\n",
|
|
245
|
+
" s.con_mu[c] = PFOOT(pair) ? s.fric : PMU(pair);\n"
|
|
246
|
+
" s.con_mus[c] = PFOOT(pair) ? fmaxf(s.pw[PW_TORS >= 0 ? PW_TORS : 0], 1e-5f) : PMUS(pair); // (foot_torsional)\n", 1),
|
|
247
|
+
)
|
|
248
|
+
TORS_HOST = (
|
|
249
|
+
("g.con_mu[c] = s.con_mu[c];", "g.con_mu[c] = s.con_mu[c]; g.con_mus[c] = s.con_mus[c];", 1),
|
|
250
|
+
("s.con_mu = g.con_mu;", "s.con_mu = g.con_mu; s.con_mus = g.con_mus;", 1),
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
ARMATURE = (
|
|
255
|
+
(" s.M[TRI(j, j)] = dot3(sw, n) + dot3(sv, f) + c_armature[j];",
|
|
256
|
+
" s.M[TRI(j, j)] = dot3(sw, n) + dot3(sv, f) + s.pw[(PW_ARM >= 0 ? PW_ARM : 0) + j]; // (world_params)", 1),
|
|
257
|
+
(" s.M[TRI(j, i)] = dot3(kw, n) + dot3(kv, f) + (i == j ? c_armature[j] : 0.f);",
|
|
258
|
+
" s.M[TRI(j, i)] = dot3(kw, n) + dot3(kv, f) + (i == j ? s.pw[(PW_ARM >= 0 ? PW_ARM : 0) + j] : 0.f);", 1),
|
|
259
|
+
("float r = s.did[i] + c_armature[i] * s.a[i]", "float r = s.did[i] + s.pw[(PW_ARM >= 0 ? PW_ARM : 0) + i] * s.a[i]",
|
|
260
|
+
1),
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
TORSO_DEVICE = r"""
|
|
265
|
+
// the torso's mass (k 0) and principal moments (k 1..3) of a world (pw: its parameters), the model's without the field
|
|
266
|
+
__device__ __forceinline__ float torso_param(const float* pw, int k) {
|
|
267
|
+
const int b = (int)c_misc[1];
|
|
268
|
+
if (k == 0) return PW_TMASS >= 0 ? pw[PW_TMASS >= 0 ? PW_TMASS : 0] : c_mass[b];
|
|
269
|
+
return PW_TINERT >= 0 ? pw[(PW_TINERT >= 0 ? PW_TINERT : 0) + k - 1] : c_inert[3 * b + k - 1];
|
|
270
|
+
}
|
|
271
|
+
"""
|
|
272
|
+
BODY_IPOS = (
|
|
273
|
+
r"""__device__ __forceinline__ void body_ipos(int b, const float* com, float* out) {
|
|
274
|
+
for (int k = 0; k < 3; k++) out[k] = c_ipos[3 * b + k] + (b == (int)c_misc[1] ? com[k] : 0.f);
|
|
275
|
+
}
|
|
276
|
+
""",
|
|
277
|
+
r"""__device__ __forceinline__ void body_ipos(int b, const float* com, float* out) { // (world_params: out[7], com[7])
|
|
278
|
+
for (int k = 0; k < 3; k++) out[k] = c_ipos[3 * b + k] + (b == (int)c_misc[1] ? com[k] : 0.f);
|
|
279
|
+
out[3] = b == (int)c_misc[1] ? com[3] : c_mass[b]; // mass
|
|
280
|
+
for (int k = 0; k < 3; k++) out[4 + k] = b == (int)c_misc[1] ? com[4 + k] : c_inert[3 * b + k]; // principal moments
|
|
281
|
+
}
|
|
282
|
+
""" + TORSO_DEVICE, 1)
|
|
283
|
+
TORSO_LOAD = (" if (lane < 3) s.com[lane] = com[(size_t)w * COM_STRIDE + lane];\n",
|
|
284
|
+
" if (lane < 3) s.com[lane] = com[(size_t)w * COM_STRIDE + lane];\n"
|
|
285
|
+
" if (lane < 4) s.com[3 + lane] = torso_param(com + (size_t)w * COM_STRIDE + PW_OFF, lane); // (world_params)\n")
|
|
286
|
+
TORSO_VJP = r"""// d psi_b / d theta of the torso's mass and principal moments (world_params): F1 = m f1, N1 = I AL + W x I W + c x F1,
|
|
287
|
+
// F2 = m f2, N2 = I AL2 + c x F2, f1 = A + AL x c + W x (W x c), f2 = A2 + AL2 x c, I = sum_k d_k r_k r_k' (r_k: the
|
|
288
|
+
// inertia frame's axes); psi_b = F1.Vl + N1.Wl + F2.Vy + N2.Wy
|
|
289
|
+
__device__ void torso_param_vjp(int b, const float* Q, const float* ipos, const float* W, const float* AL, const float* A,
|
|
290
|
+
const float* AL2, const float* A2, const float* Wl, const float* Vl, const float* Wy,
|
|
291
|
+
const float* Vy, float* dm, float* dI) {
|
|
292
|
+
float c[3], t[3], wc[3], wwc[3], f1[3], f2[3], u[3], qi[4];
|
|
293
|
+
qrot(Q, ipos, c);
|
|
294
|
+
cross(W, c, wc);
|
|
295
|
+
cross(W, wc, wwc);
|
|
296
|
+
cross(AL, c, t);
|
|
297
|
+
for (int k = 0; k < 3; k++) f1[k] = A[k] + t[k] + wwc[k];
|
|
298
|
+
cross(AL2, c, t);
|
|
299
|
+
for (int k = 0; k < 3; k++) f2[k] = A2[k] + t[k];
|
|
300
|
+
*dm = dot3(f1, Vl) + dot3(f2, Vy);
|
|
301
|
+
cross(c, f1, u);
|
|
302
|
+
*dm += dot3(u, Wl);
|
|
303
|
+
cross(c, f2, u);
|
|
304
|
+
*dm += dot3(u, Wy);
|
|
305
|
+
qmul(Q, c_iquat + 4 * b, qi);
|
|
306
|
+
for (int k = 0; k < 3; k++) {
|
|
307
|
+
float e[3] = {0.f, 0.f, 0.f}, r[3], wr[3];
|
|
308
|
+
e[k] = 1.f;
|
|
309
|
+
qrot(qi, e, r);
|
|
310
|
+
cross(W, r, wr);
|
|
311
|
+
dI[k] = dot3(r, AL) * dot3(r, Wl) + dot3(r, W) * dot3(wr, Wl) + dot3(r, AL2) * dot3(r, Wy);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
"""
|
|
316
|
+
TORSO_GRAD = r""" if (b == (int)c_misc[1] && (PW_TMASS >= 0 || PW_TINERT >= 0)) { // the torso's parameters: -d psi (world_params)
|
|
317
|
+
float dm, dI[3];
|
|
318
|
+
torso_param_vjp(b, s.Q[b], ip, s.W[b], s.AL[b], s.A[b], s.AL2[b], s.A2[b], s.Wl[b], s.Vl[b], s.Wy[b], s.Vy[b],
|
|
319
|
+
&dm, dI);
|
|
320
|
+
if (PW_TMASS >= 0) s.gpw[PW_TMASS >= 0 ? PW_TMASS : 0] -= dm;
|
|
321
|
+
if (PW_TINERT >= 0) for (int k = 0; k < 3; k++) s.gpw[(PW_TINERT >= 0 ? PW_TINERT : 0) + k] -= dI[k];
|
|
322
|
+
}
|
|
323
|
+
"""
|
|
324
|
+
CALL_TAIL = (" s.bW[b], s.bAL[b], s.bA[b], s.bAL2[b], s.bA2[b], s.bWl[b], s.bVl[b], s.bWy[b], s.bVy[b],"
|
|
325
|
+
" s.tb[b]);\n")
|
|
326
|
+
TORSO_ENGINE = (
|
|
327
|
+
(" float com[3], fric;\n", " float com[7], fric; // (world_params: the COM offset, the torso's mass and moments)\n", 3),
|
|
328
|
+
BODY_IPOS,
|
|
329
|
+
(" float m = c_mass[b];\n for (int k = 0; k < 3; k++) F[k] = m * (A[k] + u[k] + u2[k]);",
|
|
330
|
+
" float m = ipos[3]; // (world_params)\n for (int k = 0; k < 3; k++) F[k] = m * (A[k] + u[k] + u2[k]);", 1),
|
|
331
|
+
(" for (int k = 0; k < 3; k++) l[k] *= c_inert[3 * b + k];\n", " for (int k = 0; k < 3; k++) l[k] *= ipos[4 + k];\n", 2),
|
|
332
|
+
(" const float* I = c_inert + 3 * b;\n", " const float* I = ipos + 4; // (world_params)\n", 1),
|
|
333
|
+
(" float m = c_mass[b], cc = dot3(c, c);\n", " float m = ipos[3], cc = dot3(c, c);\n", 1),
|
|
334
|
+
(" const float* d = c_inert + 3 * b;\n const float m = c_mass[b];\n",
|
|
335
|
+
" const float* d = ipos + 4; // (world_params)\n const float m = ipos[3];\n", 1),
|
|
336
|
+
("__device__ void body_local_vjp(", TORSO_VJP + "__device__ void body_local_vjp(", 1),
|
|
337
|
+
(CALL_TAIL, CALL_TAIL + TORSO_GRAD, 1),
|
|
338
|
+
)
|
|
339
|
+
TORSO_KIN = (
|
|
340
|
+
(" float qpos[NQ], qvel[NV], com[3];\n", " float qpos[NQ], qvel[NV], com[7]; // (world_params)\n", 2),
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _torso(src, part):
|
|
345
|
+
if "float ip[3]" not in src:
|
|
346
|
+
raise RuntimeError("world_params: no ip[3] for the torso fields")
|
|
347
|
+
src = src.replace("float ip[3]", "float ip[7]")
|
|
348
|
+
if part == "engine":
|
|
349
|
+
src = _apply(src, TORSO_ENGINE)
|
|
350
|
+
else:
|
|
351
|
+
src = _apply(src, TORSO_KIN)
|
|
352
|
+
for a in (" Mb = c_mass[b];\n", " const float Mb = c_mass[b];\n", " const float m = c_mass[b];\n"):
|
|
353
|
+
src = src.replace(a, a.replace("c_mass[b]", "ip[3]"))
|
|
354
|
+
if "c_mass[" in src:
|
|
355
|
+
raise RuntimeError("world_params: the kinematics read c_mass outside the torso edits")
|
|
356
|
+
if src.count(TORSO_LOAD[0]) < 1:
|
|
357
|
+
raise RuntimeError("world_params: no com load for the torso fields")
|
|
358
|
+
return src.replace(*TORSO_LOAD)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
DIRECT_SOLREF = (
|
|
362
|
+
(" *k = 1.f / fmaxf(1e-15f, RMUL(RMUL(RMUL(RMUL(RMUL(dmax, dmax), tc), tc), dr), dr));\n"
|
|
363
|
+
" *b = 2.f / fmaxf(1e-15f, RMUL(dmax, tc));\n",
|
|
364
|
+
" *k = solref[0] <= 0.f ? -solref[0] / fmaxf(1e-15f, RMUL(dmax, dmax)) // direct form (world_params: foot_solref)\n"
|
|
365
|
+
" : 1.f / fmaxf(1e-15f, RMUL(RMUL(RMUL(RMUL(RMUL(dmax, dmax), tc), tc), dr), dr));\n"
|
|
366
|
+
" *b = solref[1] <= 0.f ? -solref[1] / fmaxf(1e-15f, dmax) : 2.f / fmaxf(1e-15f, RMUL(dmax, tc));\n", 1),
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _apply(src, hooks):
|
|
371
|
+
for a, b, n in hooks:
|
|
372
|
+
if src.count(a) != n:
|
|
373
|
+
raise RuntimeError(f"world_params anchor found {src.count(a)} times, expected {n}: {a[:70]!r}")
|
|
374
|
+
src = src.replace(a, b)
|
|
375
|
+
return src
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
COMPOSE_MOTOR = "__device__ void adj_compose(Adj& s, int lane, const float* rec) {\n"
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def plain_compose(src, edit):
|
|
382
|
+
"""edit(src) with motor_hooks' adj_compose signature (the record added: a build with motor limits) taken as the
|
|
383
|
+
plain one that ADJ's anchor names, and put back afterwards; without motor limits edit(src)."""
|
|
384
|
+
plain = ADJ[1][0]
|
|
385
|
+
if COMPOSE_MOTOR not in src:
|
|
386
|
+
return edit(src)
|
|
387
|
+
if src.count(COMPOSE_MOTOR) != 1 or plain in src:
|
|
388
|
+
raise RuntimeError("world_params: adj_compose's signature found more than once")
|
|
389
|
+
out = edit(src.replace(COMPOSE_MOTOR, plain))
|
|
390
|
+
if out.count(plain) != 1:
|
|
391
|
+
raise RuntimeError(f"world_params: adj_compose's signature found {out.count(plain)} times after the edits")
|
|
392
|
+
return out.replace(plain, COMPOSE_MOTOR)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def apply(src, m, params, part, pw_off=3):
|
|
396
|
+
"""apply_params(src, m, params, part, pw_off), also on a build with motor limits (plain_compose)."""
|
|
397
|
+
if not params:
|
|
398
|
+
return src
|
|
399
|
+
return plain_compose(src, lambda s: apply_params(s, m, params, part, pw_off))
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def apply_params(src, m, params, part, pw_off=3):
|
|
403
|
+
"""src with the edits of a build with parameters params (unchanged without); part: "engine" (adjoint.cuda_source,
|
|
404
|
+
after model_hooks), "host" (host.KERNEL) or "kinematics" (kinematics.KIN_DEVICE). pw_off: the parameters' offset in
|
|
405
|
+
a com row (3, or a terrain-object build's com words)."""
|
|
406
|
+
if not params:
|
|
407
|
+
return src
|
|
408
|
+
if int(m.opt.cone) == 1:
|
|
409
|
+
raise ValueError("per-world physics parameters with the elliptic friction cone: not supported yet")
|
|
410
|
+
for a, b in STRIDE:
|
|
411
|
+
src = src.replace(a, b)
|
|
412
|
+
torso = "torso_mass" in params.fields or "torso_inertia" in params.fields
|
|
413
|
+
if part == "kinematics":
|
|
414
|
+
return _torso(src, part) if torso else src
|
|
415
|
+
n = 1 if part == "engine" else 2
|
|
416
|
+
if src.count(LOAD[0]) != n:
|
|
417
|
+
raise RuntimeError(f"world_params: com loads found {src.count(LOAD[0])} times, expected {n}")
|
|
418
|
+
src = src.replace(*(LOAD_ADJ if part == "engine" else LOAD))
|
|
419
|
+
from nablaengine.g1_engine import condim4
|
|
420
|
+
c4, tors = condim4.applies(m), "foot_torsional" in params.fields
|
|
421
|
+
if tors and not c4:
|
|
422
|
+
raise ValueError("PhysicsParams foot_torsional: the model has no condim-4 pairs")
|
|
423
|
+
if part == "host":
|
|
424
|
+
src = _apply(src, SPLIT + (TORS_HOST if tors else ()))
|
|
425
|
+
return src.replace(*TORSO_LOAD) if torso else src
|
|
426
|
+
src = header(m, params, pw_off) + _apply(src, STATE + ADJ + FOOT + (partials4(tors) if c4 else PARTIALS))
|
|
427
|
+
if tors:
|
|
428
|
+
src = _apply(src, TORS_ENGINE)
|
|
429
|
+
for a, b in (("PMUS(s.con_pair[a])", "s.con_mus[a]"), ("PMUS(s.con_pair[c])", "s.con_mus[c]")):
|
|
430
|
+
if a not in src:
|
|
431
|
+
raise RuntimeError(f"world_params: {a} not found (foot_torsional)")
|
|
432
|
+
src = src.replace(a, b)
|
|
433
|
+
if "foot_solref" in params.fields:
|
|
434
|
+
src = _apply(src, DIRECT_SOLREF)
|
|
435
|
+
if "dof_damping" in params.fields:
|
|
436
|
+
if source.has_damping(m):
|
|
437
|
+
if src.count("c_damp[i]") != 6:
|
|
438
|
+
raise RuntimeError(f"world_params: c_damp[i] found {src.count('c_damp[i]')} times, expected 6")
|
|
439
|
+
src = src.replace("c_damp[i]", "s.dampw[i]")
|
|
440
|
+
else:
|
|
441
|
+
src = _apply(src, tuple((a, b.replace("c_damp[i]", "s.dampw[i]"), k)
|
|
442
|
+
for a, b, k in model_hooks.ENGINE_DAMPING[1:]))
|
|
443
|
+
if "dof_armature" in params.fields:
|
|
444
|
+
src = _apply(src, ARMATURE)
|
|
445
|
+
if torso:
|
|
446
|
+
src = _torso(src, part)
|
|
447
|
+
return src
|