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,685 @@
1
+ """Dynamics queries of the forest engine: the joint-space mass matrix M(q), the bias force qfrc_bias(q, qdot) and the
2
+ Jacobians of world points on bodies, batched over worlds, on the GPU (no host round trip), from JAX and PyTorch."""
3
+ import ctypes
4
+ import threading
5
+
6
+ import numpy as np
7
+
8
+ UNIT = "dq.cu"
9
+
10
+ FFI = r"""
11
+ #include <cuda_runtime.h>
12
+ #include <climits>
13
+ #include <cstdint>
14
+ #include <mutex>
15
+ #include <string>
16
+ #include <vector>
17
+ #include "xla/ffi/api/ffi.h"
18
+ namespace ffi = xla::ffi;
19
+ @DEFINES@
20
+ extern "C" int dq_upload(const float*, cudaStream_t);
21
+ extern "C" int dq_dynamics(cudaStream_t, int, const float*, const float*, const float*, float*, float*);
22
+ extern "C" int dq_jacobian(cudaStream_t, int, int, const float*, const int*, const float*, float*, float*);
23
+ extern "C" int dq_jacobian_vjp(cudaStream_t, int, int, const float*, const int*, const float*, const float*,
24
+ const float*, float*, float*);
25
+ extern "C" int dq_kinematics(cudaStream_t, int, const float*, const float*, const float*, float*, float*, float*,
26
+ float*, float*);
27
+ extern "C" int dq_kinematics_vjp(cudaStream_t, int, const float*, const float*, const float*, const float*,
28
+ const float*, const float*, const float*, const float*, const float*, const float*,
29
+ float*, float*);
30
+ static std::vector<float> g_consts;
31
+ static std::mutex g_mu;
32
+ static bool g_ready[64];
33
+ extern "C" int dq_set_constants(const float* p, long long n) {
34
+ std::lock_guard<std::mutex> lock(g_mu);
35
+ if (n != NCONST) return 1;
36
+ g_consts.assign(p, p + n);
37
+ for (int d = 0; d < 64; d++) g_ready[d] = false;
38
+ return 0;
39
+ }
40
+ static ffi::Error cuda_error(cudaError_t e, const char* what) {
41
+ if (e == cudaSuccess) return ffi::Error::Success();
42
+ return ffi::Error::Internal(std::string("nablaengine.dyn_query: ") + what + ": " + cudaGetErrorString(e));
43
+ }
44
+ static ffi::Error bad(const std::string& m) { return ffi::Error::InvalidArgument("nablaengine.dyn_query: " + m); }
45
+ static ffi::Error ensure_ready(cudaStream_t st) {
46
+ int dev = -1;
47
+ cudaError_t e = cudaGetDevice(&dev);
48
+ if (e != cudaSuccess) return cuda_error(e, "cudaGetDevice");
49
+ std::lock_guard<std::mutex> lock(g_mu);
50
+ if (dev < 0 || dev >= 64) return ffi::Error::Internal("nablaengine.dyn_query: device ordinal out of range");
51
+ if (g_ready[dev]) return ffi::Error::Success();
52
+ if ((long long)g_consts.size() != NCONST) return ffi::Error::Internal("nablaengine.dyn_query: no constants (init)");
53
+ int rc = dq_upload(g_consts.data(), st);
54
+ if (rc) return cuda_error((cudaError_t)rc, "constant upload");
55
+ e = cudaStreamSynchronize(st);
56
+ if (e != cudaSuccess) return cuda_error(e, "constant upload (synchronize)");
57
+ g_ready[dev] = true;
58
+ return ffi::Error::Success();
59
+ }
60
+ template <class B> static bool dims_are(const B& b, std::initializer_list<int64_t> want) {
61
+ auto d = b.dimensions();
62
+ if (d.size() != want.size()) return false;
63
+ size_t i = 0;
64
+ for (int64_t n : want)
65
+ if (d[i++] != n) return false;
66
+ return true;
67
+ }
68
+ typedef ffi::Buffer<ffi::F32> BufF;
69
+ typedef ffi::Buffer<ffi::S32> BufI;
70
+ typedef ffi::Result<ffi::Buffer<ffi::F32>> RetF;
71
+ static ffi::Error batch(const BufF& qpos, int64_t* B) {
72
+ auto d = qpos.dimensions();
73
+ if (d.size() != 2 || d[1] != NQ) return bad("qpos must be (B, nq) float32");
74
+ *B = d[0];
75
+ if (*B > INT_MAX) return bad("B too large");
76
+ return ffi::Error::Success();
77
+ }
78
+ static ffi::Error dyn_impl(cudaStream_t st, BufF qpos, BufF qvel, BufF com, RetF M, RetF bias) {
79
+ int64_t B = 0;
80
+ ffi::Error e = batch(qpos, &B);
81
+ if (e.failure()) return e;
82
+ if (!dims_are(qvel, {B, NV}) || !dims_are(com, {B, COMW})) return bad("shapes: qvel (B, nv), com (B, com_words)");
83
+ if (!dims_are(*M, {B, NV, NV}) || !dims_are(*bias, {B, NV})) return bad("outputs: M (B, nv, nv), bias (B, nv)");
84
+ if (B == 0) return ffi::Error::Success();
85
+ ffi::Error r = ensure_ready(st);
86
+ if (r.failure()) return r;
87
+ int rc = dq_dynamics(st, (int)B, qpos.typed_data(), qvel.typed_data(), com.typed_data(), M->typed_data(),
88
+ bias->typed_data());
89
+ return rc ? cuda_error((cudaError_t)rc, "k_dq_dyn launch") : ffi::Error::Success();
90
+ }
91
+ static ffi::Error jac_dims(const BufF& qpos, const BufI& bodies, const BufF& pts, int64_t* B, int64_t* P) {
92
+ ffi::Error e = batch(qpos, B);
93
+ if (e.failure()) return e;
94
+ auto d = bodies.dimensions();
95
+ if (d.size() != 2 || d[0] != *B) return bad("bodies must be (B, P) int32");
96
+ *P = d[1];
97
+ if (*P > INT_MAX / 4) return bad("P too large");
98
+ if (!dims_are(pts, {*B, *P, 3})) return bad("points must be (B, P, 3) float32");
99
+ return ffi::Error::Success();
100
+ }
101
+ static ffi::Error jac_impl(cudaStream_t st, BufF qpos, BufI bodies, BufF pts, RetF jacp, RetF jacr) {
102
+ int64_t B = 0, P = 0;
103
+ ffi::Error e = jac_dims(qpos, bodies, pts, &B, &P);
104
+ if (e.failure()) return e;
105
+ if (!dims_are(*jacp, {B, P, 3, NV}) || !dims_are(*jacr, {B, P, 3, NV}))
106
+ return bad("outputs: jacp, jacr (B, P, 3, nv)");
107
+ if (B == 0 || P == 0) return ffi::Error::Success();
108
+ ffi::Error r = ensure_ready(st);
109
+ if (r.failure()) return r;
110
+ int rc = dq_jacobian(st, (int)B, (int)P, qpos.typed_data(), bodies.typed_data(), pts.typed_data(),
111
+ jacp->typed_data(), jacr->typed_data());
112
+ return rc ? cuda_error((cudaError_t)rc, "k_dq_jac launch") : ffi::Error::Success();
113
+ }
114
+ static ffi::Error jac_vjp_impl(cudaStream_t st, BufF qpos, BufI bodies, BufF pts, BufF gjacp, BufF gjacr, RetF gq,
115
+ RetF gpts) {
116
+ int64_t B = 0, P = 0;
117
+ ffi::Error e = jac_dims(qpos, bodies, pts, &B, &P);
118
+ if (e.failure()) return e;
119
+ if (!dims_are(gjacp, {B, P, 3, NV}) || !dims_are(gjacr, {B, P, 3, NV}))
120
+ return bad("cotangents: jacp, jacr (B, P, 3, nv)");
121
+ if (!dims_are(*gq, {B, NQ}) || !dims_are(*gpts, {B, P, 3})) return bad("outputs: g_qpos (B, nq), g_points (B, P, 3)");
122
+ if (B == 0) return ffi::Error::Success();
123
+ ffi::Error r = ensure_ready(st);
124
+ if (r.failure()) return r;
125
+ int rc = dq_jacobian_vjp(st, (int)B, (int)P, qpos.typed_data(), bodies.typed_data(), pts.typed_data(),
126
+ gjacp.typed_data(), gjacr.typed_data(), gq->typed_data(), gpts->typed_data());
127
+ return rc ? cuda_error((cudaError_t)rc, "k_dq_jac_vjp launch") : ffi::Error::Success();
128
+ }
129
+ static bool kin_shapes(int64_t B, const BufF& qn, const BufF& xp, const BufF& xq, const BufF& cv, const BufF& sc) {
130
+ return dims_are(qn, {B, NQ}) && dims_are(xp, {B, NB, 3}) && dims_are(xq, {B, NB, 4}) && dims_are(cv, {B, NB, 6})
131
+ && dims_are(sc, {B, NB, 3});
132
+ }
133
+ #define KIN_SHAPES "qpos_n (B, nq), xpos (B, nbody, 3), xquat (B, nbody, 4), cvel (B, nbody, 6), subtree_com (B, nbody, 3)"
134
+ static ffi::Error kin_impl(cudaStream_t st, BufF qpos, BufF qvel, BufF com, RetF qn, RetF xp, RetF xq, RetF cv,
135
+ RetF sc) {
136
+ int64_t B = 0;
137
+ ffi::Error e = batch(qpos, &B);
138
+ if (e.failure()) return e;
139
+ if (!dims_are(qvel, {B, NV}) || !dims_are(com, {B, COMW})) return bad("shapes: qvel (B, nv), com (B, com_words)");
140
+ if (!kin_shapes(B, *qn, *xp, *xq, *cv, *sc)) return bad("outputs: " KIN_SHAPES);
141
+ if (B == 0) return ffi::Error::Success();
142
+ ffi::Error r = ensure_ready(st);
143
+ if (r.failure()) return r;
144
+ int rc = dq_kinematics(st, (int)B, qpos.typed_data(), qvel.typed_data(), com.typed_data(), qn->typed_data(),
145
+ xp->typed_data(), xq->typed_data(), cv->typed_data(), sc->typed_data());
146
+ return rc ? cuda_error((cudaError_t)rc, "k_dq_kin launch") : ffi::Error::Success();
147
+ }
148
+ static ffi::Error kin_vjp_impl(cudaStream_t st, BufF qpos, BufF qvel, BufF com, BufF gqn, BufF gxp, BufF gxq,
149
+ BufF gcv, BufF gsc, RetF gq, RetF gv) {
150
+ int64_t B = 0;
151
+ ffi::Error e = batch(qpos, &B);
152
+ if (e.failure()) return e;
153
+ if (!dims_are(qvel, {B, NV}) || !dims_are(com, {B, COMW})) return bad("shapes: qvel (B, nv), com (B, com_words)");
154
+ if (!kin_shapes(B, gqn, gxp, gxq, gcv, gsc)) return bad("cotangents: " KIN_SHAPES);
155
+ if (!dims_are(*gq, {B, NQ}) || !dims_are(*gv, {B, NV})) return bad("outputs: g_qpos (B, nq), g_qvel (B, nv)");
156
+ if (B == 0) return ffi::Error::Success();
157
+ ffi::Error r = ensure_ready(st);
158
+ if (r.failure()) return r;
159
+ int rc = dq_kinematics_vjp(st, (int)B, qpos.typed_data(), qvel.typed_data(), com.typed_data(), gqn.typed_data(),
160
+ gxp.typed_data(), gxq.typed_data(), gcv.typed_data(), gsc.typed_data(), nullptr, nullptr,
161
+ gq->typed_data(), gv->typed_data());
162
+ return rc ? cuda_error((cudaError_t)rc, "k_dq_kin_vjp launch") : ffi::Error::Success();
163
+ }
164
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(DqKin, kin_impl,
165
+ ffi::Ffi::Bind().Ctx<ffi::PlatformStream<cudaStream_t>>().Arg<BufF>().Arg<BufF>()
166
+ .Arg<BufF>().Ret<BufF>().Ret<BufF>().Ret<BufF>().Ret<BufF>().Ret<BufF>());
167
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(DqKinVjp, kin_vjp_impl,
168
+ ffi::Ffi::Bind().Ctx<ffi::PlatformStream<cudaStream_t>>().Arg<BufF>().Arg<BufF>()
169
+ .Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>()
170
+ .Ret<BufF>().Ret<BufF>());
171
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(DqDyn, dyn_impl,
172
+ ffi::Ffi::Bind().Ctx<ffi::PlatformStream<cudaStream_t>>().Arg<BufF>().Arg<BufF>()
173
+ .Arg<BufF>().Ret<BufF>().Ret<BufF>());
174
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(DqJac, jac_impl,
175
+ ffi::Ffi::Bind().Ctx<ffi::PlatformStream<cudaStream_t>>().Arg<BufF>().Arg<BufI>()
176
+ .Arg<BufF>().Ret<BufF>().Ret<BufF>());
177
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(DqJacVjp, jac_vjp_impl,
178
+ ffi::Ffi::Bind().Ctx<ffi::PlatformStream<cudaStream_t>>().Arg<BufF>().Arg<BufI>()
179
+ .Arg<BufF>().Arg<BufF>().Arg<BufF>().Ret<BufF>().Ret<BufF>());
180
+ """
181
+
182
+
183
+ def _resolve(model, foot_pairs, com_body, params):
184
+ from nablaengine import engines, jax_ffi
185
+ from nablaengine.forest_engine import step as fstep, world_params
186
+ from nablaengine.params import as_params
187
+ if model is not None and foot_pairs is None:
188
+ foot_pairs = []
189
+ m, fp, com = jax_ffi._model(None, model, foot_pairs, com_body)
190
+ params = as_params(params)
191
+ engines.require_forest(m, com, "dyn_query.init", fp)
192
+ if fstep.fixture_groups(m):
193
+ raise ValueError("nablaengine.dyn_query: models with per-world fixture placements are not supported")
194
+ if params:
195
+ world_params.check(m, params, fp, com)
196
+ if "body_inertial" in params.fields:
197
+ raise ValueError("nablaengine.dyn_query: PhysicsParams body_inertial is not supported by the queries yet "
198
+ "(nor the kinematics outputs of models the step library's kernels do not cover)")
199
+ return m, fp, com, params
200
+
201
+
202
+ def library_sources(m, com_body=None, params=None, ffi=True, pw_off=3):
203
+ """({unit: source}, packed constants, {unit: -D options}) of the query library (ffi: with the XLA FFI unit; pw_off:
204
+ the parameters' offset in a com row, 3 or the step's layout's: jax_ffi.com_layout)."""
205
+ from nablaengine.forest_engine import dyn_device
206
+ src, consts = dyn_device.cuda_source(m, com_body, params, pw_off)
207
+ units, defines = {UNIT: src}, {UNIT: []}
208
+ if ffi:
209
+ defs = [f"#define {k} {v}" for k, v in (("NQ", m.nq), ("NV", m.nv), ("NB", m.nbody), ("NCONST", len(consts)),
210
+ ("COMW", pw_off + (params.width(m.nv) if params else 0)))]
211
+ units["dk_ffi.cu"] = FFI.replace("@DEFINES@", "\n".join(defs))
212
+ defines["dk_ffi.cu"] = []
213
+ return units, consts, defines
214
+
215
+
216
+ def _build(m, com_body, params, ffi, arch, include, prefix, pw_off=3):
217
+ from nablaengine import cuda, jax_ffi
218
+ units, consts, defines = library_sources(m, com_body, params, ffi, pw_off)
219
+ flags = cuda.arch_flags(None, arch)
220
+ unit_arch = {n: flags for n in units} if flags != [f"-arch={arch}"] else None
221
+ path, built, key = jax_ffi._build(units, defines, arch, include, consts, unit_arch, prefix=prefix)
222
+ return dict(path=str(path), built=built, key=key, consts=consts)
223
+
224
+
225
+ def _check_sizes(lib, m, comw):
226
+ sz = np.zeros(6, np.int64)
227
+ lib.dq_sizes(ctypes.c_void_p(sz.ctypes.data))
228
+ assert tuple(sz[:4]) == (m.nq, m.nv, m.nbody, comw), sz
229
+ return int(sz[4])
230
+
231
+
232
+ def _default_com(m, com_body, params, pw_off=3):
233
+ row = np.zeros(pw_off + (params.width(m.nv) if params else 0), np.float32)
234
+ if params:
235
+ import mujoco
236
+ lay = params.layout(m.nv)
237
+ if "gravity" in lay:
238
+ o, n = lay["gravity"]
239
+ row[pw_off + o:pw_off + o + n] = m.opt.gravity
240
+ b = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, com_body) if com_body else -1
241
+ if "dof_armature" in lay:
242
+ o, n = lay["dof_armature"]
243
+ row[pw_off + o:pw_off + o + n] = m.dof_armature
244
+ if "torso_mass" in lay:
245
+ row[pw_off + lay["torso_mass"][0]] = m.body_mass[b]
246
+ if "torso_inertia" in lay:
247
+ o, n = lay["torso_inertia"]
248
+ row[pw_off + o:pw_off + o + n] = m.body_inertia[b]
249
+ return row
250
+
251
+
252
+ def _info(m, fp, com, params, b, sizeof, pw_off=3):
253
+ return dict(path=b["path"], key=b["key"], built=b["built"], nq=m.nq, nv=m.nv, nbody=m.nbody, com_body=com,
254
+ com_words=pw_off + (params.width(m.nv) if params else 0), params=params.key() if params else None,
255
+ foot_pairs=[int(p) for p in fp], sizeof_state=sizeof)
256
+
257
+
258
+ def pw_offset(m, params, com_layout=None, pw_off=3):
259
+ """The parameters' offset in a com row: com_layout (a jax_ffi build's info["com_layout"]: COM offset, object slots,
260
+ their motion words, then the parameters) gives it, checked against params; else pw_off. A layout with per-world
261
+ fixture placements is refused (not supported by the queries)."""
262
+ if com_layout is None:
263
+ return int(pw_off)
264
+ lay = {k: tuple(int(x) for x in v) for k, v in dict(com_layout).items()}
265
+ if "fixtures" in lay:
266
+ raise ValueError("nablaengine.dyn_query: com_layout with per-world fixture placements is not supported")
267
+ names = [k[len("params."):] for k in lay if k.startswith("params.")]
268
+ want = list(params.layout(m.nv)) if params else []
269
+ if names != want:
270
+ raise ValueError(f"nablaengine.dyn_query: com_layout's parameters {names} are not params' fields {want}")
271
+ if not names:
272
+ return max(o + w for o, w in lay.values())
273
+ off = lay["params." + names[0]][0]
274
+ for f, (o, w) in params.layout(m.nv).items():
275
+ if lay["params." + f] != (off + o, w):
276
+ raise ValueError(f"nablaengine.dyn_query: com_layout's params.{f} {lay['params.' + f]} is not at the "
277
+ f"parameters' layout ({off + o}, {w})")
278
+ return off
279
+
280
+
281
+ _LOCK = threading.Lock()
282
+ _J = {}
283
+
284
+
285
+ def init(model=None, foot_pairs=None, com_body=None, params=None, pw_off=3, com_layout=None):
286
+ """Build / load the query library for the model (default: the fixtures' G1, as jax_ffi.init) and register its FFI
287
+ targets. com_body: the body of com's COM offset and of the torso fields (default as jax_ffi.init: the G1's
288
+ torso_link, none for the forest engine's other models). params: per-world physics parameters (com's layout).
289
+ pw_off: the parameters' offset in a com row (3); com_layout: a jax_ffi build's info["com_layout"] in its place (a
290
+ terrain build: the object slots' and their motion words come before the parameters; the query then takes that
291
+ build's com rows as they are; pw_offset). Returns a dict (path, key, com_words, ...). One query library per process
292
+ (a second init with another model or layout raises)."""
293
+ from nablaengine import jax_ffi
294
+ jax_ffi.ensure_jax_ffi()
295
+ import jax
296
+ with _LOCK:
297
+ m, fp, com, params = _resolve(model, foot_pairs, com_body, params)
298
+ pw_off = pw_offset(m, params, com_layout, pw_off)
299
+ if _J:
300
+ if _J["consts_hash"] != _hash(m, com, params) or _J["info"]["pw_off"] != pw_off:
301
+ raise RuntimeError("nablaengine.dyn_query: already initialised with another model (one per process)")
302
+ return _J["info"]
303
+ arch = jax_ffi._arch()
304
+ b = _build(m, com, params, True, arch, jax.ffi.include_dir(), "libdk_dynq", pw_off)
305
+ lib = ctypes.cdll.LoadLibrary(b["path"])
306
+ lib.dq_set_constants.argtypes = [ctypes.c_void_p, ctypes.c_longlong]
307
+ c = np.ascontiguousarray(b["consts"], np.float32)
308
+ if lib.dq_set_constants(c.ctypes.data, len(c)):
309
+ raise RuntimeError("nablaengine.dyn_query: dq_set_constants failed")
310
+ sizeof = _check_sizes(lib, m, pw_off + (params.width(m.nv) if params else 0))
311
+ targets = {}
312
+ for kind, sym in (("dyn", "DqDyn"), ("jac", "DqJac"), ("jac_vjp", "DqJacVjp"), ("kin", "DqKin"),
313
+ ("kin_vjp", "DqKinVjp")):
314
+ targets[kind] = f"dq_{kind}_{b['key'][:8]}"
315
+ jax.ffi.register_ffi_target(targets[kind], jax.ffi.pycapsule(getattr(lib, sym)), platform="CUDA")
316
+ info = dict(_info(m, fp, com, params, b, sizeof, pw_off), pw_off=pw_off)
317
+ _J.update(lib=lib, targets=targets, info=info, m=m, consts_hash=_hash(m, com, params),
318
+ com_row=_default_com(m, com, params, pw_off))
319
+ return info
320
+
321
+
322
+ def _hash(m, com, params):
323
+ import hashlib
324
+ from nablaengine.forest_engine import dyn_device
325
+ c = dyn_device.constants(m, com)[0]
326
+ return hashlib.sha256(c.tobytes() + repr(params.key() if params else None).encode()).hexdigest()
327
+
328
+
329
+ def _need():
330
+ if not _J:
331
+ raise RuntimeError("nablaengine.dyn_query: call dyn_query.init() first")
332
+ return _J
333
+
334
+
335
+ def dynamics(qpos, qvel, com=None):
336
+ """(M (B, nv, nv), bias (B, nv)) of the states (qpos (B, nq), qvel (B, nv)); com (B, com_words) or None (the
337
+ model's values). Not differentiable."""
338
+ import jax
339
+ import jax.numpy as jnp
340
+ J = _need()
341
+ nv = J["info"]["nv"]
342
+ qpos = jnp.asarray(qpos, jnp.float32)
343
+ B = qpos.shape[0]
344
+ if com is None:
345
+ com = jnp.broadcast_to(jnp.asarray(J["com_row"]), (B, J["com_row"].shape[0]))
346
+ outs = [jax.ShapeDtypeStruct((B, nv, nv), jnp.float32), jax.ShapeDtypeStruct((B, nv), jnp.float32)]
347
+ M, bias = jax.ffi.ffi_call(J["targets"]["dyn"], outs)(qpos, jnp.asarray(qvel, jnp.float32),
348
+ jnp.asarray(com, jnp.float32))
349
+ return jax.lax.stop_gradient(M), jax.lax.stop_gradient(bias)
350
+
351
+
352
+ def _jac_args(qpos, bodies, points):
353
+ import jax.numpy as jnp
354
+ qpos = jnp.asarray(qpos, jnp.float32)
355
+ B = qpos.shape[0]
356
+ points = jnp.asarray(points, jnp.float32)
357
+ if points.ndim == 2:
358
+ points = jnp.broadcast_to(points, (B,) + points.shape)
359
+ bodies = jnp.asarray(bodies, jnp.int32)
360
+ if bodies.ndim == 1:
361
+ bodies = jnp.broadcast_to(bodies, (B, bodies.shape[0]))
362
+ if points.shape[:2] != bodies.shape or points.shape[2] != 3 or bodies.shape[0] != B:
363
+ raise ValueError(f"dyn_query.jacobian: bodies {bodies.shape} and points {points.shape}: (B, P) and (B, P, 3)")
364
+ return qpos, bodies, points
365
+
366
+
367
+ def jacobian_forward(qpos, bodies, points):
368
+ """(jacp, jacr) (B, P, 3, nv) without custom_vjp; bodies (B, P) int32, points (B, P, 3)."""
369
+ import jax
370
+ import jax.numpy as jnp
371
+ J = _need()
372
+ B, P, nv = qpos.shape[0], bodies.shape[1], J["info"]["nv"]
373
+ outs = [jax.ShapeDtypeStruct((B, P, 3, nv), jnp.float32)] * 2
374
+ return tuple(jax.ffi.ffi_call(J["targets"]["jac"], outs)(qpos, bodies, points))
375
+
376
+
377
+ def jacobian_backward(qpos, bodies, points, g_jacp, g_jacr):
378
+ """(g_qpos (B, nq), g_points (B, P, 3)) for the cotangents of jacp and jacr."""
379
+ import jax
380
+ import jax.numpy as jnp
381
+ J = _need()
382
+ outs = [jax.ShapeDtypeStruct(qpos.shape, jnp.float32), jax.ShapeDtypeStruct(points.shape, jnp.float32)]
383
+ return tuple(jax.ffi.ffi_call(J["targets"]["jac_vjp"], outs)(
384
+ qpos, bodies, points, jnp.asarray(g_jacp, jnp.float32), jnp.asarray(g_jacr, jnp.float32)))
385
+
386
+
387
+ _JFN = []
388
+
389
+
390
+ def _jac_fn():
391
+ if not _JFN:
392
+ import jax
393
+ import numpy as _np
394
+
395
+ @jax.custom_vjp
396
+ def f(q, b, p):
397
+ return jacobian_forward(q, b, p)
398
+
399
+ def f_fwd(q, b, p):
400
+ return jacobian_forward(q, b, p), (q, b, p)
401
+
402
+ def f_bwd(res, ct):
403
+ q, b, p = res
404
+ gq, gp = jacobian_backward(q, b, p, ct[0], ct[1])
405
+ return gq, _np.zeros(b.shape, jax.dtypes.float0), gp
406
+
407
+ f.defvjp(f_fwd, f_bwd)
408
+ _JFN.append(f)
409
+ return _JFN[0]
410
+
411
+
412
+ def jacobian(qpos, bodies, points):
413
+ """MuJoCo's mj_jac for P points per world: (jacp, jacr) (B, P, 3, nv). bodies (P,) or (B, P) int (the body each
414
+ point moves with), points (P, 3) or (B, P, 3) world coordinates. Differentiable in qpos and points."""
415
+ return _jac_fn()(*_jac_args(qpos, bodies, points))
416
+
417
+
418
+ KIN_OUTPUTS = ("qpos_n", "xpos", "xquat", "cvel", "subtree_com")
419
+
420
+
421
+ def _kin_structs(B):
422
+ import jax
423
+ import jax.numpy as jnp
424
+ i = _need()["info"]
425
+ nb = i["nbody"]
426
+ return [jax.ShapeDtypeStruct(s, jnp.float32) for s in ((B, i["nq"]), (B, nb, 3), (B, nb, 4), (B, nb, 6), (B, nb, 3))]
427
+
428
+
429
+ def _com_arg(com, B, row):
430
+ import jax.numpy as jnp
431
+ if com is None:
432
+ return jnp.broadcast_to(jnp.asarray(row), (B, row.shape[0]))
433
+ com = jnp.asarray(com, jnp.float32)
434
+ if com.shape[1] < row.shape[0]:
435
+ com = jnp.concatenate([com, jnp.broadcast_to(jnp.asarray(row[com.shape[1]:]), (B, row.shape[0] - com.shape[1]))],
436
+ axis=1)
437
+ return com
438
+
439
+
440
+ def kinematics_forward(qpos, qvel, com=None):
441
+ """(qpos_n (B, nq), xpos (B, nbody, 3), xquat (B, nbody, 4), cvel (B, nbody, 6), subtree_com (B, nbody, 3))
442
+ without custom_vjp: jax_ffi.kinematics's outputs and conventions on any forest model (several trees, free bodies,
443
+ slides): every free joint's quaternion normalized into qpos_n, subtree_com of every body (body 0: all trees),
444
+ cvel at the subtree COM of each body's tree root (MuJoCo's cvel). com: (B, com_words), (B, 3) (the parameters at
445
+ the model's values) or None."""
446
+ import jax
447
+ import jax.numpy as jnp
448
+ J = _need()
449
+ qpos = jnp.asarray(qpos, jnp.float32)
450
+ B = qpos.shape[0]
451
+ return tuple(jax.ffi.ffi_call(J["targets"]["kin"], _kin_structs(B))(
452
+ qpos, jnp.asarray(qvel, jnp.float32), _com_arg(com, B, J["com_row"])))
453
+
454
+
455
+ def kinematics_backward(qpos, qvel, com, g_qpos_n, g_xpos, g_xquat, g_cvel, g_subtree_com):
456
+ """(g_qpos (B, nq), g_qvel (B, nv)) of kinematics_forward at (qpos, qvel, com) (com gets none)."""
457
+ import jax
458
+ import jax.numpy as jnp
459
+ J = _need()
460
+ qpos = jnp.asarray(qpos, jnp.float32)
461
+ B = qpos.shape[0]
462
+ outs = [jax.ShapeDtypeStruct((B, J["info"]["nq"]), jnp.float32), jax.ShapeDtypeStruct((B, J["info"]["nv"]),
463
+ jnp.float32)]
464
+ gk = [jnp.asarray(g, jnp.float32) for g in (g_qpos_n, g_xpos, g_xquat, g_cvel, g_subtree_com)]
465
+ return tuple(jax.ffi.ffi_call(J["targets"]["kin_vjp"], outs)(
466
+ qpos, jnp.asarray(qvel, jnp.float32), _com_arg(com, B, J["com_row"]), *gk))
467
+
468
+
469
+ _KFN = []
470
+
471
+
472
+ def kinematics(qpos, qvel, com):
473
+ """Differentiable kinematics outputs (kinematics_forward), a jax.custom_vjp: cotangents of qpos (the free
474
+ quaternions through their normalization) and qvel, zeros for com. com: (B, com_words) or (B, 3)."""
475
+ if not _KFN:
476
+ import jax
477
+ import jax.numpy as jnp
478
+ from jax.ad_checkpoint import checkpoint_name
479
+ from nablaengine.jax_ffi import KIN_NAME
480
+
481
+ @jax.custom_vjp
482
+ def f(q, v, c):
483
+ return kinematics_forward(q, v, c)
484
+
485
+ def f_fwd(q, v, c):
486
+ out = tuple(checkpoint_name(x, KIN_NAME) for x in kinematics_forward(q, v, c))
487
+ return out, (checkpoint_name(q, KIN_NAME), checkpoint_name(v, KIN_NAME), c)
488
+
489
+ def f_bwd(res, ct):
490
+ q, v, c = res
491
+ gq, gv = kinematics_backward(q, v, c, *ct)
492
+ return gq, gv, jnp.zeros_like(c)
493
+
494
+ f.defvjp(f_fwd, f_bwd)
495
+ _KFN.append(f)
496
+ import jax.numpy as jnp
497
+ qpos = jnp.asarray(qpos, jnp.float32)
498
+ return _KFN[0](qpos, jnp.asarray(qvel, jnp.float32), _com_arg(com, qpos.shape[0], _need()["com_row"]))
499
+
500
+
501
+ _T = {}
502
+
503
+
504
+ def torch_init(device=None, model=None, foot_pairs=None, com_body=None, params=None, pw_off=3, com_layout=None):
505
+ """The query library for PyTorch (ctypes entries on torch's current stream; no FFI unit, no jax needed): arguments
506
+ as init(); device: the CUDA device (default the current one)."""
507
+ import torch
508
+ from nablaengine import cuda
509
+ with _LOCK:
510
+ m, fp, com, params = _resolve(model, foot_pairs, com_body, params)
511
+ pw_off = pw_offset(m, params, com_layout, pw_off)
512
+ if _T:
513
+ if _T["consts_hash"] != _hash(m, com, params) or _T["info"]["pw_off"] != pw_off:
514
+ raise RuntimeError("nablaengine.dyn_query: torch_init already called with another model")
515
+ return _T["info"]
516
+ dev = torch.device(device if device is not None else "cuda").index
517
+ dev = torch.cuda.current_device() if dev is None else dev
518
+ cc = torch.cuda.get_device_capability(dev)
519
+ arch = f"sm_{cc[0]}{cc[1]}"
520
+ cuda.arch()
521
+ b = _build(m, com, params, False, arch, None, "libdk_dynq_torch", pw_off)
522
+ lib = ctypes.cdll.LoadLibrary(b["path"])
523
+ P = ctypes.c_void_p
524
+ lib.dq_upload.argtypes = [P, P]
525
+ lib.dq_dynamics.argtypes = [P, ctypes.c_int, P, P, P, P, P]
526
+ lib.dq_jacobian.argtypes = [P, ctypes.c_int, ctypes.c_int, P, P, P, P, P]
527
+ lib.dq_jacobian_vjp.argtypes = [P, ctypes.c_int, ctypes.c_int, P, P, P, P, P, P, P]
528
+ sizeof = _check_sizes(lib, m, pw_off + (params.width(m.nv) if params else 0))
529
+ lib.dq_kinematics.argtypes = [P, ctypes.c_int] + [P] * 8
530
+ lib.dq_kinematics_vjp.argtypes = [P, ctypes.c_int] + [P] * 12
531
+ info = dict(_info(m, fp, com, params, b, sizeof, pw_off), pw_off=pw_off)
532
+ _T.update(lib=lib, info=info, consts=np.ascontiguousarray(b["consts"], np.float32), ready=set(), m=m,
533
+ consts_hash=_hash(m, com, params), com_row=_default_com(m, com, params, pw_off))
534
+ return info
535
+
536
+
537
+ def _tlib(device):
538
+ import torch
539
+ if not _T:
540
+ raise RuntimeError("nablaengine.dyn_query: call dyn_query.torch_init() first")
541
+ dev = device.index if device.index is not None else torch.cuda.current_device()
542
+ st = torch.cuda.current_stream(dev)
543
+ if dev not in _T["ready"]:
544
+ with torch.cuda.device(dev):
545
+ rc = _T["lib"].dq_upload(_T["consts"].ctypes.data, st.cuda_stream)
546
+ st.synchronize()
547
+ if rc:
548
+ raise RuntimeError(f"nablaengine.dyn_query: constant upload failed ({rc})")
549
+ _T["ready"].add(dev)
550
+ return _T["lib"], dev, st.cuda_stream
551
+
552
+
553
+ def _tcheck(rc, what):
554
+ if rc:
555
+ raise RuntimeError(f"nablaengine.dyn_query: {what} failed (cudaError {rc})")
556
+
557
+
558
+ def torch_dynamics(qpos, qvel, com=None):
559
+ """(M (B, nv, nv), bias (B, nv)) as dynamics(), torch tensors on qpos's device (no gradient)."""
560
+ import torch
561
+ lib, dev, st = _tlib(qpos.device)
562
+ nv = _T["info"]["nv"]
563
+ qpos = qpos.detach().to(torch.float32).contiguous()
564
+ qvel = qvel.detach().to(torch.float32).contiguous()
565
+ B = qpos.shape[0]
566
+ if com is None:
567
+ com = torch.as_tensor(_T["com_row"], device=qpos.device).expand(B, -1)
568
+ com = com.detach().to(torch.float32).contiguous()
569
+ assert qpos.shape == (B, _T["info"]["nq"]) and qvel.shape == (B, nv) and com.shape == (B, _T["info"]["com_words"])
570
+ M = torch.empty((B, nv, nv), dtype=torch.float32, device=qpos.device)
571
+ bias = torch.empty((B, nv), dtype=torch.float32, device=qpos.device)
572
+ with torch.cuda.device(dev):
573
+ _tcheck(lib.dq_dynamics(st, B, qpos.data_ptr(), qvel.data_ptr(), com.data_ptr(), M.data_ptr(),
574
+ bias.data_ptr()), "k_dq_dyn")
575
+ return M, bias
576
+
577
+
578
+ def _tjac_args(qpos, bodies, points):
579
+ import torch
580
+ B = qpos.shape[0]
581
+ points = torch.as_tensor(points, dtype=torch.float32, device=qpos.device)
582
+ if points.dim() == 2:
583
+ points = points.expand(B, -1, -1)
584
+ bodies = torch.as_tensor(bodies, dtype=torch.int32, device=qpos.device)
585
+ if bodies.dim() == 1:
586
+ bodies = bodies.expand(B, -1)
587
+ if tuple(points.shape[:2]) != tuple(bodies.shape) or points.shape[2] != 3:
588
+ raise ValueError(f"dyn_query.torch_jacobian: bodies {tuple(bodies.shape)} and points {tuple(points.shape)}")
589
+ return bodies.contiguous(), points
590
+
591
+
592
+ def _torch_jac_fn():
593
+ import torch
594
+
595
+ class Jac(torch.autograd.Function):
596
+ @staticmethod
597
+ def forward(ctx, qpos, bodies, points):
598
+ lib, dev, st = _tlib(qpos.device)
599
+ q = qpos.detach().to(torch.float32).contiguous()
600
+ p = points.detach().to(torch.float32).contiguous()
601
+ B, P, nv = q.shape[0], bodies.shape[1], _T["info"]["nv"]
602
+ jp = torch.empty((B, P, 3, nv), dtype=torch.float32, device=q.device)
603
+ jr = torch.empty_like(jp)
604
+ with torch.cuda.device(dev):
605
+ _tcheck(lib.dq_jacobian(st, B, P, q.data_ptr(), bodies.data_ptr(), p.data_ptr(), jp.data_ptr(),
606
+ jr.data_ptr()), "k_dq_jac")
607
+ ctx.save_for_backward(q, bodies, p)
608
+ return jp, jr
609
+
610
+ @staticmethod
611
+ def backward(ctx, gjp, gjr):
612
+ q, bodies, p = ctx.saved_tensors
613
+ lib, dev, st = _tlib(q.device)
614
+ gjp = (torch.zeros((*bodies.shape, 3, _T["info"]["nv"]), device=q.device) if gjp is None
615
+ else gjp.to(torch.float32).contiguous())
616
+ gjr = torch.zeros_like(gjp) if gjr is None else gjr.to(torch.float32).contiguous()
617
+ gq, gp = torch.empty_like(q), torch.empty_like(p)
618
+ with torch.cuda.device(dev):
619
+ _tcheck(lib.dq_jacobian_vjp(st, q.shape[0], bodies.shape[1], q.data_ptr(), bodies.data_ptr(),
620
+ p.data_ptr(), gjp.data_ptr(), gjr.data_ptr(), gq.data_ptr(),
621
+ gp.data_ptr()), "k_dq_jac_vjp")
622
+ return gq, None, gp
623
+
624
+ return Jac
625
+
626
+
627
+ def torch_jacobian(qpos, bodies, points):
628
+ """(jacp, jacr) (B, P, 3, nv) as jacobian(), differentiable (torch.autograd) in qpos and points."""
629
+ if "jac_fn" not in _T:
630
+ _T["jac_fn"] = _torch_jac_fn()
631
+ bodies, points = _tjac_args(qpos, bodies, points)
632
+ return _T["jac_fn"].apply(qpos, bodies, points)
633
+
634
+
635
+ def _torch_kin_fn():
636
+ import torch
637
+
638
+ class Kin(torch.autograd.Function):
639
+ @staticmethod
640
+ def forward(ctx, qpos, qvel, com):
641
+ lib, dev, st = _tlib(qpos.device)
642
+ q, v = qpos.detach().to(torch.float32).contiguous(), qvel.detach().to(torch.float32).contiguous()
643
+ c = com.detach().to(torch.float32).contiguous()
644
+ B, nb, nq = q.shape[0], _T["info"]["nbody"], _T["info"]["nq"]
645
+ kw = dict(dtype=torch.float32, device=q.device)
646
+ outs = [torch.empty((B, nq), **kw), torch.empty((B, nb, 3), **kw), torch.empty((B, nb, 4), **kw),
647
+ torch.empty((B, nb, 6), **kw), torch.empty((B, nb, 3), **kw)]
648
+ with torch.cuda.device(dev):
649
+ _tcheck(lib.dq_kinematics(st, B, q.data_ptr(), v.data_ptr(), c.data_ptr(),
650
+ *[o.data_ptr() for o in outs]), "k_dq_kin")
651
+ ctx.save_for_backward(q, v, c)
652
+ return tuple(outs)
653
+
654
+ @staticmethod
655
+ def backward(ctx, *g):
656
+ q, v, c = ctx.saved_tensors
657
+ lib, dev, st = _tlib(q.device)
658
+ B, nb, nq = q.shape[0], _T["info"]["nbody"], _T["info"]["nq"]
659
+ shapes = [(B, nq), (B, nb, 3), (B, nb, 4), (B, nb, 6), (B, nb, 3)]
660
+ g = [torch.zeros(s, dtype=torch.float32, device=q.device) if x is None else x.to(torch.float32).contiguous()
661
+ for x, s in zip(g, shapes)]
662
+ gq, gv = torch.empty_like(q), torch.empty_like(v)
663
+ with torch.cuda.device(dev):
664
+ _tcheck(lib.dq_kinematics_vjp(st, B, q.data_ptr(), v.data_ptr(), c.data_ptr(),
665
+ *[x.data_ptr() for x in g], None, None, gq.data_ptr(), gv.data_ptr()),
666
+ "k_dq_kin_vjp")
667
+ return gq, gv, None
668
+
669
+ return Kin
670
+
671
+
672
+ def torch_kinematics(qpos, qvel, com=None):
673
+ """(qpos_n, xpos, xquat, cvel, subtree_com) as kinematics(), differentiable (torch.autograd) in qpos and qvel;
674
+ com (B, com_words), (B, 3) or None."""
675
+ import torch
676
+ if "kin_fn" not in _T:
677
+ _T["kin_fn"] = _torch_kin_fn()
678
+ _tlib(qpos.device)
679
+ B = qpos.shape[0]
680
+ row = torch.as_tensor(_T["com_row"], device=qpos.device)
681
+ if com is None:
682
+ com = row.expand(B, -1)
683
+ elif com.shape[1] < row.shape[0]:
684
+ com = torch.cat([com.to(torch.float32), row[com.shape[1]:].expand(B, -1)], dim=1)
685
+ return _T["kin_fn"].apply(qpos, qvel, com)