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,1328 @@
1
+ """PyTorch interface of the engine: the same CUDA library and semantics as nablaengine.jax_ffi, on torch's current CUDA
2
+ stream."""
3
+ import ctypes
4
+ import hashlib
5
+ import json
6
+ import math
7
+ import os
8
+ import threading
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+
13
+ ITERATIONS, SUBSTEPS, CLAMP_KV, NORMAL = 10, 4, 0, 3
14
+ CLAMP_SOFT, GRAD_DECAY = 0.2, 1.0
15
+ DIAG = ("fwd_calls", "fwd_worlds", "fwd_unsupported_worlds", "fwd_iteration_limit_worlds", "tape_records",
16
+ "refact_records", "nonconv_records", "singular_records", "bwd_calls", "bwd_rows", "nonfinite_rows",
17
+ "nonfinite_qpos_rows", "nonfinite_qvel_rows", "nonfinite_ctrl_rows", "nonfinite_cotangent_rows",
18
+ "replay_mismatch_worlds", "fwd_contact_overflow_worlds", "fwd_row_overflow_worlds")
19
+ OVERFLOW_CONTACTS, OVERFLOW_ROWS = 4, 16
20
+ _OVERFLOW_WARN = [os.environ.get("DK_OVERFLOW_WARN", "0") not in ("", "0")]
21
+ NONFINITE_QPOS, NONFINITE_QVEL, NONFINITE_CTRL, NONFINITE_COT, NONFINITE_SHIFT = 1, 2, 4, 8, 16
22
+ VARIANTS = tuple((kv, n) for kv in (0, 1, 2) for n in (0, 1, 2, 3))
23
+ FWD_UNIT = "dk_fwd"
24
+ ARTIFACT_VERSION = 1
25
+ SOURCES = ("cuda.py", "jax_ffi.py", "torch_ffi.py", "fixtures.py", "engines.py", "ccd.py", "terrain.py",
26
+ "g1_engine/*.py", "forest_engine/*.py",
27
+ "model/*.py")
28
+
29
+
30
+ def _tag(v):
31
+ return f"dk_kv{v[0]}_n{v[1]}"
32
+
33
+
34
+ _LOCK = threading.Lock()
35
+ _STATE = {}
36
+ _READY = set()
37
+ _DIAG = {}
38
+ _DIAG_ON = [True]
39
+
40
+
41
+ def _err(msg, exc=TypeError):
42
+ return exc(f"nablaengine.torch_ffi: {msg}")
43
+
44
+
45
+ TORCH_UNIT = r"""
46
+ #include <cuda_runtime.h>
47
+ // the diagnostic counters of jax_ffi's FFI unit (k_diag_fwd / k_diag_bwd, the same counts) into a caller's
48
+ // (NDIAG,) uint64 array: one launch per forward / backward instead of one elementwise kernel per count
49
+ @DEFINES@
50
+ namespace {
51
+ __device__ __forceinline__ void diag_add(unsigned long long* d, int k, unsigned v) {
52
+ __syncwarp();
53
+ for (int o = 16; o > 0; o >>= 1) v += __shfl_down_sync(0xffffffffu, v, o);
54
+ if ((threadIdx.x & 31) == 0 && v) atomicAdd(&d[k], (unsigned long long)v);
55
+ }
56
+ __device__ __forceinline__ bool all_finite(const float* x, int n) {
57
+ bool ok = true;
58
+ for (int i = 0; i < n; i++) ok &= isfinite(x[i]);
59
+ return ok;
60
+ }
61
+ __global__ void k_tdiag_fwd(unsigned long long* d, int nw, int nsub, int iterations, const int* info,
62
+ const float* tape) {
63
+ unsigned unsup = 0, lim = 0, refact = 0, nonconv = 0, sing = 0, ocon = 0, orow = 0;
64
+ for (int w = blockIdx.x * blockDim.x + threadIdx.x; w < nw; w += gridDim.x * blockDim.x) {
65
+ unsup += info[4 * w + 3] != 0;
66
+ ocon += (info[4 * w + 3] & OVERFLOW_CONTACTS) != 0; orow += (info[4 * w + 3] & OVERFLOW_ROWS) != 0;
67
+ lim += info[4 * w] >= iterations;
68
+ if (tape)
69
+ for (int k = 0; k < nsub; k++) {
70
+ unsigned f = __float_as_uint(tape[((size_t)w * nsub + k) * REC_WORDS + OFF_FLAGS]);
71
+ refact += (f & TAPE_REFACT) != 0; nonconv += (f & TAPE_NONCONV) != 0; sing += (f & TAPE_SINGULAR) != 0;
72
+ }
73
+ }
74
+ diag_add(d, D_FWD_UNSUPPORTED_WORLDS, unsup); diag_add(d, D_FWD_ITERATION_LIMIT_WORLDS, lim);
75
+ diag_add(d, D_REFACT_RECORDS, refact); diag_add(d, D_NONCONV_RECORDS, nonconv);
76
+ diag_add(d, D_SINGULAR_RECORDS, sing);
77
+ diag_add(d, D_FWD_CONTACT_OVERFLOW_WORLDS, ocon); diag_add(d, D_FWD_ROW_OVERFLOW_WORLDS, orow);
78
+ if (blockIdx.x == 0 && threadIdx.x == 0) {
79
+ atomicAdd(&d[D_FWD_CALLS], 1ull); atomicAdd(&d[D_FWD_WORLDS], (unsigned long long)nw);
80
+ if (tape) atomicAdd(&d[D_TAPE_RECORDS], (unsigned long long)nw * nsub);
81
+ }
82
+ }
83
+ __global__ void k_tdiag_bwd(unsigned long long* d, int nw, const float* gq, const float* gv, const float* gu,
84
+ const float* cq, const float* cv, int* info) {
85
+ unsigned rows = 0, rq = 0, rv = 0, ru = 0, rc = 0, rm = 0;
86
+ for (int w = blockIdx.x * blockDim.x + threadIdx.x; w < nw; w += gridDim.x * blockDim.x) {
87
+ unsigned b = (all_finite(gq + (size_t)w * NQ, NQ) ? 0u : (unsigned)NONFINITE_QPOS)
88
+ | (all_finite(gv + (size_t)w * NV, NV) ? 0u : (unsigned)NONFINITE_QVEL)
89
+ | (all_finite(gu + (size_t)w * NU, NU) ? 0u : (unsigned)NONFINITE_CTRL)
90
+ | (all_finite(cq + (size_t)w * NQ, NQ) && all_finite(cv + (size_t)w * NV, NV) ? 0u
91
+ : (unsigned)NONFINITE_COT);
92
+ int f = info[w];
93
+ info[w] = f | (int)(b << NONFINITE_SHIFT);
94
+ rows += (b & 7u) != 0; rq += (b & NONFINITE_QPOS) != 0; rv += (b & NONFINITE_QVEL) != 0;
95
+ ru += (b & NONFINITE_CTRL) != 0; rc += (b & NONFINITE_COT) != 0; rm += (f & ADJ_REPLAY_MISMATCH) != 0;
96
+ }
97
+ diag_add(d, D_NONFINITE_ROWS, rows); diag_add(d, D_NONFINITE_QPOS_ROWS, rq); diag_add(d, D_NONFINITE_QVEL_ROWS, rv);
98
+ diag_add(d, D_NONFINITE_CTRL_ROWS, ru); diag_add(d, D_NONFINITE_COTANGENT_ROWS, rc);
99
+ diag_add(d, D_REPLAY_MISMATCH_WORLDS, rm);
100
+ if (blockIdx.x == 0 && threadIdx.x == 0) {
101
+ atomicAdd(&d[D_BWD_CALLS], 1ull); atomicAdd(&d[D_BWD_ROWS], (unsigned long long)nw);
102
+ }
103
+ }
104
+ unsigned diag_grid(long long nw) { long long g = (nw + 255) / 256; return (unsigned)(g < 1 ? 1 : g > 160 ? 160 : g); }
105
+ } // namespace
106
+ extern "C" int dk_torch_diag_fwd(cudaStream_t st, unsigned long long* d, int nw, int nsub, int iterations,
107
+ const int* info, const float* tape) {
108
+ k_tdiag_fwd<<<diag_grid(nw), 256, 0, st>>>(d, nw, nsub, iterations, info, tape);
109
+ return (int)cudaGetLastError();
110
+ }
111
+ extern "C" int dk_torch_diag_bwd(cudaStream_t st, unsigned long long* d, int nw, const float* gq, const float* gv,
112
+ const float* gu, const float* cq, const float* cv, int* info) {
113
+ k_tdiag_bwd<<<diag_grid(nw), 256, 0, st>>>(d, nw, gq, gv, gu, cq, cv, info);
114
+ return (int)cudaGetLastError();
115
+ }
116
+ """
117
+
118
+
119
+ def _torch_unit(m, rec_words=None):
120
+ from nablaengine import engines
121
+ E = engines.modules(m)
122
+ g1_adjoint, g1_tape = E.adjoint, E.tape
123
+ defs = [f"#define {k} {v}" for k, v in (
124
+ ("NQ", m.nq), ("NV", m.nv), ("NU", m.nu), ("REC_WORDS", rec_words or g1_tape.rec_words(m)),
125
+ ("OFF_FLAGS", g1_tape.layout(m)["flags"][0]), ("TAPE_REFACT", f"{g1_tape.FLAG_REFACT}u"),
126
+ ("TAPE_NONCONV", f"{g1_tape.FLAG_NONCONV}u"), ("TAPE_SINGULAR", f"{g1_tape.FLAG_SINGULAR}u"),
127
+ ("ADJ_REPLAY_MISMATCH", g1_adjoint.ADJ_REPLAY_MISMATCH), ("NONFINITE_QPOS", NONFINITE_QPOS),
128
+ ("NONFINITE_QVEL", NONFINITE_QVEL), ("NONFINITE_CTRL", NONFINITE_CTRL), ("NONFINITE_COT", NONFINITE_COT),
129
+ ("NONFINITE_SHIFT", NONFINITE_SHIFT), ("OVERFLOW_CONTACTS", OVERFLOW_CONTACTS),
130
+ ("OVERFLOW_ROWS", OVERFLOW_ROWS))]
131
+ defs += [f"#define D_{name.upper()} {i}" for i, name in enumerate(DIAG)]
132
+ return TORCH_UNIT.replace("@DEFINES@", "\n".join(defs))
133
+
134
+
135
+ def cache_dir():
136
+ """$DK_CACHE_DIR, else $XDG_CACHE_HOME/nablaengine, else ~/.cache/nablaengine (as jax_ffi.cache_dir)."""
137
+ d = Path(os.environ.get("DK_CACHE_DIR") or Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
138
+ / "nablaengine")
139
+ d.mkdir(parents=True, exist_ok=True)
140
+ return d
141
+
142
+
143
+ def sources_sha256():
144
+ """sha256 over the package files the library is generated from (SOURCES, sorted by path) and the default model
145
+ files (the .mjb and its meta.json of $DK_FIXTURES, else of the checkout's fixtures/mjlab or the packaged copy)
146
+ where they are installed."""
147
+ from nablaengine import _paths
148
+ root = Path(__file__).resolve().parent
149
+ files = sorted({f for pat in SOURCES for f in root.glob(pat)})
150
+ fix = Path(os.environ.get("DK_FIXTURES") or _paths.default_fixtures())
151
+ files += [f for f in (fix / "g1_train.mjb", fix / "g1_meta.json") if f.exists()]
152
+ h = hashlib.sha256()
153
+ for f in files:
154
+ h.update(f.name.encode() + b"\0" + f.read_bytes() + b"\0")
155
+ return h.hexdigest()
156
+
157
+
158
+ def build(arch, model_dir=None, model=None, foot_pairs=None, set_current=True, terrain=None, com_body=None,
159
+ params=None, max_contacts=None, max_rows=None, motor_limits=None, contact_forces=False, actuator=None,
160
+ contact_surrogate=False, foot_wrench=None, contact_frame=False, contact_grad=False, noslip_pairs=None,
161
+ foot_normal=False, capacity_diag=False):
162
+ """Generate and compile the library for the model and architecture arch (sm_XY) and write its artifact into the
163
+ cache directory: the library libdk_g1_torch_<arch>_<key>.so (the CUDA runtime linked statically), the packed model
164
+ constants (.npy) and the model facts (.json); returns the .json's path. Needs mujoco 3.17 and nvcc (CUDA 12.x), no
165
+ torch and no JAX; cached (the same sources reuse the library). set_current: make it the architecture's artifact
166
+ that init() loads by default (torch_<arch>_current.json); False for another model's, loaded by its path. terrain:
167
+ a nablaengine.terrain.TerrainConfig for a terrain build (never made current; set_terrain() uploads the terrain).
168
+ com_body: the body that takes the per-world COM offset (as jax_ffi.init). params: per-world physics parameters
169
+ (as jax_ffi.init; never made current). max_contacts, max_rows: the capacities per world (as jax_ffi.init; a build
170
+ with them is never made current). actuator: an actuator model (nablaengine.actuators, as jax_ffi.init; never made
171
+ current); motor_limits: its permanent alias. contact_forces: the contact table with the forces (as jax_ffi.init; a G1 build with them is never made
172
+ current; "substeps", foot_wrench, contact_frame as jax_ffi.init). contact_surrogate: the backward's contact-gradient
173
+ surrogates (as jax_ffi.init; never made current). contact_grad: the contact output's VJP (as jax_ffi.init; never
174
+ made current). foot_normal: the foot / toe-weight contact words (as jax_ffi.init; never made current).
175
+ capacity_diag: the forward info's capacity counts, info (B, 6) (as jax_ffi.init; never made current)."""
176
+ import nablaengine
177
+ from nablaengine import jax_ffi
178
+ from nablaengine import actuators
179
+ from nablaengine.params import as_params
180
+ params, act = as_params(params), actuators.resolve(actuator, motor_limits, "torch_ffi.build")
181
+ motor = act.motor if act is not None else None
182
+ if params or act is not None:
183
+ set_current = False
184
+ from nablaengine import engines
185
+ m, fp, com = jax_ffi._model(model_dir, model, foot_pairs, com_body)
186
+ E = engines.modules(m)
187
+ actuators.check_engine(act, E.forest, "torch_ffi.build")
188
+ actuators.check_bam_build(act, "torch_ffi.build", terrain, params,
189
+ contact_forces or foot_wrench not in (None, False) or contact_frame)
190
+ m = actuators.prepare_model(act, m)
191
+ bam = act.bam if act is not None else None
192
+ g1_kin, g1_step, g1_tape = E.kinematics, E.step, E.tape
193
+ engines.require(m, fp, com, "torch_ffi.build")
194
+ mc_in, mr_in, mc, nefc = jax_ffi.capacity(m, terrain, max_contacts, max_rows)
195
+ if mc_in is not None or mr_in is not None:
196
+ set_current = False
197
+ cspec = jax_ffi.contact_spec(m, contact_forces, foot_wrench, contact_frame, terrain, foot_normal)
198
+ if cspec is None and contact_grad:
199
+ from nablaengine.g1_engine import contact_forces as _cf
200
+ cspec = _cf.as_spec("last", None, False, terrain is not None, m)
201
+ if cspec is not None:
202
+ contact_forces = cspec
203
+ set_current = False
204
+ if contact_surrogate or contact_grad or capacity_diag:
205
+ set_current = False
206
+ nsp = jax_ffi._noslip_pairs(m, fp, noslip_pairs)
207
+ if nsp is not None:
208
+ set_current = False
209
+ plan = jax_ffi.build_plan(m, fp, arch, terrain, com, params, mc_in, mr_in, motor, contact_forces,
210
+ **({"bam": bam} if bam is not None else {}),
211
+ **({"surrogate": True} if contact_surrogate else {}),
212
+ **({"contact_grad": True} if contact_grad else {}),
213
+ **({"noslip_pairs": nsp} if nsp is not None else {}),
214
+ **({"capacity_diag": True} if capacity_diag else {}))
215
+ if terrain is not None:
216
+ from nablaengine import terrain as _terrain
217
+ set_current = False
218
+ tgeoms = [[int(g), int(p), int(f)] for g, p, f in _terrain.robot_terrain_geoms(m, fp, terrain.geoms)]
219
+ units = {k: v for k, v in plan["units"].items() if k != "dk_ffi.cu"}
220
+ defines = {k: v for k, v in plan["defines"].items() if k in units}
221
+ unit_arch = {k: v for k, v in (plan["unit_arch"] or {}).items() if k in units}
222
+ rec = g1_tape.rec_words(m, mc, g1_tape.kind(terrain), mr_in, **({"motor": True} if motor is not None else {}))
223
+ if bam is not None:
224
+ rec += jax_ffi._bam_tape_words(m)
225
+ units["dk_torch.cu"], defines["dk_torch.cu"] = _torch_unit(m, rec), []
226
+ if capacity_diag:
227
+ from nablaengine._optional import FOREST, load as _load
228
+ _capd = _load("nablaengine.forest_engine", FOREST, "capacity_diag")
229
+ units["dk_torch.cu"] = _capd.torch_unit(units["dk_torch.cu"])
230
+ nov = terrain.velocity_words() + terrain.material_words() if terrain is not None else 0
231
+ if params or nov:
232
+ gw = m.nu + (params.width(m.nv) + 1 if params else 0) + nov
233
+ units["dk_torch.cu"] = units["dk_torch.cu"].replace("all_finite(gu + (size_t)w * NU, NU)",
234
+ f"all_finite(gu + (size_t)w * {gw}, {gw})")
235
+ if unit_arch:
236
+ adj = unit_arch.get(f"{_tag(VARIANTS[0])}.cu")
237
+ if adj:
238
+ unit_arch["dk_torch.cu"] = adj
239
+ consts = np.ascontiguousarray(plan["consts"], np.float32)
240
+ path, built, key = jax_ffi._build(units, defines, arch, None, consts, unit_arch or None, prefix="libdk_g1_torch")
241
+ try:
242
+ g1_kin.check_model(m)
243
+ kin_error = None
244
+ except AssertionError as e:
245
+ kin_error = f"the model does not meet the kinematics outputs' assumptions ({e!r})"
246
+ stem = path.with_suffix("")
247
+ np.save(stem.with_suffix(".npy"), consts)
248
+ meta = dict(artifact_version=ARTIFACT_VERSION, engine=E.name, adj_stage=jax_ffi.adj_stage(E),
249
+ com_layout=jax_ffi.com_layout(m, terrain, params), com_body=com, library=path.name, consts=stem.with_suffix(".npy").name, key=key,
250
+ arch=arch, version=nablaengine.__version__, sources_sha256=sources_sha256(),
251
+ terrain=terrain.key() if terrain is not None else None,
252
+ terrain_geoms=tgeoms if terrain is not None else None,
253
+ com_words=(((g1_step.com_words(m) if E.forest else 3) + (terrain.com_words() - 3 if terrain is not None else 0))
254
+ + params.width(m.nv)),
255
+ params=params.key() if params else None, param_words=params.width(m.nv) if params else 0,
256
+ obj_vel_words=terrain.velocity_words() if terrain is not None else 0,
257
+ obj_mat_words=terrain.material_words() if terrain is not None else 0,
258
+ motor_limits=motor.key(m) if motor is not None else None,
259
+ actuator=act.key(m) if act is not None else None, **jax_ffi._act_info(m, bam),
260
+ clamp_implicit=(list(E.step.clamp_implicit()) if hasattr(E.step, "clamp_implicit") else None),
261
+ tree_chol=None if E.forest else g1_step.tree_chol_stages(m),
262
+ tree_chol_mode=os.environ.get("DK_TREE_CHOL") or "0",
263
+ con_words=jax_ffi.con_words(m, contact_forces), contact_forces=jax_ffi.contact_info(m, cspec),
264
+ contact_surrogate=bool(contact_surrogate), contact_grad=bool(contact_grad), noslip_pairs=list(nsp) if nsp is not None else None,
265
+ capacity_diag=bool(capacity_diag), info_words=6 if capacity_diag else 4,
266
+ consts_sha256=hashlib.sha256(consts.tobytes()).hexdigest(), rec_words=rec,
267
+ nq=m.nq, nv=m.nv, nu=m.nu, nbody=m.nbody,
268
+ maxcon=mc, nefc=nefc, elliptic=bool(int(m.opt.cone) == 1),
269
+ off_flags=int(g1_tape.layout(m)["flags"][0]), forward_unit=plan["forward_unit"],
270
+ variants=[list(v) for v in VARIANTS], kinematics_error=kin_error, timestep=float(m.opt.timestep),
271
+ foot_pairs=[int(p) for p in fp], arch_flags=plan["arch_flags"],
272
+ forward_defines=plan["forward_defines"], built=built,
273
+ default_model=model_dir is None and model is None)
274
+ js = stem.with_suffix(".json")
275
+ js.write_text(json.dumps(meta, indent=1) + "\n")
276
+ if set_current:
277
+ (cache_dir() / f"torch_{arch}_current.json").write_text(json.dumps({"artifact": js.name}) + "\n")
278
+ return js
279
+
280
+
281
+ def _artifact_path(arch, artifact):
282
+ a = artifact or os.environ.get("DK_TORCH_ARTIFACT")
283
+ if a:
284
+ return Path(a)
285
+ ptr = cache_dir() / f"torch_{arch}_current.json"
286
+ return cache_dir() / json.loads(ptr.read_text())["artifact"] if ptr.exists() else None
287
+
288
+
289
+ def _stale(js, arch):
290
+ if js is None or not js.exists():
291
+ return "no artifact"
292
+ meta = json.loads(js.read_text())
293
+ if meta.get("artifact_version") != ARTIFACT_VERSION:
294
+ return f"artifact version {meta.get('artifact_version')}, this module reads {ARTIFACT_VERSION}"
295
+ if meta["arch"] != arch:
296
+ return f"built for {meta['arch']}, the GPU is {arch}"
297
+ if not (js.parent / meta["library"]).exists() or not (js.parent / meta["consts"]).exists():
298
+ return "its library or constants file is missing"
299
+ if meta.get("default_model") and meta["sources_sha256"] != sources_sha256():
300
+ return "built from other package sources (the package changed since): rebuild it"
301
+ if meta.get("tree_chol_mode", "0") != (os.environ.get("DK_TREE_CHOL") or "0"):
302
+ return f"built with DK_TREE_CHOL={meta.get('tree_chol_mode', '0')}, the environment has another value"
303
+ return None
304
+
305
+
306
+ def init(device=None, artifact=None, model_dir=None, model=None, foot_pairs=None, terrain=None, com_body=None,
307
+ params=None, max_contacts=None, max_rows=None, motor_limits=None, contact_forces=False, actuator=None,
308
+ contact_surrogate=False, foot_wrench=None, contact_frame=False, contact_grad=False, noslip_pairs=None,
309
+ foot_normal=False, capacity_diag=False):
310
+ """Load the library and upload the model constants to device (default torch's current CUDA device); idempotent
311
+ per device, one library per process. The library comes from an artifact (build()): artifact (a .json path),
312
+ else $DK_TORCH_ARTIFACT, else the cache's current artifact for the GPU's architecture. Loading an artifact needs
313
+ torch, NumPy and the NVIDIA driver only: no nvcc, mujoco or JAX. Without a usable artifact (none, or one of other
314
+ package sources), init() builds one first (mujoco and nvcc needed then). model_dir / model / foot_pairs: another
315
+ model than the default (as jax_ffi.init): built (or found in the cache) for it, not made current. Returns the
316
+ artifact's facts (path, key, arch, sizes, ...; engine, adj_stage, com_body, com_layout as jax_ffi.init's, lists
317
+ for tuples). The first call on a device synchronizes it once: call this
318
+ before capturing a CUDA graph. terrain: a nablaengine.terrain.TerrainConfig: a terrain build (in progress;
319
+ set_terrain() uploads the terrain data; raycast() measures it). params: per-world physics parameters
320
+ (nablaengine.params.PhysicsParams or field names; com is then (B, info["com_words"]), as jax_ffi.init).
321
+ max_contacts, max_rows: the contact and constraint-row capacity per world (as jax_ffi.init; info["maxcon"] /
322
+ info["nefc"]). actuator: an actuator model (nablaengine.actuators, e.g. "unitree_g1"; as jax_ffi.init;
323
+ info["actuator"], info["motor_limits"]); motor_limits: its permanent alias. contact_forces: the contact table with
324
+ the forces (as jax_ffi.init; info["con_words"] 12; "substeps", foot_wrench, contact_frame as jax_ffi.init,
325
+ info["contact_forces"]). contact_surrogate: the backward's contact-gradient surrogates
326
+ (as jax_ffi.init; step / backward cone_mu=, impulse_clip=). contact_grad: the contact output's VJP (as
327
+ jax_ffi.init: step(contacts=True) returns a differentiable contact output, backward(g_contacts=)). foot_normal:
328
+ the foot / toe-weight contact words and contact_table()'s foot_normal (as jax_ffi.init). capacity_diag: the forward
329
+ info's capacity counts, info (B, 6) (as jax_ffi.init; capacity_counts())."""
330
+ import torch
331
+ dev = _device_index(device)
332
+ with _LOCK:
333
+ if not _STATE:
334
+ _load(torch, dev, artifact, model_dir, model, foot_pairs, terrain, com_body, params, max_contacts, max_rows,
335
+ motor_limits, contact_forces, actuator, contact_surrogate, foot_wrench, contact_frame, contact_grad, noslip_pairs,
336
+ foot_normal, capacity_diag)
337
+ elif (artifact is not None or model_dir is not None or model is not None or terrain is not None
338
+ or params is not None or max_contacts is not None or max_rows is not None
339
+ or motor_limits is not None or actuator is not None or contact_forces or contact_surrogate
340
+ or foot_wrench not in (None, False) or contact_frame or contact_grad
341
+ or noslip_pairs is not None or foot_normal or capacity_diag):
342
+ raise _err("init(artifact / model ...) after the library is loaded: one library per process", RuntimeError)
343
+ cc = torch.cuda.get_device_capability(dev)
344
+ if f"sm_{cc[0]}{cc[1]}" != _STATE["info"]["arch"]:
345
+ raise _err(f"cuda:{dev} is sm_{cc[0]}{cc[1]}, the loaded library is {_STATE['info']['arch']} (one "
346
+ "architecture per process)", RuntimeError)
347
+ if dev not in _READY:
348
+ _upload(dev)
349
+ return _STATE["info"]
350
+
351
+
352
+ def _load(torch, dev, artifact, model_dir, model, foot_pairs, terrain=None, com_body=None, params=None,
353
+ max_contacts=None, max_rows=None, motor_limits=None, contact_forces=False, actuator=None,
354
+ contact_surrogate=False, foot_wrench=None, contact_frame=False, contact_grad=False, noslip_pairs=None,
355
+ foot_normal=False, capacity_diag=False):
356
+ cc = torch.cuda.get_device_capability(dev)
357
+ arch = os.environ.get("DK_ARCH") or f"sm_{cc[0]}{cc[1]}"
358
+ if (model_dir is not None or model is not None or terrain is not None or params or max_contacts is not None
359
+ or max_rows is not None or motor_limits is not None or actuator is not None or contact_forces
360
+ or contact_surrogate or foot_wrench not in (None, False) or contact_frame or contact_grad
361
+ or noslip_pairs is not None or foot_normal or capacity_diag):
362
+ js = build(arch, model_dir, model, foot_pairs, set_current=False, terrain=terrain, com_body=com_body,
363
+ params=params, max_contacts=max_contacts, max_rows=max_rows, motor_limits=motor_limits,
364
+ contact_forces=contact_forces, actuator=actuator, contact_surrogate=contact_surrogate,
365
+ foot_wrench=foot_wrench, contact_frame=contact_frame, contact_grad=contact_grad,
366
+ noslip_pairs=noslip_pairs, **({"foot_normal": True} if foot_normal else {}),
367
+ **({"capacity_diag": True} if capacity_diag else {}))
368
+ else:
369
+ js = _artifact_path(arch, artifact)
370
+ why = _stale(js, arch)
371
+ if why and artifact is not None:
372
+ raise _err(f"artifact {js}: {why}", RuntimeError)
373
+ if why:
374
+ try:
375
+ js = build(arch)
376
+ except ImportError as e:
377
+ raise _err(f"no usable artifact for {arch} ({why}), and building one needs mujoco 3.17 and nvcc: "
378
+ f"run `python -m nablaengine.torch_ffi build` where they are installed, or set "
379
+ f"DK_TORCH_ARTIFACT ({e})", RuntimeError) from e
380
+ meta = json.loads(js.read_text())
381
+ consts = np.ascontiguousarray(np.load(js.parent / meta["consts"]), np.float32)
382
+ if hashlib.sha256(consts.tobytes()).hexdigest() != meta["consts_sha256"]:
383
+ raise _err(f"{meta['consts']} does not match its artifact {js}", RuntimeError)
384
+ lib = ctypes.cdll.LoadLibrary(str(js.parent / meta["library"]))
385
+ info = dict(meta, path=str(js.parent / meta["library"]), artifact=str(js))
386
+ info.setdefault("actuator", None)
387
+ info.setdefault("act_words", 0)
388
+ info.setdefault("act_layout", None)
389
+ info.setdefault("bam", None)
390
+ info.setdefault("contact_surrogate", False)
391
+ info.setdefault("noslip_pairs", None)
392
+ info.setdefault("contact_forces", None)
393
+ info.setdefault("capacity_diag", False)
394
+ info.setdefault("info_words", 4)
395
+ fns = _bind(lib, info)
396
+ _STATE.update(lib=lib, info=info, fns=fns, consts=consts, off_flags=int(meta["off_flags"]))
397
+ import atexit
398
+ atexit.register(_exit_report)
399
+ _custom_ops()
400
+
401
+
402
+ _TERRAIN = {}
403
+
404
+
405
+ def set_terrain(terrain, device=None, cell=1.0):
406
+ """Upload a nablaengine.terrain.Terrain to device (default the current one) for a terrain build (init(terrain=));
407
+ replaces the previous one on that device. cell: the broad-phase grid's cell size in metres."""
408
+ import torch
409
+ dev = _device_index(device)
410
+ init(dev)
411
+ if "set_terrain" not in _STATE["fns"]:
412
+ raise _err("set_terrain needs a terrain build: init(terrain=TerrainConfig(...))", RuntimeError)
413
+ packed = terrain.pack(cell)
414
+ from nablaengine import jax_ffi
415
+ jax_ffi._terrain_material_check(packed, _STATE["info"])
416
+ packed["material"] = terrain.material_upload(_STATE["info"].get("terrain"))
417
+ _STATE["terrain_sand"] = packed["sand"]
418
+ order = ("boxes", "hf_head", "hf_int", "hf_data", "grid", "cell_start", "cell_items", "elem_cell", "material")
419
+ with torch.cuda.device(dev):
420
+ tens = {k: torch.from_numpy(np.ascontiguousarray(packed[k]).reshape(-1)).to(f"cuda:{dev}") for k in order}
421
+ for k in order:
422
+ if tens[k].numel() == 0:
423
+ tens[k] = torch.zeros(1, dtype=tens[k].dtype, device=f"cuda:{dev}")
424
+ ptrs = (ctypes.c_void_p * 9)(*[tens[k].data_ptr() for k in order])
425
+ for f in _STATE["fns"]["set_terrain"]:
426
+ _rc(f(dev, ctypes.cast(ptrs, ctypes.c_void_p)), "the terrain upload")
427
+ torch.cuda.synchronize(dev)
428
+ _TERRAIN[dev] = tens
429
+
430
+
431
+
432
+
433
+ def grid_pattern(size=(1.0, 1.0), resolution=0.1, direction=(0.0, 0.0, -1.0), device=None):
434
+ """(offsets (N, 3), directions (N, 3)) of a grid of parallel rays in the frame, as mjlab's
435
+ GridPatternCfg(size, resolution, direction).generate_rays."""
436
+ import torch
437
+ x = torch.arange(-size[0] / 2, size[0] / 2 + resolution * 0.5, resolution, device=device, dtype=torch.float32)
438
+ y = torch.arange(-size[1] / 2, size[1] / 2 + resolution * 0.5, resolution, device=device, dtype=torch.float32)
439
+ gx, gy = torch.meshgrid(x, y, indexing="xy")
440
+ off = torch.zeros((gx.numel(), 3), device=device, dtype=torch.float32)
441
+ off[:, 0], off[:, 1] = gx.flatten(), gy.flatten()
442
+ d = torch.tensor(direction, device=device, dtype=torch.float32)
443
+ return off, (d / d.norm()).unsqueeze(0).expand(gx.numel(), 3).clone()
444
+
445
+
446
+ def _yaw_rotation(rot):
447
+ import torch
448
+ x = rot[:, :, 0].clone()
449
+ x[:, 2] = 0
450
+ xn = x.norm(dim=1)
451
+ sing = xn < 0.1
452
+ if sing.any():
453
+ y = rot[:, :, 1].clone()
454
+ y[:, 2] = 0
455
+ y = y / y.norm(dim=1).clamp(min=1e-6).unsqueeze(-1)
456
+ xy = torch.zeros_like(y)
457
+ xy[:, 0], xy[:, 1] = y[:, 1], -y[:, 0]
458
+ x[sing] = xy[sing]
459
+ xn[sing] = 1.0
460
+ x = x / xn.clamp(min=1e-6).unsqueeze(-1)
461
+ out = torch.zeros((rot.shape[0], 3, 3), device=rot.device, dtype=rot.dtype)
462
+ out[:, 0, 0], out[:, 1, 0], out[:, 0, 1], out[:, 1, 1], out[:, 2, 2] = x[:, 0], x[:, 1], -x[:, 1], x[:, 0], 1
463
+ return out
464
+
465
+
466
+ def raycast(pos, rot, offsets, directions, alignment="base", max_distance=10.0):
467
+ """Height scan / depth rays against the terrain of a terrain build (set_terrain), as mjlab's RayCastSensor: rays
468
+ from the frame at pos (B, 3) with rotation rot (B, 3, 3; e.g. a body's from kinematics()), pattern offsets and unit
469
+ directions (N, 3) in the frame (grid_pattern), alignment "base" (the frame's rotation), "yaw" (its yaw only) or
470
+ "world" (none). Returns dict(distances (B, N): to the nearest terrain hit, -1 for none or beyond max_distance,
471
+ normals_w (B, N, 3): its world normal (0 for none), hit_pos_w (B, N, 3): the hit (the ray origin for none)).
472
+ Only the terrain is hit (not the robot's geoms); forward only (no gradient). Intersections are MuJoCo Warp's
473
+ ray_box / ray_hfield."""
474
+ import torch
475
+ dev = _device_index(pos.device)
476
+ init(dev)
477
+ if "terrain_rays" not in _STATE["fns"]:
478
+ raise _err("raycast needs a terrain build: init(terrain=TerrainConfig(...)) and set_terrain()", RuntimeError)
479
+ if alignment == "base":
480
+ R = rot
481
+ elif alignment == "yaw":
482
+ R = _yaw_rotation(rot)
483
+ elif alignment == "world":
484
+ R = torch.eye(3, device=rot.device, dtype=rot.dtype).unsqueeze(0).expand(rot.shape[0], -1, -1)
485
+ else:
486
+ raise ValueError(f"alignment {alignment!r}: 'base', 'yaw' or 'world'")
487
+ B, N = pos.shape[0], offsets.shape[0]
488
+ origins = (pos.unsqueeze(1) + torch.einsum("bij,nj->bni", R, offsets)).contiguous()
489
+ rays = torch.einsum("bij,nj->bni", R, directions).contiguous()
490
+ dist = torch.empty((B, N), dtype=torch.float32, device=pos.device)
491
+ nrm = torch.empty((B, N, 3), dtype=torch.float32, device=pos.device)
492
+ with torch.cuda.device(dev):
493
+ st = torch.cuda.current_stream(dev).cuda_stream
494
+ _rc(_STATE["fns"]["terrain_rays"](st, B * N, origins.data_ptr(), rays.data_ptr(), float(max_distance),
495
+ dist.data_ptr(), nrm.data_ptr()), "the terrain rays")
496
+ hit = dist >= 0
497
+ hit_pos = torch.where(hit.unsqueeze(-1), origins + rays * dist.clamp(min=0).unsqueeze(-1), origins)
498
+ return dict(distances=dist, normals_w=nrm, hit_pos_w=hit_pos)
499
+
500
+ def _device_index(device):
501
+ import torch
502
+ if device is None:
503
+ return torch.cuda.current_device()
504
+ d = torch.device(device)
505
+ if d.type != "cuda":
506
+ raise _err(f"device must be a CUDA device, got {d}")
507
+ return torch.cuda.current_device() if d.index is None else d.index
508
+
509
+
510
+ def _bind(lib, info):
511
+ vp, i32, f32 = ctypes.c_void_p, ctypes.c_int, ctypes.c_float
512
+ fwd = info["forward_unit"]
513
+ fns = dict(forward=getattr(lib, f"{fwd}_forward"), work_bytes=getattr(lib, f"{fwd}_work_bytes"),
514
+ kin=getattr(lib, f"{fwd}_kinematics"), kin_vjp=getattr(lib, f"{fwd}_kinematics_vjp"))
515
+ fns["forward"].argtypes = [vp, i32] + [vp] * 6 + [i32, i32] + [vp] * (9 if info.get("act_words") else 7)
516
+ fns["work_bytes"].argtypes, fns["work_bytes"].restype = [i32], ctypes.c_longlong
517
+ fns["kin"].argtypes = [vp, i32] + [vp] * 8
518
+ fns["kin_vjp"].argtypes = [vp, i32] + [vp] * 12
519
+ fns["adjoint"] = {}
520
+ for v in VARIANTS:
521
+ t = _tag(v)
522
+ f = getattr(lib, f"{t}_adjoint")
523
+ f.argtypes = ([vp, i32, i32] + [vp] * 9 + [vp, f32] + ([vp] * 3 if info.get("act_words") else [])
524
+ + ([f32, f32] if info.get("contact_surrogate") else [])
525
+ + ([vp] if info.get("contact_grad") else []))
526
+ fns["adjoint"][v] = f
527
+ sz = np.zeros(9, np.int64)
528
+ getattr(lib, f"{t}_sizes").argtypes = [vp]
529
+ getattr(lib, f"{t}_sizes")(sz.ctypes.data)
530
+ want = (info["rec_words"], info["nq"], info["nv"], info["maxcon"], v[0], v[1], info["off_flags"])
531
+ if tuple(int(x) for x in sz[2:9]) != tuple(int(x) for x in want):
532
+ raise _err(f"unit {t}: compiled sizes {sz.tolist()} do not match the artifact {want}", RuntimeError)
533
+ units = [_tag(v) for v in VARIANTS] + ([fwd] if fwd == FWD_UNIT else [])
534
+ fns["upload"] = []
535
+ for u in units:
536
+ f = getattr(lib, f"{u}_upload")
537
+ f.argtypes = [vp, vp]
538
+ fns["upload"].append((u, f))
539
+ if info.get("terrain"):
540
+ fns["set_terrain"] = []
541
+ for u in units:
542
+ f = getattr(lib, f"{u}_set_terrain")
543
+ f.argtypes = [i32, vp]
544
+ fns["set_terrain"].append(f)
545
+ fns["terrain_rays"] = getattr(lib, f"{units[0]}_terrain_rays")
546
+ fns["terrain_rays"].argtypes = [vp, i32, vp, vp, f32, vp, vp]
547
+ for name in ("dk_torch_diag_fwd", "dk_torch_diag_bwd"):
548
+ fns[name] = getattr(lib, name)
549
+ fns["dk_torch_diag_fwd"].argtypes = [vp, vp, i32, i32, i32, vp, vp]
550
+ fns["dk_torch_diag_bwd"].argtypes = [vp, vp, i32] + [vp] * 6
551
+ return fns
552
+
553
+
554
+ def _upload(dev):
555
+ import torch
556
+ with torch.cuda.device(dev):
557
+ if torch.cuda.is_current_stream_capturing():
558
+ raise _err(f"the model constants are not on cuda:{dev} yet: call torch_ffi.init({dev}) before capturing a "
559
+ "CUDA graph", RuntimeError)
560
+ st = torch.cuda.current_stream(dev)
561
+ c = _STATE["consts"]
562
+ for unit, f in _STATE["fns"]["upload"]:
563
+ rc = f(c.ctypes.data, st.cuda_stream)
564
+ if rc:
565
+ raise _err(f"constant upload of {unit} on cuda:{dev} failed ({rc})", RuntimeError)
566
+ st.synchronize()
567
+ _DIAG[dev] = torch.zeros(len(DIAG), dtype=torch.int64, device=f"cuda:{dev}")
568
+ _READY.add(dev)
569
+
570
+
571
+ def _ready(t):
572
+ dev = t.device.index
573
+ if dev not in _READY:
574
+ init(dev)
575
+ return dev
576
+
577
+
578
+ def _on(dev):
579
+ import contextlib
580
+ import torch
581
+ return contextlib.nullcontext() if torch.cuda.current_device() == dev else torch.cuda.device(dev)
582
+
583
+
584
+ def _on_input_device(fn):
585
+ import functools
586
+
587
+ @functools.wraps(fn)
588
+ def run(first, *args):
589
+ if getattr(first, "is_cuda", False):
590
+ with _on(first.device.index):
591
+ return fn(first, *args)
592
+ return fn(first, *args)
593
+ return run
594
+
595
+
596
+ def _ptr(t):
597
+ return None if t is None else ctypes.c_void_p(t.data_ptr())
598
+
599
+
600
+ def _check(name, x, shape, dev, dtype=None):
601
+ import torch
602
+ dtype = dtype or torch.float32
603
+ if not isinstance(x, torch.Tensor):
604
+ raise _err(f"{name} must be a torch.Tensor, got {type(x).__name__}")
605
+ if x.dtype != dtype or tuple(x.shape) != tuple(shape) or x.device.type != "cuda" or not x.is_contiguous():
606
+ raise _err(f"{name} must be a contiguous {dtype} CUDA tensor {tuple(shape)}, got {x.dtype} {tuple(x.shape)} on "
607
+ f"{x.device}{'' if x.is_contiguous() else ' (not contiguous)'}")
608
+ if dev is not None and x.device.index != dev:
609
+ raise _err(f"{name} is on {x.device}, the other tensors on cuda:{dev}")
610
+
611
+
612
+ def _rc(rc, what):
613
+ if rc:
614
+ raise _err(f"{what} failed (CUDA error {rc})", RuntimeError)
615
+
616
+
617
+ def _soft(clamp_kv, clamp_soft):
618
+ if int(clamp_kv) != 2:
619
+ if clamp_soft is not None:
620
+ raise _err(f"clamp_soft is the soft clamp's (clamp_kv=2), not clamp_kv={clamp_kv}", ValueError)
621
+ return None
622
+ d = float(CLAMP_SOFT if clamp_soft is None else clamp_soft)
623
+ if not (math.isfinite(d) and d >= 0.0):
624
+ raise _err(f"clamp_soft must be finite and >= 0, got {clamp_soft}", ValueError)
625
+ return d
626
+
627
+
628
+ def _sur(cone_mu, impulse_clip):
629
+ mu = float(np.float32(cone_mu or 0.0))
630
+ if not (math.isfinite(mu) and mu >= 0.0):
631
+ raise _err(f"cone_mu must be finite and >= 0, got {cone_mu}", ValueError)
632
+ if impulse_clip is None:
633
+ return mu, 0.0
634
+ clip = float(np.float32(impulse_clip))
635
+ if not clip > 0.0:
636
+ raise _err(f"impulse_clip must be > 0 (None: off), got {impulse_clip}", ValueError)
637
+ return mu, (0.0 if clip == math.inf else clip)
638
+
639
+
640
+ def _com_words():
641
+ return int(_STATE["info"].get("com_words", 3)) if _STATE else 3
642
+
643
+
644
+ _LAST_CON = {}
645
+
646
+
647
+ def last_contacts(device=None):
648
+ """The contacts of the last substep of the most recent forward / step on device (default the current one), as a
649
+ dict of tensors over (B, maxcon): valid (pair >= 0), pair (the model's contact pair index; -1 past the world's
650
+ contacts), dist, pos (world), normal (world, the contact frame's first axis); with the forest engine also force
651
+ (the contact force in world coordinates, on the pair's second geom in the engine's geom order: the frame's normal
652
+ points from the first geom to the second) and force_normal (its normal component, >= 0). Overwritten by the next
653
+ forward on the device; not differentiable. None before any forward."""
654
+ con = _LAST_CON.get(_device_index(device))
655
+ return None if con is None else contact_table(con)
656
+
657
+
658
+ def contact_table(con, substeps=None):
659
+ """The contact output of forward / step (contacts=True), (B, width), as last_contacts' dict (and as
660
+ jax_ffi.contact_table: per-substep tables, foot wrenches, tangents, terrain element with those options)."""
661
+ import torch
662
+ from nablaengine.g1_engine import contact_forces as _cf
663
+ out = _cf.decode(con, _STATE["info"], substeps, _STATE.get("terrain_sand"))
664
+ out["pair"] = out["pair"].to(torch.int32)
665
+ out["valid"] = out["pair"] >= 0
666
+ return out
667
+
668
+
669
+ def _sizes():
670
+ i = _STATE["info"]
671
+ return i["nq"], i["nv"], i["nu"], i["nbody"], i["rec_words"]
672
+
673
+
674
+ def tape_bytes(nworld, substeps=SUBSTEPS, steps=1):
675
+ """Bytes of the tapes of `steps` differentiated control steps."""
676
+ if not _STATE:
677
+ init()
678
+ return 4 * _STATE["info"]["rec_words"] * substeps * nworld * steps
679
+
680
+
681
+
682
+ @_on_input_device
683
+ def _forward_impl(qpos, qvel, warm, ctrl, friction, com, iterations, substeps, tape, kinematics, act=None):
684
+ import torch
685
+ dev = _ready(qpos)
686
+ nq, nv, nu, nb, rec = _sizes()
687
+ B = qpos.shape[0]
688
+ for name, x, shape in (("qpos", qpos, (B, nq)), ("qvel", qvel, (B, nv)), ("warm", warm, (B, nv)),
689
+ ("ctrl", ctrl, (B, nu)), ("friction", friction, (B,)), ("com", com, (B, _com_words()))):
690
+ _check(name, x, shape, dev)
691
+ aw = int(_STATE["info"].get("act_words", 0))
692
+ if aw and act is None:
693
+ raise _err(f"this build has the BAM servo model: pass its state act= (B, {aw}) float32 "
694
+ "(nablaengine.actuators.bam.initial_state; docs/actuators.md)", ValueError)
695
+ if not aw and act is not None:
696
+ raise _err("act= is the state of a stateful actuator model (actuator='bam'); this build has none", ValueError)
697
+ if aw:
698
+ _check("act", act, (B, aw), dev)
699
+ if kinematics:
700
+ raise _err("kinematics=True is not available with the BAM servo model yet", ValueError)
701
+ if substeps < 1 or substeps > 32 or iterations < 0:
702
+ raise _err("substeps in 1..32 and iterations >= 0", ValueError)
703
+ kw = dict(dtype=torch.float32, device=qpos.device)
704
+ q1, v1, w1 = torch.empty((B, nq), **kw), torch.empty((B, nv), **kw), torch.empty((B, nv), **kw)
705
+ info = torch.empty((B, int(_STATE["info"]["info_words"])), dtype=torch.int32, device=qpos.device)
706
+ tp = torch.empty((B, substeps * rec), **kw) if tape else torch.empty((0, substeps * rec), **kw)
707
+ kin = _kin_empty(B, qpos.device) if kinematics else []
708
+ oact = [torch.empty((B, aw), **kw)] if aw else []
709
+ if B == 0:
710
+ return [q1, v1, w1, info, tp] + kin + oact
711
+ fns = _STATE["fns"]
712
+ con = torch.empty((B, _con_width(substeps)), **kw)
713
+ _LAST_CON[dev] = con
714
+ work = torch.empty((max(int(fns["work_bytes"](B)), 1),), dtype=torch.uint8, device=qpos.device)
715
+ st = torch.cuda.current_stream(dev).cuda_stream
716
+ _rc(fns["forward"](st, B, *map(_ptr, (qpos, qvel, warm, ctrl, friction, com)), iterations, substeps, _ptr(q1),
717
+ _ptr(v1), _ptr(w1), _ptr(info), _ptr(con), _ptr(tp) if tape else None,
718
+ *((_ptr(act), _ptr(oact[0])) if aw else ()), _ptr(work)),
719
+ "the forward launch")
720
+ if kinematics:
721
+ _rc(fns["kin"](st, B, _ptr(q1), _ptr(v1), _ptr(com), *map(_ptr, kin)), "the kinematics launch")
722
+ if _DIAG_ON[0]:
723
+ _diag_forward(dev, st, info, tp if tape else None, iterations, substeps)
724
+ return [q1, v1, w1, info, tp] + kin + oact
725
+
726
+
727
+ def _kin_empty(B, device):
728
+ import torch
729
+ nq, _, _, nb, _ = _sizes()
730
+ return [torch.empty(s, dtype=torch.float32, device=device) for s in
731
+ ((B, nq), (B, nb, 3), (B, nb, 4), (B, nb, 6), (B, nb, 3))]
732
+
733
+
734
+ @_on_input_device
735
+ def _backward_impl(tape, friction, com, g_qpos, g_qvel, ctrl, kin_state, kin_cot, substeps, clamp_kv, normal,
736
+ clamp_soft, act=None, g_act=None, cone_mu=0.0, impulse_clip=0.0, g_contacts=None):
737
+ import torch
738
+ dev = _ready(tape)
739
+ nq, nv, nu, nb, rec = _sizes()
740
+ B = tape.shape[0]
741
+ for name, x, shape in (("tape", tape, (B, substeps * rec)), ("friction", friction, (B,)), ("com", com, (B, _com_words())),
742
+ ("g_qpos", g_qpos, (B, nq)), ("g_qvel", g_qvel, (B, nv))):
743
+ _check(name, x, shape, dev)
744
+ v = (int(clamp_kv), int(normal))
745
+ if v not in VARIANTS:
746
+ raise _err(f"no adjoint variant clamp_kv={clamp_kv} normal={normal}", ValueError)
747
+ aw = int(_STATE["info"].get("act_words", 0))
748
+ if aw:
749
+ if act is None:
750
+ raise _err(f"this build has the BAM servo model: backward needs the step's input state act= (B, {aw})",
751
+ ValueError)
752
+ if v[0] == 2 or kin_state:
753
+ raise _err("the BAM servo model's adjoint: clamp_kv 0 or 1 (the same there: its servo force has no kv), "
754
+ "no kinematics outputs", ValueError)
755
+ if g_act is None:
756
+ g_act = torch.zeros((B, aw), dtype=torch.float32, device=tape.device)
757
+ _check("act", act, (B, aw), dev)
758
+ _check("g_act", g_act, (B, aw), dev)
759
+ elif act is not None or g_act is not None:
760
+ raise _err("act= / g_act= belong to a build with the BAM servo model", ValueError)
761
+ if (v[0] == 2) != (ctrl is not None):
762
+ raise _err("clamp_kv=2 (the soft clamp) needs the step's ctrl; 0 and 1 take none", ValueError)
763
+ sur = _STATE["info"].get("contact_surrogate")
764
+ if not sur and (cone_mu or impulse_clip):
765
+ raise _err("cone_mu / impulse_clip need a library built with init(contact_surrogate=True)", ValueError)
766
+ if ctrl is not None:
767
+ _check("ctrl", ctrl, (B, nu), dev)
768
+ cgrad = bool(_STATE["info"].get("contact_grad"))
769
+ if g_contacts is not None:
770
+ if not cgrad:
771
+ raise _err("g_contacts needs a library built with init(contact_grad=True)", ValueError)
772
+ _check("g_contacts", g_contacts, (B, _con_width(substeps)), dev)
773
+ kw = dict(dtype=torch.float32, device=tape.device)
774
+ npw = int(_STATE["info"].get("param_words", 0))
775
+ nov = int(_STATE["info"].get("obj_vel_words", 0))
776
+ nov += int(_STATE["info"].get("obj_mat_words", 0))
777
+ gq, gv = torch.empty((B, nq), **kw), torch.empty((B, nv), **kw)
778
+ gu = torch.empty((B, nu + (npw + 1 if npw else 0) + nov), **kw)
779
+ info = torch.empty((B,), dtype=torch.int32, device=tape.device)
780
+ ga = [torch.empty((B, aw), **kw)] if aw else []
781
+ if B == 0:
782
+ return [gq, gv, gu, info] + ga
783
+ fns = _STATE["fns"]
784
+ st = torch.cuda.current_stream(dev).cuda_stream
785
+ cq, cv = g_qpos, g_qvel
786
+ if kin_state:
787
+ q1, v1 = kin_state
788
+ _check("qpos'", q1, (B, nq), dev)
789
+ _check("qvel'", v1, (B, nv), dev)
790
+ for name, x, shape in zip(("g_qpos_n", "g_xpos", "g_xquat", "g_cvel", "g_subtree_com"), kin_cot,
791
+ ((B, nq), (B, nb, 3), (B, nb, 4), (B, nb, 6), (B, nb, 3))):
792
+ _check(name, x, shape, dev)
793
+ cq, cv = torch.empty((B, nq), **kw), torch.empty((B, nv), **kw)
794
+ _rc(fns["kin_vjp"](st, B, _ptr(q1), _ptr(v1), _ptr(com), *map(_ptr, kin_cot), _ptr(g_qpos), _ptr(g_qvel),
795
+ _ptr(cq), _ptr(cv)), "the kinematics VJP launch")
796
+ _rc(fns["adjoint"][v](st, B, substeps, _ptr(tape), _ptr(friction), _ptr(com), _ptr(cq), _ptr(cv), _ptr(gq),
797
+ _ptr(gv), _ptr(gu), _ptr(info), _ptr(ctrl), ctypes.c_float(clamp_soft),
798
+ *((_ptr(act), _ptr(g_act), _ptr(ga[0])) if aw else ()),
799
+ *((ctypes.c_float(cone_mu), ctypes.c_float(impulse_clip if impulse_clip else math.inf))
800
+ if sur else ()), *((_ptr(g_contacts),) if cgrad else ())),
801
+ "the adjoint launch")
802
+ if _DIAG_ON[0]:
803
+ _diag_backward(dev, st, gq, gv, gu, cq, cv, info)
804
+ return [gq, gv, gu, info] + ga
805
+
806
+
807
+ @_on_input_device
808
+ def _kinematics_impl(qpos, qvel, com):
809
+ import torch
810
+ dev = _ready(qpos)
811
+ nq, nv, _, _, _ = _sizes()
812
+ B = qpos.shape[0]
813
+ for name, x, shape in (("qpos", qpos, (B, nq)), ("qvel", qvel, (B, nv)), ("com", com, (B, _com_words()))):
814
+ _check(name, x, shape, dev)
815
+ out = _kin_empty(B, qpos.device)
816
+ if B:
817
+ st = torch.cuda.current_stream(dev).cuda_stream
818
+ _rc(_STATE["fns"]["kin"](st, B, _ptr(qpos), _ptr(qvel), _ptr(com), *map(_ptr, out)), "the kinematics launch")
819
+ return out
820
+
821
+
822
+ @_on_input_device
823
+ def _kinematics_backward_impl(qpos, qvel, com, g_qpos_n, g_xpos, g_xquat, g_cvel, g_subtree_com):
824
+ import torch
825
+ dev = _ready(qpos)
826
+ nq, nv, _, nb, _ = _sizes()
827
+ B = qpos.shape[0]
828
+ for name, x, shape in (("qpos", qpos, (B, nq)), ("qvel", qvel, (B, nv)), ("com", com, (B, _com_words())),
829
+ ("g_qpos_n", g_qpos_n, (B, nq)), ("g_xpos", g_xpos, (B, nb, 3)),
830
+ ("g_xquat", g_xquat, (B, nb, 4)), ("g_cvel", g_cvel, (B, nb, 6)),
831
+ ("g_subtree_com", g_subtree_com, (B, nb, 3))):
832
+ _check(name, x, shape, dev)
833
+ kw = dict(dtype=torch.float32, device=qpos.device)
834
+ gq, gv = torch.empty((B, nq), **kw), torch.empty((B, nv), **kw)
835
+ if B:
836
+ st = torch.cuda.current_stream(dev).cuda_stream
837
+ _rc(_STATE["fns"]["kin_vjp"](st, B, _ptr(qpos), _ptr(qvel), _ptr(com), _ptr(g_qpos_n), _ptr(g_xpos),
838
+ _ptr(g_xquat), _ptr(g_cvel), _ptr(g_subtree_com), None, None, _ptr(gq), _ptr(gv)),
839
+ "the kinematics VJP launch")
840
+ return [gq, gv]
841
+
842
+
843
+ _OPS = {}
844
+ _IMPL = dict(forward=lambda *a: _forward_impl(*a), backward=lambda *a: _backward_impl(*a),
845
+ kinematics=lambda *a: _kinematics_impl(*a), kinematics_backward=lambda *a: _kinematics_backward_impl(*a))
846
+
847
+
848
+ def _ops():
849
+ import torch
850
+ if not torch.compiler.is_compiling():
851
+ return _IMPL
852
+ return _custom_ops()
853
+
854
+
855
+ def _custom_ops():
856
+ if _OPS:
857
+ return _OPS
858
+ import torch
859
+ from typing import List, Optional
860
+ from torch import Tensor
861
+
862
+ @torch.library.custom_op("nablaengine::forward", mutates_args=())
863
+ def forward_op(qpos: Tensor, qvel: Tensor, warm: Tensor, ctrl: Tensor, friction: Tensor, com: Tensor,
864
+ iterations: int, substeps: int, tape: bool, kinematics: bool,
865
+ act: Optional[Tensor] = None) -> List[Tensor]:
866
+ return _forward_impl(qpos, qvel, warm, ctrl, friction, com, iterations, substeps, tape, kinematics, act)
867
+
868
+ @forward_op.register_fake
869
+ def _(qpos, qvel, warm, ctrl, friction, com, iterations, substeps, tape, kinematics, act=None):
870
+ nq, nv, _, nb, rec = _fake_sizes()
871
+ B = qpos.shape[0]
872
+ out = [qpos.new_empty((B, nq)), qpos.new_empty((B, nv)), qpos.new_empty((B, nv)),
873
+ qpos.new_empty((B, int(_STATE["info"].get("info_words", 4))), dtype=torch.int32),
874
+ qpos.new_empty((B if tape else 0, substeps * rec))]
875
+ if kinematics:
876
+ out += [qpos.new_empty(s) for s in ((B, nq), (B, nb, 3), (B, nb, 4), (B, nb, 6), (B, nb, 3))]
877
+ if act is not None:
878
+ out.append(act.new_empty(act.shape))
879
+ return out
880
+
881
+ @torch.library.custom_op("nablaengine::backward", mutates_args=())
882
+ def backward_op(tape: Tensor, friction: Tensor, com: Tensor, g_qpos: Tensor, g_qvel: Tensor,
883
+ ctrl: Optional[Tensor], kin_state: List[Tensor], kin_cot: List[Tensor], substeps: int,
884
+ clamp_kv: int, normal: int, clamp_soft: float, act: Optional[Tensor] = None,
885
+ g_act: Optional[Tensor] = None, cone_mu: float = 0.0, impulse_clip: float = 0.0,
886
+ g_contacts: Optional[Tensor] = None) -> List[Tensor]:
887
+ return _backward_impl(tape, friction, com, g_qpos, g_qvel, ctrl, kin_state, kin_cot, substeps, clamp_kv,
888
+ normal, clamp_soft, act, g_act, cone_mu, impulse_clip, g_contacts)
889
+
890
+ @backward_op.register_fake
891
+ def _(tape, friction, com, g_qpos, g_qvel, ctrl, kin_state, kin_cot, substeps, clamp_kv, normal, clamp_soft,
892
+ act=None, g_act=None, cone_mu=0.0, impulse_clip=0.0, g_contacts=None):
893
+ nq, nv, nu, _, _ = _fake_sizes()
894
+ B = tape.shape[0]
895
+ npw = int(_STATE["info"].get("param_words", 0))
896
+ nov = int(_STATE["info"].get("obj_vel_words", 0)) + int(_STATE["info"].get("obj_mat_words", 0))
897
+ return [tape.new_empty((B, nq)), tape.new_empty((B, nv)),
898
+ tape.new_empty((B, nu + (npw + 1 if npw else 0) + nov)),
899
+ tape.new_empty((B,), dtype=torch.int32)] + ([act.new_empty(act.shape)] if act is not None else [])
900
+
901
+ @torch.library.custom_op("nablaengine::kinematics", mutates_args=())
902
+ def kinematics_op(qpos: Tensor, qvel: Tensor, com: Tensor) -> List[Tensor]:
903
+ return _kinematics_impl(qpos, qvel, com)
904
+
905
+ @kinematics_op.register_fake
906
+ def _(qpos, qvel, com):
907
+ nq, _, _, nb, _ = _fake_sizes()
908
+ B = qpos.shape[0]
909
+ return [qpos.new_empty(s) for s in ((B, nq), (B, nb, 3), (B, nb, 4), (B, nb, 6), (B, nb, 3))]
910
+
911
+ @torch.library.custom_op("nablaengine::kinematics_backward", mutates_args=())
912
+ def kinematics_backward_op(qpos: Tensor, qvel: Tensor, com: Tensor, g_qpos_n: Tensor, g_xpos: Tensor,
913
+ g_xquat: Tensor, g_cvel: Tensor, g_subtree_com: Tensor) -> List[Tensor]:
914
+ return _kinematics_backward_impl(qpos, qvel, com, g_qpos_n, g_xpos, g_xquat, g_cvel, g_subtree_com)
915
+
916
+ @kinematics_backward_op.register_fake
917
+ def _(qpos, qvel, com, g_qpos_n, g_xpos, g_xquat, g_cvel, g_subtree_com):
918
+ nq, nv, _, _, _ = _fake_sizes()
919
+ B = qpos.shape[0]
920
+ return [qpos.new_empty((B, nq)), qpos.new_empty((B, nv))]
921
+
922
+ _OPS.update(forward=forward_op, backward=backward_op, kinematics=kinematics_op,
923
+ kinematics_backward=kinematics_backward_op)
924
+ return _OPS
925
+
926
+
927
+ def _fake_sizes():
928
+ if not _STATE:
929
+ init()
930
+ return _sizes()
931
+
932
+
933
+
934
+ def _diag_forward(dev, st, info, tape, iterations, substeps):
935
+ _rc(_STATE["fns"]["dk_torch_diag_fwd"](st, _ptr(_DIAG[dev]), info.shape[0], substeps, iterations, _ptr(info),
936
+ _ptr(tape)), "the forward diagnostics launch")
937
+
938
+
939
+ def _diag_backward(dev, st, gq, gv, gu, cq, cv, info):
940
+ _rc(_STATE["fns"]["dk_torch_diag_bwd"](st, _ptr(_DIAG[dev]), info.shape[0], *map(_ptr, (gq, gv, gu, cq, cv)),
941
+ _ptr(info)), "the backward diagnostics launch")
942
+
943
+
944
+ def set_diagnostics(enabled):
945
+ """Switch the device counters and the backward's non-finite bits on (the default) or off; returns the previous
946
+ setting. They are one small kernel per forward and per backward (dk_torch_diag_fwd / _bwd); off leaves the
947
+ counters as they are and the backward's info with the adjoint's flags only.
948
+ Outputs and gradients are the same either way. A captured CUDA graph keeps the setting of its capture."""
949
+ prev = _DIAG_ON[0]
950
+ _DIAG_ON[0] = bool(enabled)
951
+ return prev
952
+
953
+
954
+ def diagnostics(device=None):
955
+ """The device's counters (int64 (len(DIAG),) CUDA tensor, DIAG order), added up by every call since init or the
956
+ last reset; not copied or synchronized (graph-safe to read into another tensor)."""
957
+ dev = _device_index(device)
958
+ if dev not in _READY:
959
+ init(dev)
960
+ return _DIAG[dev]
961
+
962
+
963
+ def read_diagnostics(device=None, reset=True):
964
+ """The device's counters as {name: int} (synchronizes); reset=True zeroes them afterwards. With
965
+ set_overflow_warnings(True) it warns (warn_overflow) when worlds exceeded the contact or constraint-row capacity."""
966
+ d = diagnostics(device)
967
+ out = dict(zip(DIAG, (int(x) for x in d.cpu())))
968
+ if reset:
969
+ d.zero_()
970
+ if _OVERFLOW_WARN[0]:
971
+ warn_overflow(out)
972
+ return out
973
+
974
+
975
+ def warn_overflow(d, where="nablaengine"):
976
+ """A RuntimeWarning when the counters d count worlds whose contacts or constraint rows exceeded the per-world
977
+ capacity (the loaded library's info["maxcon"] / info["nefc"]): the ones beyond were dropped, so those worlds miss
978
+ support and friction forces (as jax_ffi.warn_overflow). The worlds of a call: info[:, 3] & OVERFLOW_CONTACTS /
979
+ OVERFLOW_ROWS of forward(). init(max_contacts=, max_rows=) raises the capacities."""
980
+ import warnings
981
+ nc, nr = d.get("fwd_contact_overflow_worlds", 0), d.get("fwd_row_overflow_worlds", 0)
982
+ info = _STATE["info"] if _STATE else {}
983
+ maxcon, nefc = info.get("maxcon", 64), info.get("nefc", 192)
984
+ if nc or nr:
985
+ warnings.warn(f"{where}: {nc} world-steps exceeded the contact capacity ({maxcon} per world) and {nr} the "
986
+ f"constraint-row capacity ({nefc}); their extra contacts / rows were dropped, so those worlds miss "
987
+ f"support and friction forces (e.g. deep interpenetration; init(max_contacts=, max_rows=) raises "
988
+ f"the capacities). See docs/api_torch.md, Diagnostics.", RuntimeWarning, stacklevel=3)
989
+ return nc + nr
990
+
991
+
992
+ def capacity_counts(info):
993
+ """(contacts_found, rows_needed), two (B,) int32 tensors, from forward()'s info of a build with
994
+ init(capacity_diag=True) (info (B, 6)): as jax_ffi.capacity_counts (per world the largest over the call's substeps
995
+ of the contacts found and the constraint rows needed before the capacities truncate them)."""
996
+ if info.dim() != 2 or info.shape[1] != 6:
997
+ raise _err(f"capacity_counts: info of shape {tuple(info.shape)}; the counts need a build with "
998
+ "init(capacity_diag=True), whose forward info is (B, 6)", ValueError)
999
+ return info[:, 4], info[:, 5]
1000
+
1001
+
1002
+ def set_overflow_warnings(enabled):
1003
+ """Switch the capacity-overflow warnings on or off (default off, or $DK_OVERFLOW_WARN=1): when on,
1004
+ read_diagnostics warns (warn_overflow) if worlds exceeded the per-world contact or
1005
+ constraint-row capacity, and the counts nobody read are reported once more at exit. The counters and info's bits
1006
+ are kept either way. Returns the previous setting."""
1007
+ prev = _OVERFLOW_WARN[0]
1008
+ _OVERFLOW_WARN[0] = bool(enabled)
1009
+ return prev
1010
+
1011
+
1012
+ def _exit_report():
1013
+ try:
1014
+ if not (_DIAG_ON[0] and _OVERFLOW_WARN[0]):
1015
+ return
1016
+ for dev in sorted(_DIAG):
1017
+ warn_overflow(dict(zip(DIAG, (int(x) for x in _DIAG[dev].cpu()))), where=f"nablaengine (cuda:{dev})")
1018
+ except Exception:
1019
+ pass
1020
+
1021
+
1022
+
1023
+ def _make_step_fn():
1024
+ import torch
1025
+
1026
+ class _Step(torch.autograd.Function):
1027
+ @staticmethod
1028
+ def forward(ctx, qpos, qvel, warm, ctrl, friction, com, iterations, substeps, clamp_kv, normal, clamp_soft,
1029
+ grad_decay, kin, sur=(0.0, 0.0), con=False):
1030
+ r = _ops()["forward"](qpos, qvel, warm, ctrl, friction, com, iterations, substeps, True, kin)
1031
+ q1, v1, w1, info, tp = r[:5]
1032
+ ctx.save_for_backward(tp, friction, com, ctrl, q1, v1)
1033
+ ctx.opts = (substeps, clamp_kv, normal, clamp_soft, grad_decay, kin, sur, con)
1034
+ ctx.mark_non_differentiable(w1)
1035
+ return (q1, v1, w1) + tuple(r[5:]) + ((_last_con(qpos, substeps).clone(),) if con else ())
1036
+
1037
+ @staticmethod
1038
+ def backward(ctx, g_q1, g_v1, g_w1, *g_kin):
1039
+ tp, friction, com, ctrl, q1, v1 = ctx.saved_tensors
1040
+ substeps, clamp_kv, normal, clamp_soft, grad_decay, kin, sur, con = ctx.opts
1041
+ g_con = None
1042
+ if con:
1043
+ g_con = g_kin[-1].contiguous() if g_kin[-1] is not None else None
1044
+ g_kin = g_kin[:-1]
1045
+ g_q1 = torch.zeros_like(q1) if g_q1 is None else g_q1.contiguous()
1046
+ g_v1 = torch.zeros_like(v1) if g_v1 is None else g_v1.contiguous()
1047
+ kin_state, kin_cot = [], []
1048
+ if kin and any(g is not None for g in g_kin):
1049
+ kin_state = [q1, v1]
1050
+ kin_cot = [torch.zeros(s, dtype=torch.float32, device=q1.device) if g is None else g.contiguous()
1051
+ for g, s in zip(g_kin, _kin_shapes(q1.shape[0]))]
1052
+ gq, gv, gu, _ = _ops()["backward"](tp, friction, com, g_q1, g_v1, ctrl if clamp_kv == 2 else None,
1053
+ kin_state, kin_cot, substeps, clamp_kv, normal,
1054
+ 0.0 if clamp_soft is None else clamp_soft, None, None, *sur, g_con)
1055
+ if grad_decay != 1.0:
1056
+ gq, gv = gq * grad_decay, gv * grad_decay
1057
+ gcom, gfr, nu = None, None, int(_STATE["info"]["nu"])
1058
+ npw, nov = int(_STATE["info"].get("param_words", 0)), int(_STATE["info"].get("obj_vel_words", 0))
1059
+ nov += int(_STATE["info"].get("obj_mat_words", 0))
1060
+ if npw or nov:
1061
+ gcom = torch.zeros_like(com)
1062
+ if npw:
1063
+ gcom[:, com.shape[1] - npw:] = gu[:, nu:nu + npw]
1064
+ gfr = gu[:, nu + npw].contiguous()
1065
+ if nov:
1066
+ gcom[:, com.shape[1] - npw - nov:com.shape[1] - npw] = gu[:, gu.shape[1] - nov:]
1067
+ gu = gu[:, :nu]
1068
+ return gq, gv, None, gu, gfr, gcom, None, None, None, None, None, None, None, None, None
1069
+
1070
+ return _Step
1071
+
1072
+
1073
+ def _make_step_act_fn():
1074
+ import torch
1075
+
1076
+ class _StepAct(torch.autograd.Function):
1077
+ """A BAM build's step: (qpos, qvel, warm, ctrl, friction, com, act) -> (qpos', qvel', warm', act'),
1078
+ differentiable in qpos, qvel, ctrl and act."""
1079
+ @staticmethod
1080
+ def forward(ctx, qpos, qvel, warm, ctrl, friction, com, act, iterations, substeps, clamp_kv, normal,
1081
+ grad_decay):
1082
+ r = _ops()["forward"](qpos, qvel, warm, ctrl, friction, com, iterations, substeps, True, False, act)
1083
+ q1, v1, w1, info, tp, a1 = r
1084
+ ctx.save_for_backward(tp, friction, com, act, q1, v1)
1085
+ ctx.opts = (substeps, clamp_kv, normal, grad_decay)
1086
+ ctx.mark_non_differentiable(w1)
1087
+ return q1, v1, w1, a1
1088
+
1089
+ @staticmethod
1090
+ def backward(ctx, g_q1, g_v1, g_w1, g_a1):
1091
+ tp, friction, com, act, q1, v1 = ctx.saved_tensors
1092
+ substeps, clamp_kv, normal, grad_decay = ctx.opts
1093
+ g_q1 = torch.zeros_like(q1) if g_q1 is None else g_q1.contiguous()
1094
+ g_v1 = torch.zeros_like(v1) if g_v1 is None else g_v1.contiguous()
1095
+ g_a1 = torch.zeros_like(act) if g_a1 is None else g_a1.contiguous()
1096
+ gq, gv, gu, _, ga = _ops()["backward"](tp, friction, com, g_q1, g_v1, None, [], [], substeps, clamp_kv,
1097
+ normal, 0.0, act, g_a1)
1098
+ if grad_decay != 1.0:
1099
+ gq, gv, ga = gq * grad_decay, gv * grad_decay, ga * grad_decay
1100
+ return gq, gv, None, gu, None, None, ga, None, None, None, None, None
1101
+
1102
+ return _StepAct
1103
+
1104
+
1105
+ def _kin_shapes(B):
1106
+ nq, _, _, nb, _ = _sizes()
1107
+ return (B, nq), (B, nb, 3), (B, nb, 4), (B, nb, 6), (B, nb, 3)
1108
+
1109
+
1110
+ def _make_kin_fn():
1111
+ import torch
1112
+
1113
+ class _Kin(torch.autograd.Function):
1114
+ @staticmethod
1115
+ def forward(ctx, qpos, qvel, com):
1116
+ out = _ops()["kinematics"](qpos, qvel, com)
1117
+ ctx.save_for_backward(qpos, qvel, com)
1118
+ return tuple(out)
1119
+
1120
+ @staticmethod
1121
+ def backward(ctx, *g):
1122
+ qpos, qvel, com = ctx.saved_tensors
1123
+ g = [torch.zeros(s, dtype=torch.float32, device=qpos.device) if x is None else x.contiguous()
1124
+ for x, s in zip(g, _kin_shapes(qpos.shape[0]))]
1125
+ gq, gv = _ops()["kinematics_backward"](qpos, qvel, com, *g)
1126
+ return gq, gv, None
1127
+
1128
+ return _Kin
1129
+
1130
+
1131
+ _FNS = {}
1132
+
1133
+
1134
+ def _fn(name, make):
1135
+ if name not in _FNS:
1136
+ _FNS[name] = make()
1137
+ return _FNS[name]
1138
+
1139
+
1140
+ def _con_width(substeps):
1141
+ i = _STATE["info"]
1142
+ cf, mc, cw = i.get("contact_forces"), int(i["maxcon"]), int(i.get("con_words", 8))
1143
+ if not cf:
1144
+ return mc * cw
1145
+ nf = len(cf["feet"])
1146
+ return (int(substeps) if cf["mode"] == "substeps" else 1) * mc * cw + (int(substeps) * nf * 6 + nf if nf else 0)
1147
+
1148
+
1149
+ def _last_con(x, substeps=SUBSTEPS):
1150
+ import torch
1151
+ con = _LAST_CON.get(_device_index(x.device))
1152
+ if con is None or con.shape[0] != x.shape[0]:
1153
+ con = torch.empty((x.shape[0], _con_width(substeps)), dtype=torch.float32, device=x.device)
1154
+ return con
1155
+
1156
+
1157
+ def step(qpos, qvel, warm, ctrl, friction, com, *, iterations=ITERATIONS, substeps=SUBSTEPS, clamp_kv=CLAMP_KV,
1158
+ normal=NORMAL, clamp_soft=None, grad_decay=GRAD_DECAY, kinematics=False, contacts=False, act=None,
1159
+ cone_mu=0.0, impulse_clip=None):
1160
+ """One control step: (qpos', qvel', warm'); kinematics=True: (qpos', qvel', warm', qpos_n, xpos, xquat, cvel,
1161
+ subtree_com), the output state's kinematics. Options as jax_ffi.step (clamp_kv, normal, clamp_soft and
1162
+ grad_decay act on the backward only). Differentiable in qpos, qvel and ctrl when any input requires grad (then the
1163
+ forward also writes the tape); warm' is not differentiable. contacts=True: the last substep's contact table
1164
+ (B, maxcon * con_words) after warm', as jax_ffi.step (contact_table() decodes it; not differentiable; the tensor
1165
+ last_contacts() reads, so eager mode only, not inside a captured CUDA graph). act: the BAM servo model's state
1166
+ (B, info["act_words"]) in a BAM build (required there, refused elsewhere): (qpos', qvel', warm', act'[,
1167
+ contacts]), differentiable in act too (clamp_kv 0 or 1, the same there; no kinematics outputs; docs/actuators.md).
1168
+ cone_mu, impulse_clip: the backward's contact-gradient surrogates (as jax_ffi.step; a contact_surrogate build)."""
1169
+ import torch
1170
+ if act is not None or (_STATE and _STATE["info"].get("act_words")):
1171
+ args = (qpos, qvel, warm, ctrl, friction, com, act)
1172
+ if torch.is_grad_enabled() and any(isinstance(x, torch.Tensor) and x.requires_grad for x in args):
1173
+ if kinematics or int(clamp_kv) not in (0, 1) or int(normal) not in (0, 1, 2, 3):
1174
+ raise _err("the BAM servo model's step: clamp_kv 0 or 1, normal in 0..3, no kinematics outputs",
1175
+ ValueError)
1176
+ gd = float(grad_decay)
1177
+ if not math.isfinite(gd):
1178
+ raise _err(f"grad_decay must be finite, got {grad_decay}", ValueError)
1179
+ if act is None:
1180
+ raise _err("this build has the BAM servo model: pass its state act=", ValueError)
1181
+ r = _fn("step_act", _make_step_act_fn).apply(*args, int(iterations), int(substeps), int(clamp_kv),
1182
+ int(normal), gd)
1183
+ return tuple(r) + ((_last_con(qpos, substeps),) if contacts else ())
1184
+ r = _ops()["forward"](qpos, qvel, warm, ctrl, friction, com, int(iterations), int(substeps), False,
1185
+ bool(kinematics), act)
1186
+ return tuple(r[:3]) + (r[-1],) + ((_last_con(qpos, substeps),) if contacts else ())
1187
+ if contacts and _STATE and _STATE["info"].get("contact_grad") and torch.is_grad_enabled() and any(
1188
+ isinstance(x, torch.Tensor) and x.requires_grad for x in (qpos, qvel, warm, ctrl, friction, com)):
1189
+ if int(clamp_kv) not in (0, 1, 2) or int(normal) not in (0, 1, 2, 3):
1190
+ raise _err("clamp_kv in {0, 1, 2}, normal in 0..3", ValueError)
1191
+ gd = float(grad_decay)
1192
+ if not math.isfinite(gd):
1193
+ raise _err(f"grad_decay must be finite, got {grad_decay}", ValueError)
1194
+ r = _fn("step", _make_step_fn).apply(qpos, qvel, warm, ctrl, friction, com, int(iterations), int(substeps),
1195
+ int(clamp_kv), int(normal), _soft(clamp_kv, clamp_soft), gd,
1196
+ bool(kinematics), _sur(cone_mu, impulse_clip), True)
1197
+ return tuple(r[:3]) + (r[-1],) + tuple(r[3:-1])
1198
+ if contacts:
1199
+ r = step(qpos, qvel, warm, ctrl, friction, com, iterations=iterations, substeps=substeps, clamp_kv=clamp_kv,
1200
+ normal=normal, clamp_soft=clamp_soft, grad_decay=grad_decay, kinematics=kinematics, cone_mu=cone_mu,
1201
+ impulse_clip=impulse_clip)
1202
+ return tuple(r[:3]) + (_last_con(qpos, substeps),) + tuple(r[3:])
1203
+ if int(clamp_kv) not in (0, 1, 2) or int(normal) not in (0, 1, 2, 3):
1204
+ raise _err("clamp_kv in {0, 1, 2}, normal in 0..3", ValueError)
1205
+ soft = _soft(clamp_kv, clamp_soft)
1206
+ gd = float(grad_decay)
1207
+ if not math.isfinite(gd):
1208
+ raise _err(f"grad_decay must be finite, got {grad_decay}", ValueError)
1209
+ args = (qpos, qvel, warm, ctrl, friction, com)
1210
+ if torch.is_grad_enabled() and any(isinstance(x, torch.Tensor) and x.requires_grad for x in args):
1211
+ return _fn("step", _make_step_fn).apply(*args, int(iterations), int(substeps), int(clamp_kv), int(normal),
1212
+ soft, gd, bool(kinematics), _sur(cone_mu, impulse_clip))
1213
+ r = _ops()["forward"](*args, int(iterations), int(substeps), False, bool(kinematics))
1214
+ return tuple(r[:3]) + tuple(r[5:])
1215
+
1216
+
1217
+ def kinematics(qpos, qvel, com):
1218
+ """Differentiable kinematics outputs of states (qpos, qvel, com): (qpos_n, xpos, xquat, cvel, subtree_com), as
1219
+ jax_ffi.kinematics (gradients for qpos and qvel, none for com); kinematics(q', v', com) of a step's output is
1220
+ bitwise step(..., kinematics=True)'s."""
1221
+ return _fn("kin", _make_kin_fn).apply(qpos, qvel, com)
1222
+
1223
+
1224
+ def forward(qpos, qvel, warm, ctrl, friction, com, *, iterations=ITERATIONS, substeps=SUBSTEPS, tape=False,
1225
+ kinematics=False, contacts=False, act=None):
1226
+ """One control step without autograd: (qpos', qvel', warm', info (B, info["info_words"]) int32[, contacts][, tape][, the
1227
+ kinematics outputs]), as jax_ffi.forward (contacts=True: as step's). act: a BAM build's state (B,
1228
+ info["act_words"]): (qpos', qvel', warm', act', info[, contacts][, tape]), as jax_ffi.forward."""
1229
+ if act is not None:
1230
+ r = _ops()["forward"](qpos, qvel, warm, ctrl, friction, com, int(iterations), int(substeps), bool(tape),
1231
+ bool(kinematics), act)
1232
+ return (tuple(r[:3]) + (r[-1], r[3]) + ((_last_con(qpos, substeps),) if contacts else ()) + ((r[4],) if tape else ()))
1233
+ r = _ops()["forward"](qpos, qvel, warm, ctrl, friction, com, int(iterations), int(substeps), bool(tape),
1234
+ bool(kinematics))
1235
+ return (tuple(r[:4]) + ((_last_con(qpos, substeps),) if contacts else ()) + ((r[4],) if tape else ())
1236
+ + tuple(r[5:]))
1237
+
1238
+
1239
+ def backward(tape, friction, com, g_qpos, g_qvel, *, substeps=SUBSTEPS, clamp_kv=CLAMP_KV, normal=NORMAL, ctrl=None,
1240
+ clamp_soft=None, kinematics=None, act=None, g_act=None, cone_mu=0.0, impulse_clip=None,
1241
+ g_contacts=None):
1242
+ """The adjoint of one control step from its tape: (g_qpos, g_qvel, g_ctrl, info (B,) int32), as
1243
+ jax_ffi.backward (kinematics: None or (qpos', qvel', g_qpos_n, g_xpos, g_xquat, g_cvel, g_subtree_com)). A BAM
1244
+ build: act (the step's input state) and g_act (the cotangent of act'; None: zeros) -> (g_qpos, g_qvel, g_ctrl,
1245
+ g_act, info), as jax_ffi.backward. cone_mu, impulse_clip: the contact-gradient surrogates (as jax_ffi.backward).
1246
+ g_contacts: the contact output's cotangent (a contact_grad build; as jax_ffi.backward)."""
1247
+ if _STATE and _STATE["info"].get("act_words"):
1248
+ if int(clamp_kv) == 2 or kinematics is not None:
1249
+ raise _err("the BAM servo model's adjoint: clamp_kv 0 or 1 (the same there: its servo force has no kv), "
1250
+ "no kinematics outputs", ValueError)
1251
+ gq, gv, gu, info, ga = _ops()["backward"](tape, friction, com, g_qpos, g_qvel, None, [], [], int(substeps),
1252
+ int(clamp_kv), int(normal), 0.0, act, g_act)
1253
+ return gq, gv, gu, ga, info
1254
+ soft = _soft(clamp_kv, clamp_soft)
1255
+ if soft is not None and ctrl is None:
1256
+ raise _err("clamp_kv=2 (the soft clamp) needs the step's ctrl", ValueError)
1257
+ ks, kc = ([], []) if kinematics is None else (list(kinematics[:2]), list(kinematics[2:]))
1258
+ if kinematics is not None and len(kc) != 5:
1259
+ raise _err("kinematics = (qpos', qvel', g_qpos_n, g_xpos, g_xquat, g_cvel, g_subtree_com)", ValueError)
1260
+ sur = _sur(cone_mu, impulse_clip)
1261
+ r = tuple(_ops()["backward"](tape, friction, com, g_qpos, g_qvel, ctrl if soft is not None else None, ks, kc,
1262
+ int(substeps), int(clamp_kv), int(normal), 0.0 if soft is None else soft, None, None,
1263
+ *(sur if sur is not None else (0.0, 0.0)), g_contacts))
1264
+ nu = int(_STATE["info"]["nu"])
1265
+ npw, nov = int(_STATE["info"].get("param_words", 0)), int(_STATE["info"].get("obj_vel_words", 0))
1266
+ nom = int(_STATE["info"].get("obj_mat_words", 0))
1267
+ gw = r[2].shape[1]
1268
+ ov = (r[2][:, gw - nom - nov:gw - nom],) if nov else ()
1269
+ ov += (r[2][:, gw - nom:],) if nom else ()
1270
+ if npw:
1271
+ return (r[0], r[1], r[2][:, :nu], r[3], r[2][:, nu:nu + npw], r[2][:, nu + npw]) + ov
1272
+ if nov or nom:
1273
+ return (r[0], r[1], r[2][:, :nu], r[3]) + ov
1274
+ return r
1275
+
1276
+
1277
+ def _make_scale_fn():
1278
+ import torch
1279
+
1280
+ class _Scale(torch.autograd.Function):
1281
+ @staticmethod
1282
+ def forward(ctx, gamma, *xs):
1283
+ ctx.gamma = gamma
1284
+ return tuple(x.view_as(x) for x in xs)
1285
+
1286
+ @staticmethod
1287
+ def backward(ctx, *g):
1288
+ return (None,) + tuple(None if x is None else x * ctx.gamma for x in g)
1289
+
1290
+ return _Scale
1291
+
1292
+
1293
+ def scale_grad(tree, gamma):
1294
+ """The identity on a pytree of tensors whose cotangent the backward multiplies by gamma (floating tensors only;
1295
+ others pass through), as jax_ffi.scale_grad: put it on the whole carried state at the top of each rollout step for
1296
+ an exact decay^n per step boundary (see jax_ffi's module docstring)."""
1297
+ import torch
1298
+ from torch.utils import _pytree
1299
+ g = float(gamma)
1300
+ if not math.isfinite(g):
1301
+ raise _err(f"scale_grad's gamma must be finite, got {gamma}", ValueError)
1302
+ leaves, spec = _pytree.tree_flatten(tree)
1303
+ idx = [i for i, x in enumerate(leaves) if isinstance(x, torch.Tensor) and x.is_floating_point()]
1304
+ if idx:
1305
+ out = _fn("scale", _make_scale_fn).apply(g, *(leaves[i] for i in idx))
1306
+ for i, x in zip(idx, out):
1307
+ leaves[i] = x
1308
+ return _pytree.tree_unflatten(leaves, spec)
1309
+
1310
+
1311
+ def _main(argv=None):
1312
+ import argparse
1313
+ ap = argparse.ArgumentParser(prog="python -m nablaengine.torch_ffi",
1314
+ description="build the PyTorch interface's library and artifact (mujoco and nvcc "
1315
+ "needed here; the processes that load it need neither)")
1316
+ sub = ap.add_subparsers(dest="cmd", required=True)
1317
+ b = sub.add_parser("build", help="build for one or more architectures and make them current")
1318
+ b.add_argument("--arch", action="append", help="sm_XY, repeatable (default: $DK_ARCH, else the first GPU's)")
1319
+ a = ap.parse_args(argv)
1320
+ if a.cmd == "build":
1321
+ from nablaengine import cuda
1322
+ for arch in a.arch or [cuda.arch()]:
1323
+ print(f"nablaengine.torch_ffi: artifact {build(arch)}")
1324
+
1325
+
1326
+ if __name__ == "__main__":
1327
+ _main()
1328
+