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.
Files changed (136) hide show
  1. nablaengine/__init__.py +4 -0
  2. nablaengine/_fixtures/README.md +19 -0
  3. nablaengine/_fixtures/data/mf_s0.npz +0 -0
  4. nablaengine/_fixtures/mjlab/LICENSE +27 -0
  5. nablaengine/_fixtures/mjlab/README.md +113 -0
  6. nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
  7. nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
  8. nablaengine/_optional.py +30 -0
  9. nablaengine/_paths.py +38 -0
  10. nablaengine/actuators/__init__.py +169 -0
  11. nablaengine/actuators/bam.py +306 -0
  12. nablaengine/actuators/bam_params/LICENSE +202 -0
  13. nablaengine/actuators/bam_params/xl330/m6.json +19 -0
  14. nablaengine/boxbox.py +259 -0
  15. nablaengine/ccd.py +1122 -0
  16. nablaengine/checks.py +376 -0
  17. nablaengine/cuda.py +483 -0
  18. nablaengine/dist_query.py +628 -0
  19. nablaengine/dual.py +223 -0
  20. nablaengine/dyn_query.py +685 -0
  21. nablaengine/engines.py +114 -0
  22. nablaengine/envs/__init__.py +24 -0
  23. nablaengine/envs/brax.py +165 -0
  24. nablaengine/envs/convert.py +771 -0
  25. nablaengine/envs/dmc.py +523 -0
  26. nablaengine/envs/env.py +233 -0
  27. nablaengine/envs/kin.py +371 -0
  28. nablaengine/envs/ops.py +134 -0
  29. nablaengine/envs/rewards.py +57 -0
  30. nablaengine/fixtures.py +243 -0
  31. nablaengine/forest_engine/__init__.py +0 -0
  32. nablaengine/forest_engine/adjoint.py +1726 -0
  33. nablaengine/forest_engine/adjoint_contact.py +493 -0
  34. nablaengine/forest_engine/bam_hooks.py +248 -0
  35. nablaengine/forest_engine/body_params.py +1007 -0
  36. nablaengine/forest_engine/capacity_diag.py +116 -0
  37. nablaengine/forest_engine/ccd_coop.py +250 -0
  38. nablaengine/forest_engine/chol_blk.py +80 -0
  39. nablaengine/forest_engine/contact_forces.py +142 -0
  40. nablaengine/forest_engine/contact_vjp.py +462 -0
  41. nablaengine/forest_engine/convex.py +1331 -0
  42. nablaengine/forest_engine/cylinder.py +73 -0
  43. nablaengine/forest_engine/dist_device.py +923 -0
  44. nablaengine/forest_engine/dyn_device.py +696 -0
  45. nablaengine/forest_engine/ellipsoid.py +179 -0
  46. nablaengine/forest_engine/elliptic.py +272 -0
  47. nablaengine/forest_engine/equality.py +842 -0
  48. nablaengine/forest_engine/floss.py +148 -0
  49. nablaengine/forest_engine/foot_offset.py +368 -0
  50. nablaengine/forest_engine/free_gyro.py +288 -0
  51. nablaengine/forest_engine/host.py +530 -0
  52. nablaengine/forest_engine/kdof64.py +127 -0
  53. nablaengine/forest_engine/kinematics.py +320 -0
  54. nablaengine/forest_engine/margin.py +167 -0
  55. nablaengine/forest_engine/margin_convex.py +326 -0
  56. nablaengine/forest_engine/midphase.py +439 -0
  57. nablaengine/forest_engine/model_hooks.py +913 -0
  58. nablaengine/forest_engine/motor_hooks.py +50 -0
  59. nablaengine/forest_engine/muscle.py +485 -0
  60. nablaengine/forest_engine/nb128.py +118 -0
  61. nablaengine/forest_engine/nb64.py +163 -0
  62. nablaengine/forest_engine/noslip.py +1124 -0
  63. nablaengine/forest_engine/nv128.py +1944 -0
  64. nablaengine/forest_engine/object_size.py +283 -0
  65. nablaengine/forest_engine/replay_guard.py +40 -0
  66. nablaengine/forest_engine/root_spread.py +126 -0
  67. nablaengine/forest_engine/solref.py +74 -0
  68. nablaengine/forest_engine/source.py +1464 -0
  69. nablaengine/forest_engine/sparse_pattern.py +527 -0
  70. nablaengine/forest_engine/spatial.py +1045 -0
  71. nablaengine/forest_engine/step.py +3083 -0
  72. nablaengine/forest_engine/surrogate.py +498 -0
  73. nablaengine/forest_engine/tape.py +199 -0
  74. nablaengine/forest_engine/tendon.py +845 -0
  75. nablaengine/forest_engine/terrain.py +1059 -0
  76. nablaengine/forest_engine/world_forces.py +166 -0
  77. nablaengine/forest_engine/world_params.py +230 -0
  78. nablaengine/g1_engine/__init__.py +0 -0
  79. nablaengine/g1_engine/adjoint.py +1661 -0
  80. nablaengine/g1_engine/adjoint_contact.py +577 -0
  81. nablaengine/g1_engine/bam_hooks.py +596 -0
  82. nablaengine/g1_engine/condim4.py +245 -0
  83. nablaengine/g1_engine/contact_forces.py +500 -0
  84. nablaengine/g1_engine/cylccd.py +1158 -0
  85. nablaengine/g1_engine/cylinder.py +216 -0
  86. nablaengine/g1_engine/elliptic.py +565 -0
  87. nablaengine/g1_engine/exact_replay.py +61 -0
  88. nablaengine/g1_engine/host.py +358 -0
  89. nablaengine/g1_engine/kinematics.py +320 -0
  90. nablaengine/g1_engine/mesh.py +305 -0
  91. nablaengine/g1_engine/mesh_tables.py +79 -0
  92. nablaengine/g1_engine/model_hooks.py +919 -0
  93. nablaengine/g1_engine/motor_hooks.py +70 -0
  94. nablaengine/g1_engine/replay_guard.py +55 -0
  95. nablaengine/g1_engine/source.py +1107 -0
  96. nablaengine/g1_engine/sphbox.py +93 -0
  97. nablaengine/g1_engine/step.py +3716 -0
  98. nablaengine/g1_engine/tape.py +173 -0
  99. nablaengine/g1_engine/world_params.py +447 -0
  100. nablaengine/identity.py +401 -0
  101. nablaengine/jax_ffi.py +2536 -0
  102. nablaengine/model/__init__.py +1 -0
  103. nablaengine/model/capability.py +694 -0
  104. nablaengine/model/fields.py +317 -0
  105. nablaengine/model/gravcomp.py +64 -0
  106. nablaengine/model/invweight.py +145 -0
  107. nablaengine/motor.py +143 -0
  108. nablaengine/object_geometry.py +609 -0
  109. nablaengine/params.py +258 -0
  110. nablaengine/provenance.py +196 -0
  111. nablaengine/reference/__init__.py +0 -0
  112. nablaengine/reference/adjoint_groups.py +226 -0
  113. nablaengine/reference/jax64.py +690 -0
  114. nablaengine/reference/warp_physics.py +262 -0
  115. nablaengine/sensors/__init__.py +4 -0
  116. nablaengine/sensors/cameras.py +285 -0
  117. nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
  118. nablaengine/sensors/data/livox_mid360.npz +0 -0
  119. nablaengine/sensors/g1.py +521 -0
  120. nablaengine/sensors/jax_rays.py +364 -0
  121. nablaengine/sensors/optix_rays.py +725 -0
  122. nablaengine/sensors/raycore.py +630 -0
  123. nablaengine/sensors/raygrad.py +374 -0
  124. nablaengine/sensors/raygrad_cuda.py +191 -0
  125. nablaengine/sensors/robot_mesh.py +273 -0
  126. nablaengine/sensors/torch_rays.py +275 -0
  127. nablaengine/terrain.py +424 -0
  128. nablaengine/torch_ffi.py +1328 -0
  129. nablaengine/workdir.py +37 -0
  130. nablaengine-1.0.2.dist-info/METADATA +236 -0
  131. nablaengine-1.0.2.dist-info/RECORD +136 -0
  132. nablaengine-1.0.2.dist-info/WHEEL +5 -0
  133. nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
  134. nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
  135. nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
  136. nablaengine-1.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,628 @@
1
+ """Distance queries of the forest engine: signed distances, closest points and normals between chosen geom or body
2
+ pairs, batched over worlds on the GPU, with the VJP with respect to qpos, from JAX and PyTorch."""
3
+ import ctypes
4
+ import os
5
+ import threading
6
+
7
+ import numpy as np
8
+
9
+ QUERY_TYPES = ("plane", "sphere", "capsule", "box", "mesh", "cylinder", "ellipsoid")
10
+ MAX_SLOTS = 128
11
+ TERRAIN = "@terrain"
12
+ TERRAIN_GEOM = -1
13
+ FACE_PX, FACE_NX, FACE_PY, FACE_NY, FACE_PZ, FACE_NZ = range(6)
14
+ UNIT_NAME = "dist_query.cu"
15
+ PREFIX = "dist"
16
+
17
+ UNIT = r"""
18
+ #include <cuda_runtime.h>
19
+ namespace {
20
+ @ENGINE@
21
+ } // namespace
22
+ extern "C" int @PFX@_upload(const float* p, cudaStream_t st) {
23
+ @LOAD_CONSTS@
24
+ return (int)cudaGetLastError();
25
+ }
26
+ extern "C" int @PFX@_query(cudaStream_t st, int nw, const float* qpos, const float* com, float dmax, float* dist,
27
+ float* pts, float* nrm, int* far, int* face) {
28
+ if (nw > 0) k_dst_query<<<(nw + DST_WPB - 1) / DST_WPB, 32 * DST_WPB, 0, st>>>(nw, qpos, com, dmax, dist, pts, nrm, far,
29
+ face);
30
+ return (int)cudaGetLastError();
31
+ }
32
+ extern "C" int @PFX@_query_vjp(cudaStream_t st, int nw, const float* qpos, const float* com, float dmax,
33
+ const float* gd, const float* gp, float* gq) {
34
+ if (nw > 0) k_dst_query_vjp<<<(nw + DST_WPB - 1) / DST_WPB, 32 * DST_WPB, 0, st>>>(nw, qpos, com, dmax, gd, gp, gq);
35
+ return (int)cudaGetLastError();
36
+ }
37
+ extern "C" void @PFX@_sizes(long long* o) {
38
+ o[0] = (long long)sizeof(DstS); o[1] = NQ; o[2] = NV; o[3] = DST_NS; o[4] = COM_WORDS;
39
+ }
40
+ """
41
+
42
+ FFI = r"""
43
+ #include <cuda_runtime.h>
44
+ #include <climits>
45
+ #include <cstdint>
46
+ #include <cmath>
47
+ #include <mutex>
48
+ #include <string>
49
+ #include <vector>
50
+ #include "xla/ffi/api/ffi.h"
51
+ namespace ffi = xla::ffi;
52
+ @DEFINES@
53
+ typedef int (*UploadFn)(const float*, cudaStream_t);
54
+ typedef int (*QueryFn)(cudaStream_t, int, const float*, const float*, float, float*, float*, float*, int*, int*);
55
+ typedef int (*QueryVjpFn)(cudaStream_t, int, const float*, const float*, float, const float*, const float*, float*);
56
+ @DECLS@
57
+ static std::vector<float> g_consts;
58
+ static std::mutex g_mu;
59
+ static bool g_ready[64];
60
+ extern "C" int dst_set_constants(const float* p, long long n) {
61
+ std::lock_guard<std::mutex> lock(g_mu);
62
+ if (n != NCONST) return 1;
63
+ g_consts.assign(p, p + n);
64
+ for (int d = 0; d < 64; d++) g_ready[d] = false;
65
+ return 0;
66
+ }
67
+ static ffi::Error cuda_error(cudaError_t e, const char* what) {
68
+ if (e == cudaSuccess) return ffi::Error::Success();
69
+ return ffi::Error::Internal(std::string("nablaengine.dist_query: ") + what + ": " + cudaGetErrorString(e));
70
+ }
71
+ static ffi::Error bad(const std::string& m) { return ffi::Error::InvalidArgument("nablaengine.dist_query: " + m); }
72
+ static ffi::Error ensure_ready(cudaStream_t st) {
73
+ int dev = -1;
74
+ cudaError_t e = cudaGetDevice(&dev);
75
+ if (e != cudaSuccess) return cuda_error(e, "cudaGetDevice");
76
+ std::lock_guard<std::mutex> lock(g_mu);
77
+ if (dev < 0 || dev >= 64) return ffi::Error::Internal("nablaengine.dist_query: device ordinal out of range");
78
+ if (g_ready[dev]) return ffi::Error::Success();
79
+ if ((long long)g_consts.size() != NCONST) return ffi::Error::Internal("nablaengine.dist_query: no constants (dist_query.init)");
80
+ for (int v = 0; v < NVAR; v++) {
81
+ int rc = kUpload[v](g_consts.data(), st);
82
+ if (rc) return cuda_error((cudaError_t)rc, "constant upload");
83
+ }
84
+ e = cudaStreamSynchronize(st);
85
+ if (e != cudaSuccess) return cuda_error(e, "constant upload (synchronize)");
86
+ g_ready[dev] = true;
87
+ return ffi::Error::Success();
88
+ }
89
+ template <class B> static bool dims_are(const B& b, std::initializer_list<int64_t> want) {
90
+ auto d = b.dimensions();
91
+ if (d.size() != want.size()) return false;
92
+ size_t i = 0;
93
+ for (int64_t n : want)
94
+ if (d[i++] != n) return false;
95
+ return true;
96
+ }
97
+ typedef ffi::Buffer<ffi::F32> BufF;
98
+ typedef ffi::Result<ffi::Buffer<ffi::F32>> RetF;
99
+ typedef ffi::Result<ffi::Buffer<ffi::S32>> RetI;
100
+ static ffi::Error query_impl(cudaStream_t st, BufF qpos, BufF com, float dmax, RetF dist, RetF pts, RetF nrm, RetI far,
101
+ RetI face) {
102
+ auto d = qpos.dimensions();
103
+ if (d.size() != 2 || d[1] != NQ) return bad("qpos must be (B, nq) float32");
104
+ const int64_t B = d[0];
105
+ if (B > INT_MAX) return bad("B too large");
106
+ if (!dims_are(com, {B, COMW})) return bad("com must be (B, com_words) float32");
107
+ if (!dims_are(*dist, {B, NS}) || !dims_are(*pts, {B, NS, 2, 3}) || !dims_are(*nrm, {B, NS, 3}) || !dims_are(*far, {B, NS})
108
+ || !dims_are(*face, {B, NS, 2}))
109
+ return bad("outputs: dist (B, S), points (B, S, 2, 3), normal (B, S, 3), far (B, S), face (B, S, 2)");
110
+ if (B == 0) return ffi::Error::Success();
111
+ ffi::Error r = ensure_ready(st);
112
+ if (r.failure()) return r;
113
+ int rc = kQuery(st, (int)B, qpos.typed_data(), com.typed_data(), dmax, dist->typed_data(), pts->typed_data(),
114
+ nrm->typed_data(), far->typed_data(), face->typed_data());
115
+ return rc ? cuda_error((cudaError_t)rc, "k_dst_query launch") : ffi::Error::Success();
116
+ }
117
+ static ffi::Error query_vjp_impl(cudaStream_t st, BufF qpos, BufF com, BufF gd, BufF gp, float dmax, RetF gq) {
118
+ auto d = qpos.dimensions();
119
+ if (d.size() != 2 || d[1] != NQ) return bad("qpos must be (B, nq) float32");
120
+ const int64_t B = d[0];
121
+ if (B > INT_MAX) return bad("B too large");
122
+ if (!dims_are(com, {B, COMW}) || !dims_are(gd, {B, NS}) || !dims_are(gp, {B, NS, 2, 3}) || !dims_are(*gq, {B, NQ}))
123
+ return bad("shapes: com (B, com_words), g_dist (B, S), g_points (B, S, 2, 3), out (B, nq)");
124
+ if (B == 0) return ffi::Error::Success();
125
+ ffi::Error r = ensure_ready(st);
126
+ if (r.failure()) return r;
127
+ int rc = kQueryVjp(st, (int)B, qpos.typed_data(), com.typed_data(), dmax, gd.typed_data(), gp.typed_data(),
128
+ gq->typed_data());
129
+ return rc ? cuda_error((cudaError_t)rc, "k_dst_query_vjp launch") : ffi::Error::Success();
130
+ }
131
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(DstQuery, query_impl,
132
+ ffi::Ffi::Bind().Ctx<ffi::PlatformStream<cudaStream_t>>().Arg<BufF>().Arg<BufF>()
133
+ .Attr<float>("dmax").Ret<BufF>().Ret<BufF>().Ret<BufF>().Ret<ffi::Buffer<ffi::S32>>()
134
+ .Ret<ffi::Buffer<ffi::S32>>());
135
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(DstQueryVjp, query_vjp_impl,
136
+ ffi::Ffi::Bind().Ctx<ffi::PlatformStream<cudaStream_t>>().Arg<BufF>().Arg<BufF>()
137
+ .Arg<BufF>().Arg<BufF>().Attr<float>("dmax").Ret<BufF>());
138
+ """
139
+
140
+ TERRAIN_UNIT = r"""extern "C" int @PFX@_set_terrain(int dev, const void* p) {
141
+ int old = 0;
142
+ cudaGetDevice(&old);
143
+ cudaError_t e = cudaSetDevice(dev);
144
+ if (e == cudaSuccess) e = cudaMemcpyToSymbol(g_ter, p, sizeof(TerrainPtrs));
145
+ cudaSetDevice(old);
146
+ return (int)e;
147
+ }
148
+ """
149
+
150
+ FFI_TERRAIN = (("!dims_are(*face, {B, NS, 2})", "!dims_are(*face, {B, NS, 4})"),
151
+ ("face (B, S, 2)\");", "face (B, S, 4)\");"))
152
+
153
+
154
+ def _collision_geoms_of(m, b, who="nablaengine.dist_query"):
155
+ import mujoco
156
+ from nablaengine.forest_engine import step
157
+ cg = set(step.collision_geoms(m))
158
+ gs = [g for g in range(m.ngeom) if int(m.geom_bodyid[g]) == b and g in cg]
159
+ if not gs:
160
+ gs = [g for g in range(m.ngeom) if int(m.geom_bodyid[g]) == b
161
+ and int(m.geom_type[g]) in (int(mujoco.mjtGeom.mjGEOM_SPHERE), int(mujoco.mjtGeom.mjGEOM_CAPSULE),
162
+ int(mujoco.mjtGeom.mjGEOM_BOX), int(mujoco.mjtGeom.mjGEOM_MESH),
163
+ int(mujoco.mjtGeom.mjGEOM_CYLINDER), int(mujoco.mjtGeom.mjGEOM_ELLIPSOID))]
164
+ if not gs:
165
+ raise ValueError(f"{who}: body {m.body(b).name!r} has no geom to query")
166
+ return gs
167
+
168
+
169
+ def resolve(m, pairs, who="nablaengine.dist_query"):
170
+ """(slots: per pair a list of model geom id pairs, labels) of the query pairs (TERRAIN as the second name, or
171
+ TERRAIN_GEOM as the second geom id: the terrain of a terrain build). A body's geoms are its collision geoms (the
172
+ engine's), or, if it has none, its geoms of the supported solid types."""
173
+ import mujoco
174
+ slots, labels = [], []
175
+ for p in pairs:
176
+ if len(p) == 2:
177
+ g1, g2 = int(p[0]), int(p[1])
178
+ slots.append([(g1, g2)])
179
+ labels.append(f"geom:{m.geom(g1).name}|{TERRAIN if g2 == TERRAIN_GEOM else m.geom(g2).name}")
180
+ continue
181
+ kind, a, b = p
182
+ if a == TERRAIN:
183
+ raise ValueError(f"{who}: the terrain is the second geom of a pair: {p}")
184
+ if kind == "geom":
185
+ ids = [mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_GEOM, x) if x != TERRAIN else TERRAIN_GEOM for x in (a, b)]
186
+ if ids[0] < 0 or (ids[1] < 0 and b != TERRAIN):
187
+ raise ValueError(f"{who}: unknown geom in {p}")
188
+ slots.append([tuple(ids)])
189
+ elif kind == "body":
190
+ ids = [mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, x) if x != TERRAIN else TERRAIN_GEOM for x in (a, b)]
191
+ if ids[0] < 0 or (ids[1] < 0 and b != TERRAIN):
192
+ raise ValueError(f"{who}: unknown body in {p}")
193
+ g2s = [TERRAIN_GEOM] if b == TERRAIN else _collision_geoms_of(m, ids[1], who)
194
+ slots.append([(g1, g2) for g1 in _collision_geoms_of(m, ids[0], who) for g2 in g2s])
195
+ else:
196
+ raise ValueError(f"{who}: a pair is ('geom' | 'body', name1, name2) or (geom1, geom2): {p}")
197
+ labels.append(f"{kind}:{a}|{b}")
198
+ if not slots or len(slots) > MAX_SLOTS:
199
+ raise ValueError(f"{who}: 1 .. {MAX_SLOTS} query pairs")
200
+ return slots, labels
201
+
202
+
203
+ def check_terrain_params(terrain, params, who="nablaengine.dist_query"):
204
+ """ValueError for a terrain build with per-world parameters (not supported by the query libraries, as the
205
+ engine's object_size against the terrain)."""
206
+ from nablaengine.params import as_params
207
+ if terrain is not None and as_params(params):
208
+ raise ValueError(f"{who}: per-world parameters (params=) with a terrain build (terrain=) are not supported")
209
+
210
+
211
+ def engine_text(m, foot_pairs, com_body, max_contacts=None, max_rows=None, terrain=None, params=None,
212
+ who="nablaengine.dist_query"):
213
+ """The forest engine's text a query library is built on and its inputs: a dict with m (the build's model:
214
+ object_size's bound model with that field), params, ter ((TerrainConfig, robot terrain geoms) or None), consts
215
+ (packed constants), load (the constant loader, asynchronous on stream st), engine (adjoint.cuda_source's text,
216
+ include removed), mc (the contact capacity), mr (the row capacity or None). terrain: a TerrainConfig; params:
217
+ per-world physics parameters (nablaengine.params). Not both (ValueError)."""
218
+ import re
219
+ from nablaengine.forest_engine import adjoint, host, object_size, world_params
220
+ from nablaengine import engines, jax_ffi
221
+ from nablaengine.params import as_params
222
+ if not engines.is_forest(m):
223
+ raise ValueError(f"{who}: the forest engine's models only (nablaengine.engines)")
224
+ params = as_params(params)
225
+ check_terrain_params(terrain, params, who)
226
+ if params:
227
+ world_params.check(m, params, foot_pairs, com_body)
228
+ if "sole_thickness" in params.fields or params.invweight0 != "model":
229
+ raise ValueError(f"{who}: PhysicsParams sole_thickness / invweight0='per_world' are not supported in this "
230
+ "build yet")
231
+ params = object_size.resolve(m, params, com_body)
232
+ m = object_size.bound_model(m, params)
233
+ ter = None
234
+ if terrain is not None:
235
+ from nablaengine import terrain as _terrain
236
+ if getattr(terrain, "terrain_sand", False):
237
+ raise ValueError(f"{who}: TerrainConfig.terrain_sand is not supported in this build")
238
+ ter = (terrain, _terrain.robot_terrain_geoms(m, foot_pairs, terrain.geoms))
239
+ consts, lays, sizes = adjoint.engine_constants(m, foot_pairs, com_body, **({"terrain": ter} if ter else {}))
240
+ load = host.loader(lays, sizes)
241
+ load = re.sub(r"cudaMemcpyToSymbol\(([^;]*)\);", r"cudaMemcpyToSymbolAsync(\1, 0, cudaMemcpyHostToDevice, st);", load)
242
+ mc_in, mr_in, mc, _ = jax_ffi.capacity(m, terrain, max_contacts, max_rows)
243
+ engine = adjoint.cuda_source(m, mc_in, ter, **({"max_rows": mr_in} if mr_in is not None else {}),
244
+ **({"params": params} if params else {}))
245
+ engine = engine.replace("#include <cuda_runtime.h>\n", "")
246
+ return dict(m=m, params=params, ter=ter, consts=consts, load=load, engine=engine, mc=mc, mr=mr_in)
247
+
248
+
249
+ def terrain_unit(prefix, ter):
250
+ """The unit's terrain upload entry <prefix>_set_terrain (jax_ffi.set_terrain / torch_ffi.set_terrain's pointers;
251
+ with TerrainConfig.terrain_material also the elements' materials, the 9th pointer)."""
252
+ tu = TERRAIN_UNIT.replace("@PFX@", prefix)
253
+ if getattr(ter[0], "terrain_material", False):
254
+ tu = tu.replace(" cudaSetDevice(old);\n", " if (e == cudaSuccess) e = cudaMemcpyToSymbol(g_tmat, "
255
+ "(const void* const*)p + 8, sizeof(const float*));\n cudaSetDevice(old);\n")
256
+ return tu
257
+
258
+
259
+ def com_words(m, ter, params):
260
+ """Floats per world of the com input of a build (the step's com row)."""
261
+ from nablaengine.forest_engine import step as fstep
262
+ comw = fstep.com_words(m) + (ter[0].com_words() - 3 if ter else 0)
263
+ return comw + (params.width(m.nv) if params else 0)
264
+
265
+
266
+ def library_sources(m, foot_pairs, com_body, slots, max_contacts=None, max_rows=None, ffi=True, terrain=None,
267
+ params=None):
268
+ """({unit: source}, packed constants, {unit: -D options}, query geom ids) of the query library. slots: resolve's.
269
+ terrain: the build's nablaengine.terrain.TerrainConfig (a terrain build: the engine's terrain text, the terrain
270
+ query geom, the unit's dist_set_terrain). params: per-world physics parameters (nablaengine.params; the com rows
271
+ as the engine library's; object_size also in the queries' geom, forest_engine.object_size.queries). Not both
272
+ (ValueError)."""
273
+ from nablaengine.forest_engine import dist_device, object_size
274
+ e = engine_text(m, foot_pairs, com_body, max_contacts, max_rows, terrain, params)
275
+ m, params, ter = e["m"], e["params"], e["ter"]
276
+ engine, geoms = dist_device.apply(e["engine"], m, slots, **({"terrain": True} if ter else {}))
277
+ engine = object_size.queries(engine, m, params, geoms)
278
+ unit = UNIT.replace("@PFX@", PREFIX).replace("@LOAD_CONSTS@", e["load"]).replace("@ENGINE@", engine)
279
+ if params:
280
+ assert unit.count("o[4] = COM_WORDS;") == 1
281
+ unit = unit.replace("o[4] = COM_WORDS;", "o[4] = COM_STRIDE;")
282
+ if ter:
283
+ unit += terrain_unit(PREFIX, ter)
284
+ units, defines = {UNIT_NAME: unit}, {UNIT_NAME: []}
285
+ if ffi:
286
+ defs = [f"#define {k} {val}" for k, val in (("NQ", m.nq), ("NV", m.nv), ("NS", len(slots)),
287
+ ("NCONST", len(e["consts"])),
288
+ ("COMW", com_words(m, ter, params)), ("NVAR", 1))]
289
+ decls = [f'extern "C" int {PREFIX}_upload(const float*, cudaStream_t);',
290
+ f'extern "C" int {PREFIX}_query(cudaStream_t, int, const float*, const float*, float, float*, float*, '
291
+ 'float*, int*, int*);',
292
+ f'extern "C" int {PREFIX}_query_vjp(cudaStream_t, int, const float*, const float*, float, '
293
+ 'const float*, const float*, float*);',
294
+ f"static const QueryFn kQuery = {PREFIX}_query;",
295
+ f"static const QueryVjpFn kQueryVjp = {PREFIX}_query_vjp;",
296
+ f"static const UploadFn kUpload[NVAR] = {{{PREFIX}_upload}};"]
297
+ ffi_text = FFI
298
+ if ter:
299
+ for a, b in FFI_TERRAIN:
300
+ assert ffi_text.count(a) == 1
301
+ ffi_text = ffi_text.replace(a, b)
302
+ units["dk_ffi.cu"] = ffi_text.replace("@DEFINES@", "\n".join(defs)).replace("@DECLS@", "\n".join(decls))
303
+ defines["dk_ffi.cu"] = []
304
+ return units, e["consts"], defines, geoms
305
+
306
+
307
+ def _build(m, foot_pairs, com_body, pairs, max_contacts, max_rows, ffi, arch, include, prefix, terrain=None,
308
+ params=None):
309
+ from nablaengine import cuda, jax_ffi
310
+ slots, labels = resolve(m, pairs)
311
+ units, consts, defines, geoms = library_sources(m, foot_pairs, com_body, slots, max_contacts, max_rows, ffi,
312
+ **({"terrain": terrain} if terrain else {}),
313
+ **({"params": params} if params else {}))
314
+ for n in units:
315
+ defines[n] = list(defines[n]) + cuda.forest_hold_defines(arch, units[n], defines[n])
316
+ flags = cuda.arch_flags(None, arch)
317
+ unit_arch = {n: flags for n in units} if flags != [f"-arch={arch}"] else None
318
+ path, built, key = jax_ffi._build(units, defines, arch, include, consts, unit_arch, prefix=prefix)
319
+ return dict(path=str(path), built=built, key=key, slots=slots, labels=labels, geoms=geoms, consts=consts,
320
+ nslot=len(slots))
321
+
322
+
323
+ def _check_sizes(lib, nq, nv, nslot, comw, who="nablaengine.dist_query"):
324
+ sz = np.zeros(5, np.int64)
325
+ fn = getattr(lib, f"{PREFIX}_sizes")
326
+ fn(ctypes.c_void_p(sz.ctypes.data))
327
+ if tuple(int(x) for x in sz[1:5]) != (nq, nv, nslot, comw):
328
+ raise RuntimeError(f"{who}: the library's sizes {sz.tolist()} do not match (nq, nv, S, com_words) = "
329
+ f"{(nq, nv, nslot, comw)}")
330
+
331
+
332
+ def _info(b, max_distance, einfo, terrain):
333
+ return dict(path=b["path"], key=b["key"], built=b["built"], labels=b["labels"],
334
+ slots=[[list(map(int, p)) for p in s] for s in b["slots"]], max_distance=float(max_distance),
335
+ engine=einfo, nslot=b["nslot"], terrain=terrain is not None, geoms=[int(g) for g in b["geoms"]])
336
+
337
+
338
+ def jax_terrain_hooks(lib, prefixes, who="nablaengine.dist_query"):
339
+ """Register the units' terrain upload (<prefix>_set_terrain) with jax_ffi.set_terrain and apply a terrain already
340
+ uploaded."""
341
+ import jax
342
+ from nablaengine import jax_ffi
343
+ fns = []
344
+ for t in prefixes:
345
+ f = getattr(lib, f"{t}_set_terrain")
346
+ f.argtypes = [ctypes.c_int, ctypes.c_void_p]
347
+ fns.append(f)
348
+ jax_ffi._STATE.setdefault("terrain_hooks", []).extend(fns)
349
+ devs = {d.id: d for d in jax.devices()}
350
+ for did, arrs in jax_ffi._TERRAIN.items():
351
+ ptrs = (ctypes.c_void_p * 8)(*[x.unsafe_buffer_pointer() for x in arrs])
352
+ for f in fns:
353
+ rc = f(int(devs[did].local_hardware_id), ctypes.cast(ptrs, ctypes.c_void_p))
354
+ if rc:
355
+ raise RuntimeError(f"{who}: the terrain upload failed ({rc})")
356
+
357
+
358
+ def torch_terrain_hooks(lib, prefixes, who="nablaengine.dist_query"):
359
+ """Register the units' terrain upload with torch_ffi.set_terrain and apply a terrain already uploaded."""
360
+ from nablaengine import torch_ffi
361
+ tf = []
362
+ for t in prefixes:
363
+ f = getattr(lib, f"{t}_set_terrain")
364
+ f.argtypes = [ctypes.c_int, ctypes.c_void_p]
365
+ tf.append(f)
366
+ torch_ffi._STATE["fns"]["set_terrain"] = list(torch_ffi._STATE["fns"]["set_terrain"]) + tf
367
+ order = ("boxes", "hf_head", "hf_int", "hf_data", "grid", "cell_start", "cell_items", "elem_cell")
368
+ for tdev, tens in torch_ffi._TERRAIN.items():
369
+ ptrs = (ctypes.c_void_p * 8)(*[tens[k].data_ptr() for k in order])
370
+ for f in tf:
371
+ if f(int(tdev), ctypes.cast(ptrs, ctypes.c_void_p)):
372
+ raise RuntimeError(f"{who}: the terrain upload failed")
373
+
374
+
375
+ _LOCK = threading.Lock()
376
+ _J = {}
377
+
378
+
379
+ def init(model, pairs, max_distance=1.0, *, foot_pairs=(), com_body=None, max_contacts=None, max_rows=None,
380
+ terrain=None, params=None):
381
+ """Initialise jax_ffi with the model (jax_ffi.init(model=model, foot_pairs=..., com_body=..., max_contacts=...,
382
+ max_rows=..., terrain=..., params=...)) and build / load the query library for the pairs (module docstring).
383
+ max_distance: the queries' cutoff (m; query takes another per call). terrain: a nablaengine.terrain.TerrainConfig
384
+ (a terrain build: pairs with TERRAIN; the terrain jax_ffi.set_terrain uploads, before or after init, reaches the
385
+ query library too). params: per-world physics parameters (nablaengine.params, as jax_ffi.init's: com is then
386
+ (B, com_words) with them; object_size applies to the queries). terrain and params: not both (ValueError). Returns
387
+ a dict (path, key, labels, slots: per pair its model geom id pairs, geoms, max_distance, nslot, engine: jax_ffi's
388
+ info). One query library per process."""
389
+ import jax
390
+ from nablaengine import jax_ffi
391
+ check_terrain_params(terrain, params)
392
+ with _LOCK:
393
+ if _J:
394
+ raise RuntimeError("nablaengine.dist_query: already initialised (one query library per process)")
395
+ einfo = jax_ffi.init(model=model, foot_pairs=list(foot_pairs), com_body=com_body, max_contacts=max_contacts,
396
+ max_rows=max_rows, **({"terrain": terrain} if terrain is not None else {}),
397
+ **({"params": params} if params else {}))
398
+ if einfo["engine"] != "forest":
399
+ raise ValueError("nablaengine.dist_query: the forest engine's models only")
400
+ if einfo.get("actuator"):
401
+ raise ValueError("nablaengine.dist_query: not with an actuator model yet")
402
+ m = jax_ffi._STATE["m"]
403
+ b = _build(m, einfo["foot_pairs"], einfo["com_body"], pairs, max_contacts, max_rows, True, einfo["arch"],
404
+ jax.ffi.include_dir(), "libdk_dist", terrain, params)
405
+ lib = ctypes.cdll.LoadLibrary(b["path"])
406
+ if terrain is not None:
407
+ jax_terrain_hooks(lib, [PREFIX])
408
+ lib.dst_set_constants.argtypes = [ctypes.c_void_p, ctypes.c_longlong]
409
+ c = np.ascontiguousarray(b["consts"], np.float32)
410
+ if lib.dst_set_constants(c.ctypes.data, len(c)):
411
+ raise RuntimeError("nablaengine.dist_query: dst_set_constants failed")
412
+ _check_sizes(lib, m.nq, m.nv, b["nslot"], int(einfo["com_words"]))
413
+ targets = {}
414
+ for kind, sym in (("query", "DstQuery"), ("query_vjp", "DstQueryVjp")):
415
+ targets[kind] = f"dist_{kind}_{b['key'][:8]}"
416
+ jax.ffi.register_ffi_target(targets[kind], jax.ffi.pycapsule(getattr(lib, sym)), platform="CUDA")
417
+ info = _info(b, max_distance, einfo, terrain)
418
+ _J.update(lib=lib, targets=targets, info=info, dmax=float(np.float32(max_distance)), m=m, qfn={})
419
+ return info
420
+
421
+
422
+ def _need():
423
+ if not _J:
424
+ raise RuntimeError("nablaengine.dist_query: call dist_query.init(model, pairs) first")
425
+ return _J
426
+
427
+
428
+ def jax_query_forward(J, qpos, com, max_distance=None):
429
+ """query_forward on the interface state J (a dict with targets["query"], info, dmax)."""
430
+ import jax
431
+ import jax.numpy as jnp
432
+ B, S = qpos.shape[0], J["info"]["nslot"]
433
+ dmax = np.float32(J["dmax"] if max_distance is None else max_distance)
434
+ f32 = jnp.float32
435
+ fw = 4 if J["info"].get("terrain") else 2
436
+ outs = [jax.ShapeDtypeStruct((B, S), f32), jax.ShapeDtypeStruct((B, S, 2, 3), f32),
437
+ jax.ShapeDtypeStruct((B, S, 3), f32), jax.ShapeDtypeStruct((B, S), jnp.int32),
438
+ jax.ShapeDtypeStruct((B, S, fw), jnp.int32)]
439
+ return tuple(jax.ffi.ffi_call(J["targets"]["query"], outs)(qpos, com, dmax=dmax))
440
+
441
+
442
+ def jax_query_backward(J, qpos, com, g_dist, g_points, max_distance=None):
443
+ """query_backward on the interface state J."""
444
+ import jax
445
+ import jax.numpy as jnp
446
+ dmax = np.float32(J["dmax"] if max_distance is None else max_distance)
447
+ out = jax.ShapeDtypeStruct(qpos.shape, jnp.float32)
448
+ return jax.ffi.ffi_call(J["targets"]["query_vjp"], out)(qpos, com, g_dist, g_points, dmax=dmax)
449
+
450
+
451
+ def query_outputs(r, faces, elements, who="nablaengine.dist_query"):
452
+ """(dist, points, normal, far) of a query's raw outputs, then face (faces=True) and element (elements=True)."""
453
+ if not (faces or elements):
454
+ return r[:4]
455
+ if elements and r[4].shape[-1] != 4:
456
+ raise ValueError(f"{who}: elements=True needs a terrain build (init(terrain=...))")
457
+ return r[:4] + ((r[4][..., :2],) if faces else ()) + ((r[4][..., 2:],) if elements else ())
458
+
459
+
460
+ def jax_query(J, cache, qpos, com, max_distance=None, faces=False, elements=False, who="nablaengine.dist_query"):
461
+ """query on the interface state J (cache: {max_distance: custom_vjp function})."""
462
+ import jax
463
+ import jax.numpy as jnp
464
+ dm = float(np.float32(J["dmax"] if max_distance is None else max_distance))
465
+ if dm not in cache:
466
+ @jax.custom_vjp
467
+ def f(q, c):
468
+ return jax_query_forward(J, q, c, dm)
469
+
470
+ def f_fwd(q, c):
471
+ return jax_query_forward(J, q, c, dm), (q, c)
472
+
473
+ def f_bwd(res, ct):
474
+ q, c = res
475
+ return jax_query_backward(J, q, c, ct[0], ct[1], dm), jnp.zeros_like(c)
476
+
477
+ f.defvjp(f_fwd, f_bwd)
478
+ cache[dm] = f
479
+ return query_outputs(cache[dm](qpos, com), faces, elements, who)
480
+
481
+
482
+ def query_forward(qpos, com, max_distance=None):
483
+ """(dist (B, S), points (B, S, 2, 3), normal (B, S, 3), far (B, S) int32, face (B, S, 2) int32; terrain builds
484
+ (B, S, 4): face, face, element, triangle) without custom_vjp. face: the box face (FACE_PX ... FACE_NZ) of geom 1
485
+ and of geom 2 at the closest points, -1 for other geoms."""
486
+ return jax_query_forward(_need(), qpos, com, max_distance)
487
+
488
+
489
+ def query_backward(qpos, com, g_dist, g_points, max_distance=None):
490
+ """The cotangent of qpos (B, nq, qpos form) for cotangents of dist and points."""
491
+ return jax_query_backward(_need(), qpos, com, g_dist, g_points, max_distance)
492
+
493
+
494
+ def query(qpos, com, max_distance=None, faces=False, elements=False):
495
+ """Differentiable queries (dist, points, normal, far), with faces=True also face (B, S, 2) int32, with
496
+ elements=True (terrain builds) then element (B, S, 2) int32 (module docstring): a jax.custom_vjp whose VJP gives
497
+ qpos's cotangent from dist's and points' (normal, far, face and element get none; com zeros). qpos (B, nq)
498
+ float32, com (B, com_words) float32 (info["engine"]["com_words"])."""
499
+ J = _need()
500
+ return jax_query(J, J["qfn"], qpos, com, max_distance, faces, elements)
501
+
502
+
503
+ _T = {}
504
+
505
+
506
+ def torch_init(model, pairs, max_distance=1.0, *, device=None, foot_pairs=(), com_body=None, max_contacts=None,
507
+ max_rows=None, terrain=None, params=None):
508
+ """torch_ffi.init(device, model=model, ...) and the query library for PyTorch (built where nvcc and mujoco are
509
+ available; ctypes entries on torch's current stream; no jax needed). Arguments as init(); returns its dict."""
510
+ import torch
511
+ from nablaengine import torch_ffi
512
+ check_terrain_params(terrain, params)
513
+ with _LOCK:
514
+ if _T:
515
+ raise RuntimeError("nablaengine.dist_query: torch_init already called (one query library per process)")
516
+ einfo = torch_ffi.init(device, model=model, foot_pairs=list(foot_pairs), com_body=com_body,
517
+ max_contacts=max_contacts, max_rows=max_rows,
518
+ **({"terrain": terrain} if terrain is not None else {}),
519
+ **({"params": params} if params else {}))
520
+ if einfo["engine"] != "forest":
521
+ raise ValueError("nablaengine.dist_query: the forest engine's models only")
522
+ if einfo.get("actuator"):
523
+ raise ValueError("nablaengine.dist_query: not with an actuator model yet")
524
+ dev = torch_ffi._device_index(device)
525
+ cc = torch.cuda.get_device_capability(dev)
526
+ arch = os.environ.get("DK_ARCH") or f"sm_{cc[0]}{cc[1]}"
527
+ b = _build(model, einfo["foot_pairs"], einfo["com_body"], pairs, max_contacts, max_rows, False, arch, None,
528
+ "libdk_dist_torch", terrain, params)
529
+ lib = ctypes.cdll.LoadLibrary(b["path"])
530
+ if terrain is not None:
531
+ torch_terrain_hooks(lib, [PREFIX])
532
+ vp, i32, f32 = ctypes.c_void_p, ctypes.c_int, ctypes.c_float
533
+ up = getattr(lib, f"{PREFIX}_upload")
534
+ up.argtypes = [vp, vp]
535
+ q = getattr(lib, f"{PREFIX}_query")
536
+ q.argtypes = [vp, i32, vp, vp, f32, vp, vp, vp, vp, vp]
537
+ qv = getattr(lib, f"{PREFIX}_query_vjp")
538
+ qv.argtypes = [vp, i32, vp, vp, f32, vp, vp, vp]
539
+ _check_sizes(lib, int(einfo["nq"]), int(einfo["nv"]), b["nslot"], int(einfo["com_words"]))
540
+ info = _info(b, max_distance, einfo, terrain)
541
+ _T.update(lib=lib, query=q, query_vjp=qv, upload=[up], consts=np.ascontiguousarray(b["consts"], np.float32),
542
+ ready=set(), info=info, dmax=float(np.float32(max_distance)))
543
+ return info
544
+
545
+
546
+ def torch_ready(T, t, who="nablaengine.dist_query"):
547
+ """The device index of tensor t with the interface state T's constants uploaded there (once per device)."""
548
+ import torch
549
+ if not T:
550
+ raise RuntimeError(f"{who}: call torch_init(model, pairs) first")
551
+ dev = t.device.index
552
+ if dev not in T["ready"]:
553
+ with torch.cuda.device(dev):
554
+ st = torch.cuda.current_stream(dev)
555
+ for f in T["upload"]:
556
+ rc = f(ctypes.c_void_p(T["consts"].ctypes.data), ctypes.c_void_p(st.cuda_stream))
557
+ if rc:
558
+ raise RuntimeError(f"{who}: constant upload failed ({rc})")
559
+ st.synchronize()
560
+ T["ready"].add(dev)
561
+ return dev
562
+
563
+
564
+ def _p(t):
565
+ return ctypes.c_void_p(t.data_ptr())
566
+
567
+
568
+ def torch_query_forward(T, qpos, com, dmax, who="nablaengine.dist_query"):
569
+ """(dist, points, normal, far, face) tensors of the interface state T's query entry (no autograd)."""
570
+ import torch
571
+ dev = torch_ready(T, qpos, who)
572
+ B, S = qpos.shape[0], T["info"]["nslot"]
573
+ kw = dict(dtype=torch.float32, device=qpos.device)
574
+ dist, pts, nrm = torch.empty((B, S), **kw), torch.empty((B, S, 2, 3), **kw), torch.empty((B, S, 3), **kw)
575
+ far = torch.empty((B, S), dtype=torch.int32, device=qpos.device)
576
+ face = torch.empty((B, S, 4 if T["info"].get("terrain") else 2), dtype=torch.int32, device=qpos.device)
577
+ with torch.cuda.device(dev):
578
+ st = torch.cuda.current_stream(dev).cuda_stream
579
+ rc = T["query"](ctypes.c_void_p(st), B, _p(qpos), _p(com), dmax, _p(dist), _p(pts), _p(nrm), _p(far),
580
+ _p(face))
581
+ if rc:
582
+ raise RuntimeError(f"{who}: query launch failed ({rc})")
583
+ return dist, pts, nrm, far, face
584
+
585
+
586
+ def torch_query_backward(T, qpos, com, gd, gp, dmax, who="nablaengine.dist_query"):
587
+ """The qpos cotangent of the interface state T's query VJP entry."""
588
+ import torch
589
+ dev = torch_ready(T, qpos, who)
590
+ gq = torch.empty_like(qpos)
591
+ with torch.cuda.device(dev):
592
+ st = torch.cuda.current_stream(dev).cuda_stream
593
+ rc = T["query_vjp"](ctypes.c_void_p(st), qpos.shape[0], _p(qpos), _p(com), dmax, _p(gd.contiguous()),
594
+ _p(gp.contiguous()), _p(gq))
595
+ if rc:
596
+ raise RuntimeError(f"{who}: query VJP launch failed ({rc})")
597
+ return gq
598
+
599
+
600
+ def torch_query_on(T, qpos, com, max_distance=None, faces=False, elements=False, who="nablaengine.dist_query"):
601
+ """torch_query on the interface state T."""
602
+ import torch
603
+ if not T:
604
+ raise RuntimeError(f"{who}: call torch_init(model, pairs) first")
605
+ dmax = float(np.float32(T["dmax"] if max_distance is None else max_distance))
606
+
607
+ class Q(torch.autograd.Function):
608
+ @staticmethod
609
+ def forward(ctx, q, c):
610
+ ctx.save_for_backward(q, c)
611
+ d, p, n, f, fc = torch_query_forward(T, q, c, dmax, who)
612
+ ctx.mark_non_differentiable(n, f, fc)
613
+ return d, p, n, f, fc
614
+
615
+ @staticmethod
616
+ def backward(ctx, gd, gp, gn, gf, gfc):
617
+ q, c = ctx.saved_tensors
618
+ gd = torch.zeros((q.shape[0], T["info"]["nslot"]), device=q.device) if gd is None else gd
619
+ gp = torch.zeros((q.shape[0], T["info"]["nslot"], 2, 3), device=q.device) if gp is None else gp
620
+ return torch_query_backward(T, q, c, gd, gp, dmax, who), None
621
+
622
+ return query_outputs(Q.apply(qpos, com), faces, elements, who)
623
+
624
+
625
+ def torch_query(qpos, com, max_distance=None, faces=False, elements=False):
626
+ """query() for torch tensors (qpos (B, nq), com (B, com_words) float32 CUDA tensors, contiguous; autograd: qpos's
627
+ gradient from dist's and points'; faces=True: also face; elements=True: also element, terrain builds)."""
628
+ return torch_query_on(_T, qpos, com, max_distance, faces, elements)