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,1661 @@
1
+ """CUDA source of the G1 engine's analytic adjoint: the VJP of a control step from its forward tape."""
2
+
3
+ import numpy as np
4
+
5
+ from nablaengine.dual import DUAL_DEVICE
6
+ from nablaengine.g1_engine import adjoint_contact, condim4, elliptic, model_hooks, motor_hooks, source, step, tape
7
+
8
+ ADJ_ROWS_SKIPPED = 1 << 12
9
+ ADJ_REPLAY_MISMATCH = 1 << 13
10
+ NO_ROW = 1e30
11
+
12
+ PROF_PHASES = ("record", "poses", "integrator", "solve_Q", "solve_H", "tree_down", "limits", "contact_setup",
13
+ "contact_rows", "contact_reduce", "tree_up", "compose", "io", "count_contacts",
14
+ "count_contacts_active", "count_limit_rows")
15
+ PROF_PARTITION = 13
16
+ PROF_DESIGN = dict(record="A0", poses="A3", integrator="A1", solve_Q="A1", solve_H="A2", tree_down="A3+A4",
17
+ limits="A5+A6", contact_setup="A5", contact_rows="A5+A6", contact_reduce="A6", tree_up="A7",
18
+ compose="A8", io="kernel")
19
+
20
+ DEBUG_FIELDS = (
21
+ ("g_qpos_out", "nq"), ("g_qvel_out", "nv"),
22
+ ("adj_qpos_int", "nq"), ("adj_qvel_int", "nv"), ("adj_qacc_adv", "nv"),
23
+ ("y", "nv"), ("adj_qacc", "nv"), ("lam", "nv"), ("w_dir", "nv"),
24
+ ("adj_qpos_M", "nq"), ("res_qpos_rne", "nq"), ("res_qpos_act", "nq"), ("res_qvel_rne", "nv"), ("res_qvel_act", "nv"),
25
+ ("res_qpos_contact", "nq"), ("res_qvel_contact", "nv"), ("res_qpos_limit", "nq"), ("res_qvel_limit", "nv"),
26
+ ("grad_qpos_in", "nq"), ("grad_qvel_in", "nv"), ("grad_ctrl_k", "nu"),
27
+ ("resid", "nv"), ("resid_norm", 1), ("tau_norm", 1), ("id_norm", 1),
28
+ ("ma_norm", 1),
29
+ ("jtf_norm", 1),
30
+ ("con_dist", "mc"), ("con_pos", ("mc", 3)), ("con_dist_bar", "mc"), ("con_pos_bar", ("mc", 3)),
31
+ ("con_frame_bar", ("mc", 9)), ("con_x", ("mc", 4)), ("con_force", ("mc", 3)), ("con_br", "mc"),
32
+ ("con_kink", "mc"), ("con_basis", "mc"), ("con_sin_free", "mc"),
33
+ ("lim_x", "nv"), ("lim_force", "nv"), ("lim_kink", "nv"),
34
+ ("body_q", ("nb", 4)), ("body_x", ("nb", 3)), ("geom_x", ("ng", 3)), ("geom_q", ("ng", 4)),
35
+ )
36
+
37
+
38
+ def debug_layout(m, max_contacts=None):
39
+ """{name: (offset, length, shape)} of a -DDK_ADJ_DEBUG record (words; shape: the decoded trailing shape), and its
40
+ length."""
41
+ sizes = {"nq": m.nq, "nv": m.nv, "nu": m.nv - 6, "mc": max_contacts or step.maxcon(m), "nb": m.nbody,
42
+ "ng": len(step.collision_geoms(m))}
43
+ out, off = {}, 0
44
+ for name, n in DEBUG_FIELDS:
45
+ unit, width = n if isinstance(n, tuple) else (n, 1)
46
+ cnt = sizes[unit] if isinstance(unit, str) else unit
47
+ shape = () if (cnt == 1 and width == 1) else ((cnt,) if width == 1 else (cnt, width))
48
+ out[name], off = (off, cnt * width, shape), off + cnt * width
49
+ return out, off
50
+
51
+
52
+ def decode_debug(arr, m, max_contacts=None):
53
+ """-DDK_ADJ_DEBUG records (..., debug words) -> dict of arrays (leading shape kept; scalars per record, per-contact
54
+ vectors as (..., maxcon, width))."""
55
+ lay, nw = debug_layout(m, max_contacts)
56
+ a = np.asarray(arr, np.float32)
57
+ assert a.shape[-1] == nw, (a.shape, nw)
58
+ return {k: a[..., o:o + n].reshape(a.shape[:-1] + shape) for k, (o, n, shape) in lay.items()}
59
+
60
+
61
+ def solimp_powers(m):
62
+ """The solimp powers of the model's constraint rows as the engine packs them (float32): the hinge limits'
63
+ (step.pair_constants: c_jsolimp, one set for all joints) and the contact pairs' parameter sets (c_pset)."""
64
+ sets = np.asarray(step.pair_param_sets(m)[0], np.float32)
65
+ fl = {float(np.float32(x)) for x in m.dof_solimp[m.dof_frictionloss > 0, 4]}
66
+ return sorted({float(np.float32(m.jnt_solimp[1][4]))} | {float(x) for x in sets[:, 3 + 4]} | fl)
67
+
68
+
69
+ def header(m):
70
+ """#defines of the adjoint (stage, options, debug layout, the model's solimp power); asserts the mjlab-only scope."""
71
+ has_box, box_ok, _ = model_hooks.box_pairs(m)
72
+ assert not has_box or box_ok, "the adjoint has box contacts with planes and boxes only (model_hooks)"
73
+ assert m.nu == m.nv - 6, "one position actuator per hinge dof"
74
+ lay, nw = debug_layout(m)
75
+ lines = [f"#define ADJ_ROWS_SKIPPED {ADJ_ROWS_SKIPPED}u", f"#define ADJ_REPLAY_MISMATCH {ADJ_REPLAY_MISMATCH}u",
76
+ f"#define DBG_NO_ROW {NO_ROW:.0e}f", f"#define DBG_WORDS {nw} // -DDK_ADJ_DEBUG record",
77
+ f"#define NAPROF {len(PROF_PHASES)} // -DDK_PROFILE: PROF_PHASES"]
78
+ lines += [f"#define APROF_{k.upper()} {i}" for i, k in enumerate(PROF_PHASES)]
79
+ dof0 = int(m.body_dofadr[2]) - 2
80
+ assert m.body_dofadr[1] == 0 and m.body_dofnum[1] == 6 and all(
81
+ m.body_dofnum[b] == 1 and m.body_dofadr[b] == b + dof0 for b in range(2, m.nbody)), \
82
+ "a free root (dofs 0-5), then one hinge dof per body, in body order"
83
+ lines.append(f"#define ADJ_HINGE_DOF0 {dof0} // the hinge dof of body b >= 2 is b + ADJ_HINGE_DOF0")
84
+ pw = solimp_powers(m)
85
+ if len(pw) == 1:
86
+ lines.append(f"#define ADJ_SOLIMP_POWER {pw[0].hex()}f // {pw[0]:g}, every row's solimp power")
87
+ lines += [f"#define DBG_{k.upper()} {o}" for k, (o, n, _) in lay.items()]
88
+ return "\n" + "\n".join(lines) + "\n"
89
+
90
+
91
+ ADJ_DEVICE = r"""
92
+ #ifndef DK_ADJ_STAGE
93
+ #define DK_ADJ_STAGE 3 // 1: smooth dynamics, integrator, actuator; 2: + limit rows, plane contacts; 3: + self contacts
94
+ #endif
95
+ #ifndef DK_ADJ_CLAMP_KV
96
+ #define DK_ADJ_CLAMP_KV 1 // 1: -kv lambda dropped on clamped dofs (exact); 0: kept (as MuJoCo Warp's adjoint)
97
+ #endif // 2: the soft clamp (lam_soft)
98
+ static_assert(DK_ADJ_CLAMP_KV >= 0 && DK_ADJ_CLAMP_KV <= 2, "DK_ADJ_CLAMP_KV: 0, 1 or 2");
99
+ #if DK_ADJ_CLAMP_KV == 2
100
+ // the soft clamp's delta is k_adjoint's run-time argument clamp_soft after ctrl (ADJ_SOFT_PARAM; a launch passes
101
+ // ADJ_SOFT_ARG(delta)); the other builds' kernel signature, and their code, are unchanged
102
+ #define ADJ_SOFT_PARAM , float clamp_soft
103
+ #define ADJ_SOFT_ARG(x) , (x)
104
+ #else
105
+ #define ADJ_SOFT_PARAM
106
+ #define ADJ_SOFT_ARG(x)
107
+ #endif
108
+ static_assert(HAS_BOX == 0 && NFLOSS == 0, "the adjoint is for the mjlab model (no boxes, no frictionloss rows)");
109
+ static_assert(DK_ADJ_STAGE >= 1 && DK_ADJ_STAGE <= 3, "DK_ADJ_STAGE: 1, 2 or 3");
110
+ static_assert(NB <= 31, "the contact reduction: lanes 0 and 31 take two of the root rotation dofs");
111
+ #define CS_N 24 // per-contact words (A6, in registers of the contact's lane): W_v, W_a, W_lam (0-8), contact point
112
+ // (9-11), the pose cotangents from its geometry of body 1 (f bar 12-14, tau bar 15-17) and of body 2
113
+ // (18-23)
114
+
115
+ // -DDK_PROFILE phase marks (adjoint.PROF_PHASES): APROF(k) adds lane 0's cycles since the previous mark to phase k.
116
+ // Unlike the forward's PROF they are empty in every other build (no __syncwarp() either), so the production code is
117
+ // the same with and without the marks; the marks sit right after a __syncwarp() of the code (the kernel's last one
118
+ // after its stores).
119
+ // APROF_COUNT(k, n) adds n (evaluated by all lanes: it may hold a full-mask ballot) to the count k
120
+ #ifdef DK_PROFILE
121
+ #ifdef DK_ADJ_DEBUG
122
+ #error "-DDK_PROFILE times the production path: build it without -DDK_ADJ_DEBUG"
123
+ #endif
124
+ #define APROF_START() do { __syncwarp(); if (lane == 0) s.aprof_t = clock64(); } while (0)
125
+ #define APROF(k) do { __syncwarp(); if (lane == 0) { long long t_ = clock64(); s.aprof[k] += t_ - s.aprof_t; s.aprof_t = t_; } __syncwarp(); } while (0)
126
+ #define APROF_COUNT(k, n) do { const long long n_ = (n); if (lane == 0) s.aprof[k] += n_; } while (0)
127
+ #else
128
+ #define APROF_START() do {} while (0)
129
+ #define APROF(k) do {} while (0)
130
+ #define APROF_COUNT(k, n) do {} while (0)
131
+ #endif
132
+ static_assert(NAPROF <= 32, "one profile counter per lane");
133
+
134
+ // Shared memory per world (10108 B on mjlab's G1, against 15740 B without the unions and the register-held contact
135
+ // words below: 9 instead of 6 worlds per SM on the 100 KB SMs of sm_86 / sm_120 (1 KB reserved per block, 128 B
136
+ // granularity: <= 10240 B for 9; the native sm_120 build, NVVM 20, has about 237 registers, which allow 8) and 16
137
+ // instead of 13 on sm_90a, where 128 registers then cap it): what is live through a whole substep, then two unions of
138
+ // arrays whose lifetimes within a substep are disjoint (the phases in adj_substep's order, a __syncwarp() between the
139
+ // last read of one alternative and the first write of the next; no function touches two alternatives of a union that
140
+ // overlap), and a contact batch's per-contact words in the registers of the contacts' lanes (adj_contacts: shuffles
141
+ // instead of a 3.2 KB scratch). The arithmetic and its order are unchanged: the gradients are bitwise the same.
142
+ // UA: V, aadv (A0 .. A1: V only inside adj_poses' recursion, aadv until adj_integrator) | L, y, abar (A1 .. A2,
143
+ // adj_solves) | the cotangents b*, fb, tb (A4 .. A7: adj_tree_down to adj_tree_up)
144
+ // UB: A, A2, Vl, Vy (A3 .. A4: adj_poses / adj_tree_down to body_local_vjp) | {gx, gq, zr (A5 / A6: adj_contacts) |
145
+ // rb (A7: adj_tree_up)} with P_q, P_v (A5 .. A8: adj_tree_down sets them to 0 after its last read of A .. Vy)
146
+ // Body 0's entries of the union arrays are never read (the root's recursions do not read their parent's). A caller
147
+ // that runs adj_tree_down again after adj_contacts needs A again, and P across adj_tree_down: -DDK_ADJ_DEBUG keeps A,
148
+ // zr, P_q, P_v outside UB (its pass by source does that); the U11 unit test (docs/verification.md) reruns adj_poses
149
+ struct Adj {
150
+ // the substep (A0: from the record) and the adjoint's vectors, dof (NV) or qpos (NQ) indexed
151
+ float q[NQ], v[NV], a[NV], at[NV]; // input state, a*, a~ = a* - a_adv
152
+ float ny[NV], lam[NV]; // -y, lambda
153
+ float qbar[NQ], vbar[NV], ubar[NV - 6]; // cotangents of the substep's output, then of its input; ctrl (summed)
154
+ float com[3], fric;
155
+ unsigned clamp[(NV + 31) / 32]; // the record's actuator clamp mask (dof bits)
156
+ unsigned zone[(NEFC + 31) / 32]; // the record's quadratic-zone bits of the constraint rows (forward row order)
157
+ unsigned con[(MAXCON + 1) / 2]; // the record's contact table: pair | slot << 9 per 16 bits
158
+ int hdr; // the record's header: ncon | nefc << 8 | nlim << 16 | niter << 24
159
+ int flags; // union of the records' flags (tape.py), ADJ_ROWS_SKIPPED, ADJ_REPLAY_MISMATCH
160
+ // bodies, lane b = body b (body 0: the world, at rest). Forward quantities (A3) read up to A7:
161
+ float Q[NB][4], X[NB][3], z[NB][3]; // pose (X_b: origin = hinge anchor), hinge axis z_b = R_b axis_b (b >= 2)
162
+ float W[NB][3], AL[NB][3]; // channel 1 (fwd_body): angular velocity W of v, angular acceleration AL at a*
163
+ float AL2[NB][3]; // channel 2: angular acceleration at a~ with v = 0, no gravity (the twist recursion of a~)
164
+ float Wl[NB][3], Wy[NB][3]; // angular parts of the twists of lambda, -y
165
+ #ifdef DK_ADJ_DEBUG // outside UB: the debug build's pass by source runs adj_tree_down after adj_contacts
166
+ float A[NB][3], zr[3][3], Pq[NV], Pv[NV];
167
+ #endif
168
+ union { // UA
169
+ struct { // A0 .. A1
170
+ float V[NB][3]; // channel 1's linear velocity of the origin: only adj_poses' recursion reads it
171
+ float aadv[NV]; // a_adv (the record's): adj_integrator
172
+ };
173
+ struct { // A1, A2 (adj_solves)
174
+ float L[NTRI]; // a factor from the record: L_Q (A1), then L_H (A2)
175
+ float y[NV], abar[NV]; // y, a_adv bar then a* bar
176
+ };
177
+ struct { // cotangents (A4, then completed in A7): channel 1, channel 2, the lambda and -y twists
178
+ float bW[NB][3], bAL[NB][3], bA[NB][3], bAL2[NB][3], bA2[NB][3], bWl[NB][3], bVl[NB][3], bWy[NB][3], bVy[NB][3];
179
+ float fb[NB][3], tb[NB][3]; // pose cotangents f bar_b, tau bar_b (A4, A6), then the subtree sums F_b, N_b (A7)
180
+ };
181
+ };
182
+ union { // UB
183
+ struct { // A3 .. A4: read last by body_local_vjp (adj_tree_down)
184
+ #ifndef DK_ADJ_DEBUG
185
+ float A[NB][3]; // channel 1's linear acceleration of the origin at a*, with gravity
186
+ #endif
187
+ float A2[NB][3]; // channel 2's linear acceleration
188
+ float Vl[NB][3], Vy[NB][3]; // linear parts of the twists of lambda, -y
189
+ };
190
+ struct { // A5 .. A8
191
+ union {
192
+ struct { // A5 / A6 (adj_contacts; a batch's per-contact words stay in the registers of the contacts' lanes)
193
+ float gx[NGEOMC][3], gq[NGEOMC][4]; // world poses of the collision geoms (the forward's geom_poses)
194
+ #ifndef DK_ADJ_DEBUG
195
+ float zr[3][3]; // the root's rotation axes R_1 e_k (the anchor of their Jacobian columns is X_1)
196
+ #endif
197
+ };
198
+ float rb[NB][3]; // A7: r bar_b of r_b = X_b - X_parent (the parent subtracts it from its F)
199
+ };
200
+ #ifndef DK_ADJ_DEBUG
201
+ // P = grad Psi: dof tangent (root: world translation, local rotation), qvel; set to 0 by
202
+ // adj_tree_down after its last read of A .. Vy, then summed by adj_limits, adj_contacts, adj_tree_up, adj_compose
203
+ float Pq[NV], Pv[NV];
204
+ #endif
205
+ };
206
+ };
207
+ #ifdef DK_ADJ_DEBUG
208
+ float dF[NB][3], dN[NB][3], did[NV], jtf[NV], ma_norm; // residual check: subtree forces of channel 1, ID, J'f, |M a*|
209
+ float tmp[NV], zero[NV]; // scratch, zeros (the split by source); only the debug build has them
210
+ #endif
211
+ #ifdef DK_PROFILE
212
+ long long aprof[NAPROF], aprof_t; // phase cycles and counts of lane 0 (APROF), the last mark
213
+ #endif
214
+ #if DK_ADJ_CLAMP_KV == 2
215
+ float u[NV - 6], soft; // the world's ctrl and delta (clamp_soft) for lam_soft (120 B: still 9 worlds per SM)
216
+ #endif
217
+ #if DK_CLAMP_IMPLICIT
218
+ float kvi[NV]; // the substep's implicit actuator damping per dof (the forward's Q = M + h diag(kvi))
219
+ #endif
220
+ #if DK_CLAMP_IMPLICIT == 2
221
+ float kvw[NV]; // the record's sign(f) w per dof (step.py; 1 where unclamped)
222
+ #endif
223
+ };
224
+
225
+ // LANE_BOUND(lane) at the top of a __noinline__ function: its lane parameter carries no bound for the compiler (the
226
+ // kernel's lane = threadIdx.x & 31 does not cross the call; see host.py k_substep), so each lane-strided loop
227
+ // (for i = lane; i < n; i += 32) would get an unknown trip count, unrolled by 4 with a remainder loop. In adj_solves,
228
+ // adj_tree_down, adj_tree_up, adj_limits and adj_contacts; bitwise the same gradients. k_adjoint on the RTX 3090
229
+ // (the interface defaults, a 4096-state corpus, 10 iterations): 1.9% / 1.7% faster at 1787 / 4096 worlds on top of
230
+ // the blocked
231
+ // tri_solve_packed; adj_solves 830 -> 595 SASS instructions (sm_86); k_adjoint 128 -> 140 registers on sm_120 (whose
232
+ // 6 worlds per SM were set by the 15.7 KB of shared memory, not by the registers), 127 -> 128 on sm_90a
233
+ #define LANE_BOUND(lane) __builtin_assume((lane) >= 0 && (lane) < 32)
234
+
235
+ // y / d as the fast path of the compiler's IEEE division (div.rn.f32 on sm_70 and sm_86, CUDA 12: r = MUFU.RCP(d), one
236
+ // Newton step r2 = r + r (1 - d r), q = y r2, q + r2 (y - d q)), whose reciprocal part depends on d alone. The
237
+ // division's own FCHK test sends operands outside the fast path's range (small |y|, |d| or the quotient near the
238
+ // exponent limits) to a slow path; this form has no branch, so a solve's divisions schedule ahead of the chain of y.
239
+ // Bitwise y / d where the residual y - d q is exact and d, 1 / d and the quotient are normal floats: |y| >= 2^-102 (the
240
+ // residual's last bit is then >= 2^-149). Below 2^-102 the residual can underflow and the quotient be off by an ulp
241
+ // (at most 1; with 2^32 random y per binade and the tapes' divisors L_kk, 0.063 .. 98, mismatches occur in every binade
242
+ // below 2^-102, rarer by about 2x per binade upwards); y = -0 gives +0, an overflowing quotient NaN instead of +-inf.
243
+ // Through the solves and sweeps such an ulp grows: the corpora's cotangents (N(0, 1) entries) scaled by s >= 1e-28 give gradients bitwise
244
+ // equal to a build with '/' (both corpora, 4 substeps, 3 cotangents each); s = 1e-29 changes 146 entries for one of the
245
+ // six, 1e-30 52 to 327 of the 409600 (up to 2816 ulp), 1e-32 about 4%, 1e-36 about 92%. So cotangents of realistic
246
+ // size (entries > 1e-20) give the gradients of '/' bitwise (at s = 1 ncu showed the slow path of '/' never ran here)
247
+ __device__ __forceinline__ float rcp_step(float d) {
248
+ float r;
249
+ asm("rcp.approx.ftz.f32 %0, %1;" : "=f"(r) : "f"(d));
250
+ return __fmaf_rn(r, __fmaf_rn(-d, r, 1.f), r);
251
+ }
252
+ __device__ __forceinline__ float div_fast(float y, float d, float r2) {
253
+ const float q = __fmaf_rn(y, r2, 0.f);
254
+ return __fmaf_rn(r2, __fmaf_rn(-d, q, y), q);
255
+ }
256
+
257
+ // x = (L L')^-1 b in place for a packed lower-triangular L (TRI) in shared memory and a shared NV vector b; one copy
258
+ // for both solves. The arithmetic of chol_solve_compact's solve, in its order (y_r -= L_rk x_k for k ascending, then
259
+ // x_r = y_r / L_rr; backwards likewise), so bitwise its result on the corpora; the division is div_fast (no branch,
260
+ // the reciprocal of L_kk off the chain). Two forms of the same arithmetic in the same plain C (ptxas fuses every update
261
+ // into one fma in both, on sm_70, sm_86, sm_90a and sm_120), so bitwise the same gradients:
262
+ // DK_ADJ_TRI_BLOCKED=1 (the default where 32 < NV <= 35) solves rows 0..31 in blocks of 8 as the forward's
263
+ // chol_resolve: a block's 8 broadcasts are independent, its 8 x 8 triangle is
264
+ // solved redundantly on every lane (broadcast loads of L; the chain: 8 quotients with their in-block updates), then
265
+ // each lane applies the block's 8 columns to its row, so one round of shuffles per block instead of one shuffle per
266
+ // row on the chain; the tail rows 32.. on every lane. k_adjoint on the RTX 3090 (the interface defaults, a 4096-state
267
+ // corpus, 10 iterations, with the lane mask): 5.9% / 6.0% faster at 1787 / 4096 worlds.
268
+ // =0: column by column (lane l holds entries l and l + 32, column k broadcast by __shfl_sync), written for a short
269
+ // step: the step's entries L_kk, L_rk are loaded before the broadcast, at a clamped index valid for every lane,
270
+ // the updates are selects instead of branches, so a step's critical path is the broadcast, three fused multiply-adds
271
+ // of the quotient and the one of the update (unrolled by 5)
272
+ #ifndef DK_ADJ_TRI_BLOCKED
273
+ #define DK_ADJ_TRI_BLOCKED (NV > 32 && NV <= 35)
274
+ #endif
275
+ #if DK_ADJ_TRI_BLOCKED
276
+ static_assert(NV > 32 && NV <= 35, "rows 0..31 on the lanes, a tail of 1..3 rows on every lane");
277
+ #define TRI_NT (NV - 32) // tail rows
278
+ __device__ __noinline__ void tri_solve_packed(const float* L, float* b, int lane) {
279
+ const int r = lane, r1 = min(32 + lane, NV - 1); // lanes 0 .. TRI_NT - 1: tail row 32 + lane (y1); others a dummy
280
+ const int tr = TRI(r, 0), tr1 = TRI(r1, 0); // the rows' starts
281
+ __syncwarp();
282
+ float y = b[r], y1 = b[r1];
283
+ #pragma unroll
284
+ for (int kb = 0; kb < 32; kb += 8) { // forward: L y = b on rows 0..31
285
+ float yb[8];
286
+ #pragma unroll
287
+ for (int j = 0; j < 8; j++) yb[j] = __shfl_sync(0xffffffffu, y, kb + j);
288
+ #pragma unroll
289
+ for (int j = 0; j < 8; j++) {
290
+ float u = yb[j];
291
+ #pragma unroll
292
+ for (int i = 0; i < j; i++) u = u - L[TRI(kb + j, kb + i)] * yb[i];
293
+ const float d = L[TRI(kb + j, kb + j)];
294
+ yb[j] = div_fast(u, d, rcp_step(d));
295
+ }
296
+ #pragma unroll
297
+ for (int j = 0; j < 8; j++) {
298
+ y = r >= kb + 8 ? y - L[tr + min(kb + j, r)] * yb[j] : (r == kb + j ? yb[j] : y);
299
+ y1 = y1 - L[tr1 + kb + j] * yb[j];
300
+ }
301
+ }
302
+ float yt[TRI_NT]; // the tail rows on every lane: forward, backward, then their part of rows 0..31
303
+ #pragma unroll
304
+ for (int t = 0; t < TRI_NT; t++) {
305
+ float u = __shfl_sync(0xffffffffu, y1, t);
306
+ #pragma unroll
307
+ for (int i = 0; i < t; i++) u = u - L[TRI(32 + t, 32 + i)] * yt[i];
308
+ const float d = L[TRI(32 + t, 32 + t)];
309
+ yt[t] = div_fast(u, d, rcp_step(d));
310
+ }
311
+ #pragma unroll
312
+ for (int t = TRI_NT - 1; t >= 0; t--) {
313
+ float u = yt[t];
314
+ #pragma unroll
315
+ for (int i = TRI_NT - 1; i > t; i--) u = u - L[TRI(32 + i, 32 + t)] * yt[i];
316
+ const float d = L[TRI(32 + t, 32 + t)];
317
+ yt[t] = div_fast(u, d, rcp_step(d));
318
+ }
319
+ #pragma unroll
320
+ for (int t = TRI_NT - 1; t >= 0; t--) y = y - L[TRI(32 + t, r)] * yt[t];
321
+ #pragma unroll
322
+ for (int kb = 24; kb >= 0; kb -= 8) { // backward: L' x = y on rows 0..31
323
+ float xb[8];
324
+ #pragma unroll
325
+ for (int j = 0; j < 8; j++) xb[j] = __shfl_sync(0xffffffffu, y, kb + j);
326
+ #pragma unroll
327
+ for (int j = 7; j >= 0; j--) {
328
+ float u = xb[j];
329
+ #pragma unroll
330
+ for (int i = 7; i > j; i--) u = u - L[TRI(kb + i, kb + j)] * xb[i];
331
+ const float d = L[TRI(kb + j, kb + j)];
332
+ xb[j] = div_fast(u, d, rcp_step(d));
333
+ }
334
+ #pragma unroll
335
+ for (int j = 7; j >= 0; j--)
336
+ y = r < kb ? y - L[TRI(kb + j, min(r, kb + j))] * xb[j] : (r == kb + j ? xb[j] : y);
337
+ }
338
+ __syncwarp();
339
+ b[r] = y;
340
+ if (lane == 0) { // (lane t writing entry 32 + t would index yt dynamically)
341
+ #pragma unroll
342
+ for (int t = 0; t < TRI_NT; t++) b[32 + t] = yt[t];
343
+ }
344
+ __syncwarp();
345
+ }
346
+ #undef TRI_NT
347
+ #else
348
+ __device__ __noinline__ void tri_solve_packed(const float* L, float* b, int lane) {
349
+ static_assert(NV <= 64, "two entries per lane");
350
+ const int r0 = lane, r1 = min(lane + 32, NV - 1); // r1: clamped to a valid row (only lanes with has1 use it)
351
+ const bool has1 = lane + 32 < NV;
352
+ const int t0 = TRI(r0, 0), t1 = TRI(r1, 0); // the rows' starts
353
+ __syncwarp();
354
+ float y0 = b[r0], y1 = has1 ? b[r1] : 0.f;
355
+ #pragma unroll 5
356
+ for (int k = 0; k < NV; k++) { // forward: L y = b
357
+ const float d = L[TRI(k, k)], l0 = L[t0 + min(k, r0)], l1 = L[t1 + min(k, r1)];
358
+ const float yk = div_fast(__shfl_sync(0xffffffffu, k < 32 ? y0 : y1, k & 31), d, rcp_step(d));
359
+ y0 = r0 == k ? yk : (r0 > k ? y0 - l0 * yk : y0);
360
+ y1 = r1 == k ? yk : (has1 && r1 > k ? y1 - l1 * yk : y1);
361
+ }
362
+ #pragma unroll 5
363
+ for (int k = NV - 1; k >= 0; k--) { // backward: L' x = y
364
+ const int tk = TRI(k, 0);
365
+ const float d = L[tk + k], l0 = L[tk + min(r0, k)], l1 = L[tk + min(r1, k)];
366
+ const float xk = div_fast(__shfl_sync(0xffffffffu, k < 32 ? y0 : y1, k & 31), d, rcp_step(d));
367
+ y0 = r0 == k ? xk : (r0 < k ? y0 - l0 * xk : y0);
368
+ y1 = r1 == k ? xk : (has1 && r1 < k ? y1 - l1 * xk : y1);
369
+ }
370
+ __syncwarp();
371
+ b[r0] = y0;
372
+ if (has1) b[r1] = y1;
373
+ __syncwarp();
374
+ }
375
+ #endif
376
+
377
+ // out = L (L' x) for a packed lower-triangular L (Q x for L = L_Q); tmp: NV scratch; all shared (-DDK_ADJ_DEBUG: |M a*|)
378
+ __device__ void tri_mul_llt(const float* L, const float* x, float* tmp, float* out, int lane) {
379
+ for (int j = lane; j < NV; j += 32) { // tmp = L' x, column j
380
+ float acc = 0.f;
381
+ for (int i = j; i < NV; i++) acc += L[TRI(i, j)] * x[i];
382
+ tmp[j] = acc;
383
+ }
384
+ __syncwarp();
385
+ for (int i = lane; i < NV; i += 32) { // out = L tmp, row i
386
+ float acc = 0.f;
387
+ for (int j = 0; j <= i; j++) acc += L[TRI(i, j)] * tmp[j];
388
+ out[i] = acc;
389
+ }
390
+ __syncwarp();
391
+ }
392
+
393
+ __device__ __forceinline__ float dot4(const float* a, const float* b) {
394
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
395
+ }
396
+ __device__ __forceinline__ float adj_sinc(float x) { return x * x < 1e-4f ? 1.f - x * x / 6.f : sinf(x) / x; }
397
+ __device__ __forceinline__ float adj_dsinc_x(float x) { // sinc'(x) / x = (x cos x - sin x) / x^3, smooth and even
398
+ return x * x < 1e-4f ? -1.f / 3.f + x * x / 30.f : (x * cosf(x) - sinf(x)) / (x * x * x);
399
+ }
400
+
401
+ // MuJoCo Warp's _adj_quat_integrate: the VJP of q' = normalize(normalize(q) rho), rho = (cos x, (h/2) sinc(x)
402
+ // w), x = (h/2) |w| (the engine's axis-angle update in a form that is smooth at w = 0), for the cotangent g of q':
403
+ // qbar = its cotangent of q (4), wbar = of w (3)
404
+ __device__ void quat_integrate_vjp(const float* q, const float* w, float h, const float* g, float* qbar, float* wbar) {
405
+ float nq2 = dot4(q, q);
406
+ if (nq2 == 0.f) {
407
+ for (int k = 0; k < 4; k++) qbar[k] = 0.f;
408
+ for (int k = 0; k < 3; k++) wbar[k] = 0.f;
409
+ return;
410
+ }
411
+ float hh = 0.5f * h, x = hh * sqrtf(dot3(w, w)), sc = adj_sinc(x), sh = hh * sc, nq = sqrtf(nq2);
412
+ float rho[4] = {cosf(x), sh * w[0], sh * w[1], sh * w[2]}, qn[4], u[4], gu[4], gqn[4], gr[4];
413
+ for (int k = 0; k < 4; k++) qn[k] = q[k] / nq;
414
+ qmul(qn, rho, u);
415
+ float nu = sqrtf(dot4(u, u)), od = 0.f;
416
+ for (int k = 0; k < 4; k++) od += u[k] / nu * g[k];
417
+ for (int k = 0; k < 4; k++) gu[k] = (g[k] - u[k] / nu * od) / nu; // the final normalize
418
+ float rc[4] = {rho[0], -rho[1], -rho[2], -rho[3]}, qc[4] = {qn[0], -qn[1], -qn[2], -qn[3]};
419
+ qmul(gu, rc, gqn); // u = qn rho: the transposes of left / right multiplication are products with the conjugates
420
+ qmul(qc, gu, gr);
421
+ float qd = dot4(qn, gqn);
422
+ for (int k = 0; k < 4; k++) qbar[k] = (gqn[k] - qn[k] * qd) / nq; // qn = normalize(q)
423
+ // rho's dependence on w through x collapses to smooth even functions of x times w (no w / |w|)
424
+ float coef = hh * hh * (-gr[0] * sc + hh * dot3(w, gr + 1) * adj_dsinc_x(x));
425
+ for (int k = 0; k < 3; k++) wbar[k] = sh * gr[1 + k] + coef * w[k];
426
+ }
427
+
428
+ // twist (W, V) of body b's origin for the generalized vector s from its parent's (W angular, V the origin's velocity;
429
+ // z, r: hinge axis and r_b = X_b - X_parent; sb = s at the body's hinge dof); the root's is (R_1 s_rot, s_trans). The
430
+ // same recursion carries channel 2 (s = a~ at v = 0 without gravity: W = AL2, V = A2)
431
+ __device__ __forceinline__ void adj_twist(int b, const float* Q, const float* z, const float* r, const float* Wp,
432
+ const float* Vp, const float* s, float sb, float* W, float* V) {
433
+ if (b == 1) {
434
+ qrot(Q, s + 3, W);
435
+ for (int k = 0; k < 3; k++) V[k] = s[k];
436
+ return;
437
+ }
438
+ float u[3];
439
+ cross(Wp, r, u);
440
+ for (int k = 0; k < 3; k++) { W[k] = Wp[k] + z[k] * sb; V[k] = Vp[k] + u[k]; }
441
+ }
442
+
443
+ // o = I x for the body inertia I = R_i diag(d) R_i' (qi: the inertia frame), as body_force
444
+ __device__ __forceinline__ void inert_mul(const float* qi, const float* d, const float* x, float* o) {
445
+ float l[3];
446
+ qrot_inv(qi, x, l);
447
+ for (int k = 0; k < 3; k++) l[k] *= d[k];
448
+ qrot(qi, l, o);
449
+ }
450
+
451
+ // A4 for body b alone, a pure function of its forward quantities (ipos: COM offset in the body frame, with
452
+ // the torso's DR offset). Its RNE forces about the origin X_b in both channels, F1 = m (A + AL x c + W x (W x c)),
453
+ // N1 = I AL + W x I W + c x F1 (= body_force), F2 = m (A2 + AL2 x c), N2 = I AL2 + c x F2 (c = R_b ipos), and the VJP of
454
+ // psi_b = F1.Vl + N1.Wl + F2.Vy + N2.Wy (virtual work: lambda' ID - y' M a~ = sum_b psi_b): the cotangents of its twists
455
+ // (bVl = F1, bWl = N1, bVy = F2, bWy = N2), of channel 1 (bW, bAL, bA) and channel 2 (bAL2, bA2), and of its own
456
+ // rotation through c and I (tb; its position does not enter psi_b)
457
+ __device__ void body_local_vjp(int b, const float* Q, const float* ipos, const float* W, const float* AL, const float* A,
458
+ const float* AL2, const float* A2, const float* Wl, const float* Vl, const float* Wy,
459
+ const float* Vy, float* bW, float* bAL, float* bA, float* bAL2, float* bA2, float* bWl,
460
+ float* bVl, float* bWy, float* bVy, float* tb) {
461
+ float c[3], qi[4], t[3], u[3], v3[3];
462
+ qrot(Q, ipos, c);
463
+ qmul(Q, c_iquat + 4 * b, qi);
464
+ const float* d = c_inert + 3 * b;
465
+ const float m = c_mass[b];
466
+ float IW[3], IL[3], IL2[3], IWl[3], IWy[3], X[3], IX[3];
467
+ inert_mul(qi, d, W, IW);
468
+ inert_mul(qi, d, AL, IL);
469
+ inert_mul(qi, d, AL2, IL2);
470
+ inert_mul(qi, d, Wl, IWl);
471
+ inert_mul(qi, d, Wy, IWy);
472
+ cross(Wl, W, X); // Wl x W
473
+ inert_mul(qi, d, X, IX);
474
+ // forces (bVl = F1, bWl = N1, bVy = F2, bWy = N2)
475
+ float wc[3], wwc[3], F1[3], F2[3];
476
+ cross(W, c, wc);
477
+ cross(W, wc, wwc);
478
+ cross(AL, c, t);
479
+ for (int k = 0; k < 3; k++) F1[k] = m * (A[k] + t[k] + wwc[k]);
480
+ cross(AL2, c, t);
481
+ for (int k = 0; k < 3; k++) F2[k] = m * (A2[k] + t[k]);
482
+ cross(W, IW, t);
483
+ cross(c, F1, u);
484
+ for (int k = 0; k < 3; k++) { bVl[k] = F1[k]; bWl[k] = IL[k] + t[k] + u[k]; }
485
+ cross(c, F2, u);
486
+ for (int k = 0; k < 3; k++) { bVy[k] = F2[k]; bWy[k] = IL2[k] + u[k]; }
487
+ // channel 1: g = m (Vl + Wl x c) is the cotangent of F1 (Vl directly, Wl through c x F1)
488
+ float g[3], gw[3], cb[3], tau[3];
489
+ cross(Wl, c, t);
490
+ for (int k = 0; k < 3; k++) g[k] = m * (Vl[k] + t[k]);
491
+ cross(c, g, t);
492
+ for (int k = 0; k < 3; k++) { bA[k] = g[k]; bAL[k] = t[k] + IWl[k]; }
493
+ cross(g, W, gw);
494
+ cross(wc, g, t);
495
+ cross(c, gw, u);
496
+ cross(IW, Wl, v3);
497
+ for (int k = 0; k < 3; k++) bW[k] = t[k] + u[k] + v3[k] + IX[k];
498
+ cross(F1, Wl, t); // c bar
499
+ cross(g, AL, u);
500
+ cross(gw, W, v3);
501
+ for (int k = 0; k < 3; k++) cb[k] = t[k] + u[k] + v3[k];
502
+ cross(IL, Wl, t); // rotation of I: (I x) x y bar - x x (I y bar) for each I x
503
+ cross(AL, IWl, u);
504
+ for (int k = 0; k < 3; k++) tau[k] = t[k] - u[k];
505
+ cross(IW, X, t);
506
+ cross(W, IX, u);
507
+ for (int k = 0; k < 3; k++) tau[k] += t[k] - u[k];
508
+ // channel 2 (twist -y): g2 = m (Vy + Wy x c)
509
+ cross(Wy, c, t);
510
+ for (int k = 0; k < 3; k++) g[k] = m * (Vy[k] + t[k]);
511
+ cross(c, g, t);
512
+ for (int k = 0; k < 3; k++) { bA2[k] = g[k]; bAL2[k] = t[k] + IWy[k]; }
513
+ cross(F2, Wy, t);
514
+ cross(g, AL2, u);
515
+ for (int k = 0; k < 3; k++) cb[k] += t[k] + u[k];
516
+ cross(IL2, Wy, t);
517
+ cross(AL2, IWy, u);
518
+ for (int k = 0; k < 3; k++) tau[k] += t[k] - u[k];
519
+ cross(c, cb, t); // c = R_b ipos rotates with the body
520
+ for (int k = 0; k < 3; k++) tb[k] = tau[k] + t[k];
521
+ }
522
+
523
+ // A3, first part: poses (Q_b, X_b) and channel 1 (the twist of v, the accelerations at a* with gravity) by the forward's
524
+ // fwd_body, one tree level at a time. The contact replay needs the poses bitwise the forward's: fwd_body is written
525
+ // with explicit roundings (source.DEVICE), so they are in any kernel and compilation unit (before, with the plain C
526
+ // fused by ptxas by context, only this loop inlined into the kernel as in substep_pre gave them, and a non-inlined
527
+ // version differed by an ulp in 30% of the bodies' quaternions)
528
+ __device__ __forceinline__ void adj_poses(Adj& s, int lane) {
529
+ const int b = lane, d = b < NB ? c_depth[b] : -1, p = b < NB ? c_parent[b] : 0;
530
+ for (int L = 1; L <= MAXD; L++) {
531
+ if (d == L)
532
+ fwd_body(b, s.Q[p], s.X[p], s.W[p], s.V[p], s.AL[p], s.A[p], s.q, s.v, s.a, s.Q[b], s.X[b], s.W[b], s.V[b],
533
+ s.AL[b], s.A[b]);
534
+ __syncwarp();
535
+ }
536
+ }
537
+
538
+ // A3 + A4: the root-to-leaf sweep after adj_poses (hinge axes, channel 2, the twists of lam and ny = -y; one tree level
539
+ // at a time) and the bodies' local VJP; f bar = 0, tau bar from A4 (the contact stage adds to both), and P_q = P_v = 0
540
+ // (after the last read of A .. Vy, whose memory they share). lam and ny are the seeds of the two channels (a zero
541
+ // vector switches one off, both off leave f bar = tau bar = 0: the debug build's split by source)
542
+ __device__ __noinline__ void adj_tree_down(Adj& s, const float* lam, const float* ny, int lane) {
543
+ LANE_BOUND(lane);
544
+ const int b = lane, d = b < NB ? c_depth[b] : -1, p = b < NB ? c_parent[b] : 0;
545
+ // what does not depend on the parent's twists comes before the sweep (off the levels' chain): r_b and the three
546
+ // seeds at the body's dof
547
+ const int i = b >= 2 && b < NB ? c_dadr[b] : 0;
548
+ float r[3];
549
+ for (int k = 0; k < 3; k++) r[k] = b < NB ? s.X[b][k] - s.X[p][k] : 0.f;
550
+ const float sa = s.at[i], sl = lam[i], sy = ny[i];
551
+ for (int L = 1; L <= MAXD; L++) {
552
+ if (d == L) {
553
+ if (b >= 2) qrot(s.Q[b], c_axis + 3 * b, s.z[b]);
554
+ adj_twist(b, s.Q[b], s.z[b], r, s.AL2[p], s.A2[p], s.at, sa, s.AL2[b], s.A2[b]);
555
+ adj_twist(b, s.Q[b], s.z[b], r, s.Wl[p], s.Vl[p], lam, sl, s.Wl[b], s.Vl[b]);
556
+ adj_twist(b, s.Q[b], s.z[b], r, s.Wy[p], s.Vy[p], ny, sy, s.Wy[b], s.Vy[b]);
557
+ }
558
+ __syncwarp();
559
+ }
560
+ if (b >= 1 && b < NB) {
561
+ float ip[3];
562
+ body_ipos(b, s.com, ip);
563
+ body_local_vjp(b, s.Q[b], ip, s.W[b], s.AL[b], s.A[b], s.AL2[b], s.A2[b], s.Wl[b], s.Vl[b], s.Wy[b], s.Vy[b],
564
+ s.bW[b], s.bAL[b], s.bA[b], s.bAL2[b], s.bA2[b], s.bWl[b], s.bVl[b], s.bWy[b], s.bVy[b], s.tb[b]);
565
+ for (int k = 0; k < 3; k++) s.fb[b][k] = 0.f;
566
+ }
567
+ __syncwarp();
568
+ for (int i = lane; i < NV; i += 32) { s.Pq[i] = 0.f; s.Pv[i] = 0.f; }
569
+ __syncwarp();
570
+ }
571
+
572
+ // A7: the leaf-to-root sweep, one tree level at a time. Body b first pulls its children's finished
573
+ // cotangents (the reverse of their recursions from b's quantities; F_b, N_b collect the children's subtree sums as
574
+ // accumulate() does), then finishes its own: P_v of its dof, z bar and r bar, its pose cotangent (tau bar += z x z bar,
575
+ // f bar += r bar, the parent's f bar -= r bar when it pulls), and P_q = z . N_b; the root P_v (angular), P_q (F_1,
576
+ // R_1' N_1). Adds to s.Pq, s.Pv. lam, ny: the seeds of adj_tree_down
577
+ __device__ __noinline__ void adj_tree_up(Adj& s, const float* lam, const float* ny, int lane) {
578
+ LANE_BOUND(lane);
579
+ const int b = lane, d = b < NB ? c_depth[b] : -1, p = b < NB ? c_parent[b] : 0;
580
+ for (int L = MAXD; L >= 1; L--) {
581
+ if (d == L) {
582
+ float bW[3], bAL[3], bA[3], bAL2[3], bA2[3], bWl[3], bVl[3], bWy[3], bVy[3], F[3], N[3], t[3], u[3];
583
+ for (int k = 0; k < 3; k++) {
584
+ bW[k] = s.bW[b][k]; bAL[k] = s.bAL[b][k]; bA[k] = s.bA[b][k]; bAL2[k] = s.bAL2[b][k]; bA2[k] = s.bA2[b][k];
585
+ bWl[k] = s.bWl[b][k]; bVl[k] = s.bVl[b][k]; bWy[k] = s.bWy[b][k]; bVy[k] = s.bVy[b][k];
586
+ F[k] = s.fb[b][k]; N[k] = s.tb[b][k];
587
+ }
588
+ const float* Wb = s.W[b];
589
+ for (int i = 0; i < c_nchild[b]; i++) {
590
+ const int c = c_child[3 * b + i];
591
+ float r[3], zv[3], vc = s.v[c_dadr[c]];
592
+ for (int k = 0; k < 3; k++) { r[k] = s.X[c][k] - s.X[b][k]; zv[k] = s.z[c][k] * vc; }
593
+ const float *cW = s.bW[c], *cAL = s.bAL[c], *cA = s.bA[c];
594
+ // channel 1: W_c = W_b + z qd, AL_c = AL_b + z qdd + W_b x z qd, A_c = A_b + AL_b x r + W_b x (W_b x r)
595
+ cross(zv, cAL, t);
596
+ for (int k = 0; k < 3; k++) bW[k] += cW[k] + t[k];
597
+ cross(Wb, r, u);
598
+ cross(u, cA, t);
599
+ for (int k = 0; k < 3; k++) bW[k] += t[k];
600
+ cross(cA, Wb, u);
601
+ cross(r, u, t);
602
+ for (int k = 0; k < 3; k++) bW[k] += t[k];
603
+ cross(r, cA, t);
604
+ for (int k = 0; k < 3; k++) { bAL[k] += cAL[k] + t[k]; bA[k] += cA[k]; }
605
+ // channel 2 and the twists: W_c = W_b + z s, V_c = V_b + W_b x r
606
+ cross(r, s.bA2[c], t);
607
+ for (int k = 0; k < 3; k++) { bAL2[k] += s.bAL2[c][k] + t[k]; bA2[k] += s.bA2[c][k]; }
608
+ cross(r, s.bVl[c], t);
609
+ for (int k = 0; k < 3; k++) { bWl[k] += s.bWl[c][k] + t[k]; bVl[k] += s.bVl[c][k]; }
610
+ cross(r, s.bVy[c], t);
611
+ for (int k = 0; k < 3; k++) { bWy[k] += s.bWy[c][k] + t[k]; bVy[k] += s.bVy[c][k]; }
612
+ // pose sweep: F_b += F_c - r bar_c (the parent's share of r bar_c), N_b += N_c + r x F_c
613
+ cross(r, s.fb[c], t);
614
+ for (int k = 0; k < 3; k++) { F[k] += s.fb[c][k] - s.rb[c][k]; N[k] += s.tb[c][k] + t[k]; }
615
+ }
616
+ if (b >= 2) {
617
+ const int i = c_dadr[b];
618
+ const float *z = s.z[b], *Wp = s.W[p];
619
+ const float qd = s.v[i];
620
+ float zb[3], rb[3];
621
+ cross(Wp, z, t);
622
+ s.Pv[i] += dot3(z, bW) + dot3(bAL, t);
623
+ cross(bAL, Wp, t);
624
+ for (int k = 0; k < 3; k++)
625
+ zb[k] = qd * (bW[k] + t[k]) + s.a[i] * bAL[k] + s.at[i] * bAL2[k] + lam[i] * bWl[k] + ny[i] * bWy[k];
626
+ cross(bA, s.AL[p], rb);
627
+ cross(bA, Wp, u);
628
+ cross(u, Wp, t);
629
+ for (int k = 0; k < 3; k++) rb[k] += t[k];
630
+ cross(bA2, s.AL2[p], t);
631
+ for (int k = 0; k < 3; k++) rb[k] += t[k];
632
+ cross(bVl, s.Wl[p], t);
633
+ for (int k = 0; k < 3; k++) rb[k] += t[k];
634
+ cross(bVy, s.Wy[p], t);
635
+ for (int k = 0; k < 3; k++) rb[k] += t[k];
636
+ cross(z, zb, t); // z_b = R_b axis rotates with the body
637
+ for (int k = 0; k < 3; k++) { N[k] += t[k]; F[k] += rb[k]; s.rb[b][k] = rb[k]; }
638
+ s.Pq[i] += dot3(z, N);
639
+ } else { // root: W_1 = R_1 w, AL_1 = R_1 a_w, AL2_1, Wl_1, Wy_1 likewise; its A, A2, V's do not depend on the pose
640
+ float l[3];
641
+ qrot_inv(s.Q[1], bW, l);
642
+ for (int k = 0; k < 3; k++) s.Pv[3 + k] += l[k];
643
+ cross(s.W[1], bW, t);
644
+ for (int k = 0; k < 3; k++) N[k] += t[k];
645
+ cross(s.AL[1], bAL, t);
646
+ for (int k = 0; k < 3; k++) N[k] += t[k];
647
+ cross(s.AL2[1], bAL2, t);
648
+ for (int k = 0; k < 3; k++) N[k] += t[k];
649
+ cross(s.Wl[1], bWl, t);
650
+ for (int k = 0; k < 3; k++) N[k] += t[k];
651
+ cross(s.Wy[1], bWy, t);
652
+ for (int k = 0; k < 3; k++) N[k] += t[k];
653
+ qrot_inv(s.Q[1], N, l);
654
+ for (int k = 0; k < 3; k++) { s.Pq[k] += F[k]; s.Pq[3 + k] += l[k]; }
655
+ }
656
+ for (int k = 0; k < 3; k++) { // publish for the parent
657
+ s.bW[b][k] = bW[k]; s.bAL[b][k] = bAL[k]; s.bA[b][k] = bA[k]; s.bAL2[b][k] = bAL2[k]; s.bA2[b][k] = bA2[k];
658
+ s.bWl[b][k] = bWl[k]; s.bVl[b][k] = bVl[k]; s.bWy[b][k] = bWy[k]; s.bVy[b][k] = bVy[k];
659
+ s.fb[b][k] = F[k]; s.tb[b][k] = N[k];
660
+ }
661
+ }
662
+ __syncwarp();
663
+ }
664
+ }
665
+
666
+ // A1: the integrator's VJP. In: qbar, vbar = the cotangents of q' = q (+) h v', v' = v + h a_adv; out:
667
+ // qbar = its direct part (translation, hinges unchanged; the quaternion through quat_integrate_vjp), vbar = v' bar,
668
+ // abar = a_adv bar = h v' bar. w' = v'_rot rebuilt as the forward computes it (fmaf), bitwise the same
669
+ __device__ void adj_integrator(Adj& s, int lane) {
670
+ const float h = c_misc[0];
671
+ for (int i = lane; i < NV; i += 32) {
672
+ if (i < 3) s.vbar[i] += h * s.qbar[i];
673
+ else if (i >= 6) s.vbar[i] += h * s.qbar[i + 1];
674
+ }
675
+ if (lane == 0) {
676
+ float w[3], qb[4], wb[3];
677
+ for (int k = 0; k < 3; k++) w[k] = fmaf(h, s.aadv[3 + k], s.v[3 + k]);
678
+ quat_integrate_vjp(s.q + 3, w, h, s.qbar + 3, qb, wb);
679
+ for (int k = 0; k < 4; k++) s.qbar[3 + k] = qb[k];
680
+ for (int k = 0; k < 3; k++) s.vbar[3 + k] += wb[k];
681
+ }
682
+ __syncwarp();
683
+ for (int i = lane; i < NV; i += 32) s.abar[i] = h * s.vbar[i];
684
+ __syncwarp();
685
+ }
686
+
687
+ // A1 / A2, from abar = a_adv bar: y = Q^-1 a_adv bar (L_Q), abar = a* bar = M y = a_adv bar - h kv y (Q = M + h
688
+ // diag(kv) and Q y = a_adv bar; exact to rounding, unlike the product form L_Q (L_Q' y) - h kv y, whose float32 error
689
+ // grows with cond(Q) ~ 4e3), ny = -y, lam = H^-1 a* bar (L_H). rec: the substep's record
690
+ // (the factors, read once: streaming loads)
691
+ __device__ __noinline__ void adj_solves(Adj& s, const float* rec, int lane) {
692
+ LANE_BOUND(lane);
693
+ const float h = c_misc[0];
694
+ #if DK_CLAMP_IMPLICIT == 1
695
+ for (int i = lane; i < NV; i += 32) // MuJoCo 4.0: no implicit damping on a clamped dof (the record's mask)
696
+ s.kvi[i] = (s.clamp[i >> 5] >> (i & 31)) & 1u ? 0.f : c_kv[i];
697
+ #elif DK_CLAMP_IMPLICIT == 2
698
+ for (int i = lane; i < NV; i += 32) { // the recorded weights: kv w, w = |sign(f) w|
699
+ const float wv = __ldcs(rec + OFF_KVW + i);
700
+ s.kvw[i] = wv;
701
+ s.kvi[i] = c_kv[i] * fabsf(wv);
702
+ }
703
+ #endif
704
+ for (int e = lane; e < NTRI; e += 32) s.L[e] = __ldcs(rec + OFF_LQ + e);
705
+ for (int i = lane; i < NV; i += 32) s.y[i] = s.abar[i];
706
+ tri_solve_packed(s.L, s.y, lane);
707
+ for (int i = lane; i < NV; i += 32) { s.abar[i] -= h * KVI(i) * s.y[i]; s.ny[i] = -s.y[i]; }
708
+ __syncwarp();
709
+ APROF(APROF_SOLVE_Q);
710
+ #ifdef DK_ADJ_DEBUG
711
+ { // |M a*| for the residual check's scale
712
+ tri_mul_llt(s.L, s.a, s.tmp, s.did, lane);
713
+ float acc = 0.f;
714
+ for (int i = lane; i < NV; i += 32) { float x = s.did[i] - h * KVI(i) * s.a[i]; acc += x * x; }
715
+ acc = warp_sum(acc);
716
+ if (lane == 0) s.ma_norm = sqrtf(acc);
717
+ __syncwarp();
718
+ }
719
+ #endif
720
+ for (int e = lane; e < NTRI; e += 32) s.L[e] = __ldcs(rec + OFF_LH + e);
721
+ for (int i = lane; i < NV; i += 32) s.lam[i] = s.abar[i];
722
+ tri_solve_packed(s.L, s.lam, lane);
723
+ }
724
+
725
+ // lam on the dofs whose actuator force is not clamped (the record's mask; MuJoCo Warp's actuator_lam), 0 elsewhere
726
+ __device__ __forceinline__ float lam_unclamped(const Adj& s, int i) {
727
+ return i >= 6 && !((s.clamp[i >> 5] >> (i & 31)) & 1u) ? s.lam[i] : 0.f;
728
+ }
729
+
730
+ #if DK_ADJ_CLAMP_KV == 2
731
+ // the soft clamp's lam~ (DK_ADJ_CLAMP_KV=2): lam on an unclamped dof (lam_unclamped's value),
732
+ // w lam on a clamped one (the record's mask), w = exp(-o / delta), o = max((|f| - tau_max) / tau_max, 0) the relative
733
+ // overshoot of the unclamped PD force f = kp (u - q) - kv v at the substep's input (the forward's expression; the
734
+ // model's clamp is per dof: jnt_actfrcrange of the dof's hinge, symmetric, one gear-1 actuator per hinge,
735
+ // source.constants asserts it), delta = s.soft. A dof clamped by the tape whose recomputed f rounds to within its
736
+ // bound gets o = 0, w = 1 (the derivative is continuous at the bound, so the FMA contraction of f does not matter as
737
+ // it would for the mask). delta <= 0, or w underflowing to 0, gives 0: the build with DK_ADJ_CLAMP_KV=1 bitwise
738
+ __device__ __forceinline__ float lam_soft(const Adj& s, int i) {
739
+ if (i < 6) return 0.f;
740
+ if (!((s.clamp[i >> 5] >> (i & 31)) & 1u)) return s.lam[i];
741
+ if (!(s.soft > 0.f)) return 0.f;
742
+ const float f = c_kp[i] * (s.u[i - 6] - s.q[i + 1]) - c_kv[i] * s.v[i], fmax = c_frclim[i];
743
+ const float w = expf(-fmaxf((fabsf(f) - fmax) / fmax, 0.f) / s.soft);
744
+ return w > 0.f ? w * s.lam[i] : 0.f;
745
+ }
746
+ #define LAM_ACT(s, i) lam_soft(s, i)
747
+ #else
748
+ #define LAM_ACT(s, i) lam_unclamped(s, i)
749
+ #endif
750
+
751
+ // A8: the actuator's part of P (P_q += kp lam~, P_v += kv lam (DK_ADJ_CLAMP_KV: kv lam~), u bar +=
752
+ // kp lam~; DK_ADJ_CLAMP_KV=2: lam~ of lam_soft), then the substep's input cotangents q bar = q bar_dir -
753
+ // dof_to_qpos(P_q; xi_k) (MuJoCo Warp's _dof_to_qpos: 2 xi (0, P_rot), xi not normalized) and v bar = v' bar - P_v
754
+ __device__ void adj_compose(Adj& s, int lane) {
755
+ #if DK_CLAMP_IMPLICIT == 2
756
+ { // the fading implicit damping kv w(f) of the clamped dofs: Q's diagonal h kv w gets w bar = h kv ny a_adv (the
757
+ // armature's and damping's rule, y = -ny; a_adv = a* - a~, s.aadv is dead here), w = exp(-o / delta) gives
758
+ // f bar = w bar dw/df with dw/df = -sign(f) w / (delta tau) where o > 0 (|wv| < 1 on a clamped dof), and
759
+ // f = kp (u - q) - kv v takes f bar as the force's lam does
760
+ const float h = c_misc[0];
761
+ for (int i = 6 + lane; i < NV; i += 32) {
762
+ const float wv = s.kvw[i];
763
+ if (!((s.clamp[i >> 5] >> (i & 31)) & 1u) || !(fabsf(wv) < 1.f)) continue;
764
+ const float fb = h * c_kv[i] * s.ny[i] * (s.a[i] - s.at[i]) * (-wv / (DK_CLAMP_IMPLICIT_DELTA * c_frclim[i]));
765
+ s.Pq[i] += c_kp[i] * fb;
766
+ s.Pv[i] += c_kv[i] * fb;
767
+ s.ubar[i - 6] += c_kp[i] * fb;
768
+ }
769
+ __syncwarp();
770
+ }
771
+ #endif
772
+ for (int i = 6 + lane; i < NV; i += 32) {
773
+ float lt = LAM_ACT(s, i), kl = c_kp[i] * lt;
774
+ s.Pq[i] += kl;
775
+ s.Pv[i] += c_kv[i] * (DK_ADJ_CLAMP_KV ? lt : s.lam[i]);
776
+ s.ubar[i - 6] += kl;
777
+ }
778
+ __syncwarp();
779
+ for (int i = lane; i < NV; i += 32) {
780
+ if (i < 3) s.qbar[i] -= s.Pq[i];
781
+ else if (i >= 6) s.qbar[i + 1] -= s.Pq[i];
782
+ s.vbar[i] -= s.Pv[i];
783
+ }
784
+ if (lane == 0) {
785
+ float g[4] = {0.f, s.Pq[3], s.Pq[4], s.Pq[5]}, t[4];
786
+ qmul(s.q + 3, g, t);
787
+ for (int k = 0; k < 4; k++) s.qbar[3 + k] -= 2.f * t[k];
788
+ }
789
+ __syncwarp();
790
+ }
791
+
792
+ #if DK_ADJ_STAGE >= 2
793
+ // kbimp_d and efc_D_d of one row in a single non-inlined copy for the limit rows and the contacts (their solimp power
794
+ // branch inlines powf): out = (k, b, imp, dimp, D, dD) of the row with impedance parameters solref, solimp at pos and
795
+ // invweight invw, the forward's expressions (substep_pre). ADJ_SOLIMP_POWER (header(m): the model's rows share one
796
+ // power, 2 for mjlab's G1) replaces solimp[4] by that constant, the same value: kbimp's and kbimp_d's branches on the
797
+ // power fold at compile time and powf is not compiled for the powers 1 and 2 (1324 -> 310 SASS instructions)
798
+ __device__ __noinline__ void adj_row_impedance(const float* solref, const float* solimp, float pos, float invw,
799
+ float* out) {
800
+ #ifdef ADJ_SOLIMP_POWER
801
+ const float si[5] = {solimp[0], solimp[1], solimp[2], solimp[3], ADJ_SOLIMP_POWER};
802
+ kbimp_d(solref, si, pos, c_misc[0], out, out + 1, out + 2, out + 3);
803
+ #else
804
+ kbimp_d(solref, solimp, pos, c_misc[0], out, out + 1, out + 2, out + 3);
805
+ #endif
806
+ efc_D_d(invw, out[2], out[3], out + 4, out + 5);
807
+ }
808
+
809
+ // A5 / A6, joint limits, one lane per dof: the hinge-limit rows replayed with the forward's test
810
+ // (substep_pre: one IEEE subtraction per side, so bitwise the forward's rows), row r = the number of limit rows of the
811
+ // dofs before (dof order: the first rows); a row on its quadratic zone (the tape's bit) adds limit_row_vjp's P_phi,
812
+ // P_v to its dof. A count other than the tape header's sets ADJ_REPLAY_MISMATCH. DBG (the debug build's pass by
813
+ // source, -DDK_ADJ_DEBUG): writes every dof's limit-row x, row force and kink to dbg. The production pass is the <false>
814
+ // instance in every build, so its code, and with it its rounding (ptxas fuses mul / add by context), is the same with
815
+ // and without -DDK_ADJ_DEBUG (as one function with a run-time dbg, 5 of a corpus's 4096 worlds differed by 1e-7)
816
+ template <bool DBG>
817
+ __device__ __noinline__ void adj_limits(Adj& s, int lane, float* dbg_in) {
818
+ LANE_BOUND(lane);
819
+ float* const dbg = DBG ? dbg_in : nullptr;
820
+ (void)dbg; // no debug entries without -DDK_ADJ_DEBUG
821
+ const unsigned below = (1u << lane) - 1u;
822
+ int nl = 0;
823
+ #pragma unroll 1
824
+ for (int i0 = 0; i0 < NV; i0 += 32) {
825
+ const int i = min(i0 + lane, NV - 1); // clamped so that the loads need no branch (as the forward)
826
+ float dmin, dmax;
827
+ limit_dists(i, s.q[i + 1], &dmin, &dmax); // the forward's test (step.py)
828
+ const bool on = i0 + lane < NV && i >= 6 && c_jlim[i] != 0.f && fminf(dmin, dmax) < 0.f;
829
+ const unsigned bal = __ballot_sync(0xffffffffu, on);
830
+ if (on) {
831
+ const int r = nl + __popc(bal & below);
832
+ const float pos = fminf(dmin, dmax), sg = dmin < dmax ? 1.f : -1.f; // lower limit: J = +e_i, upper: -e_i
833
+ const bool act = (s.zone[r >> 5] >> (r & 31)) & 1u;
834
+ float ri[6], pq, pv;
835
+ adj_row_impedance(c_jsolref, c_jsolimp, pos, c_dinvw[i], ri);
836
+ const float k = ri[0], b = ri[1], imp = ri[2], dimp = ri[3], D = ri[4], dD = ri[5];
837
+ if (act) {
838
+ limit_row_vjp(sg, pos, s.a[i], s.v[i], s.lam[i], k, b, imp, dimp, D, dD, &pq, &pv);
839
+ s.Pq[i] += pq;
840
+ s.Pv[i] += pv;
841
+ }
842
+ #ifdef DK_ADJ_DEBUG
843
+ if (dbg) {
844
+ const float ja = sg * s.a[i], aref = -k * imp * pos - b * (sg * s.v[i]), x = ja - aref;
845
+ dbg[DBG_LIM_X + i] = x;
846
+ dbg[DBG_LIM_FORCE + i] = act ? -D * x : 0.f;
847
+ dbg[DBG_LIM_KINK + i] = fabsf(x) / fmaxf(fabsf(ja) + fabsf(aref), 1e-30f);
848
+ }
849
+ #endif
850
+ }
851
+ #ifdef DK_ADJ_DEBUG
852
+ else if (dbg && i0 + lane < NV) {
853
+ dbg[DBG_LIM_X + i0 + lane] = 0.f; dbg[DBG_LIM_FORCE + i0 + lane] = 0.f; dbg[DBG_LIM_KINK + i0 + lane] = DBG_NO_ROW;
854
+ }
855
+ #endif
856
+ nl += __popc(bal);
857
+ }
858
+ if (lane == 0 && nl != (int)(((unsigned)s.hdr >> 16) & 255u)) s.flags |= (int)ADJ_REPLAY_MISMATCH;
859
+ __syncwarp();
860
+ APROF_COUNT(APROF_COUNT_LIMIT_ROWS, nl);
861
+ APROF(APROF_LIMITS);
862
+ }
863
+
864
+ // A5 / A6 of contact c of the tape's table, (pair, slot) with the zone bits of its rows (bit e: row e on its quadratic
865
+ // zone), on its own lane: the replay (adj_pair_geom: dist, pos, frame bitwise the forward's), the rows' impedance with
866
+ // the forward's expressions (substep_pre: mu = the world's foot friction on a foot pair, the pyramid invweight for
867
+ // condim 3, kbimp_d / efc_D_d), the contact point's motions V_v, V_a, V_lam = sum over the support dofs of
868
+ // s_i col_i (v_i, a*_i, lam_i) and their angular parts Om_* = sum over the rotational ones of s_i z_i (.)_i (support:
869
+ // the dofs on exactly one of the two chains, s_i = +1 on body 2's; col_i = z_i x (p - x_i), x_i the origin of the dof's
870
+ // body, X_1 for the root rotations; e_k for the root translations), contact_psi_vjp, p bar = contact_pbar_motion, the
871
+ // primitive's VJP (adj_pair_geom with the cotangents) and geom_to_body_vjp of both geoms (the floor takes none). Writes
872
+ // cs[CS_N] (the lane's registers): W_v, W_a, W_lam, p, the geometry's (f bar, tau bar) of body 1 and of body 2.
873
+ // Returns the replayed distance. dbg (-DDK_ADJ_DEBUG, may be null): the contact's debug entries
874
+ __device__ __forceinline__ float adj_contact_one(Adj& s, int c, int pair, int slot, unsigned zone, float* cs,
875
+ float* dbg) {
876
+ const int g1 = PG1(pair), g2 = PG2(pair), b1 = c_gbody[g1], b2 = c_gbody[g2], dim = PDIM(pair);
877
+ float d, p[3], fr[9], nu;
878
+ const int br = adj_pair_geom(pair, slot, s.gx, s.gq, &d, p, fr, &nu, nullptr, nullptr);
879
+ const float mu = PFOOT(pair) ? s.fric : PMU(pair);
880
+ float ri[6];
881
+ adj_row_impedance(PSOLREF(pair), PSOLIMP(pair), d, contact_invw(pair, mu), ri);
882
+ const float k = ri[0], b = ri[1], imp = ri[2], dimp = ri[3], D = ri[4], dD = ri[5];
883
+ float Vv[3] = {0.f, 0.f, 0.f}, Va[3] = {0.f, 0.f, 0.f}, Vl[3] = {0.f, 0.f, 0.f};
884
+ float Ov[3] = {0.f, 0.f, 0.f}, Oa[3] = {0.f, 0.f, 0.f}, Ol[3] = {0.f, 0.f, 0.f};
885
+ const unsigned m1 = c_ancmask[b1], m2 = c_ancmask[b2], sup = m1 ^ m2; // body bits on exactly one chain
886
+ if ((sup >> 1) & 1u) { // the root in the support (a floor contact): its translations, columns e_k
887
+ const float sg = (m2 >> 1) & 1u ? 1.f : -1.f;
888
+ for (int t = 0; t < 3; t++) { Vv[t] = sg * s.v[t]; Va[t] = sg * s.a[t]; Vl[t] = sg * s.lam[t]; }
889
+ }
890
+ // the support's rotational dofs in ascending order, the same terms in the same order as a loop over all dofs that
891
+ // skips the others (a lane runs only its own, about half of the 32): the root's rotations 3, 4, 5 if the root is
892
+ // in the support, then one hinge dof i = b + ADJ_HINGE_DOF0 per body bit b >= 2, lowest first (header(m) asserts it)
893
+ unsigned hb = sup & ~3u; // the support's hinge bodies (bit 0: the world, 1: the root)
894
+ int i = (sup >> 1) & 1u ? 3 : (hb ? __ffs(hb) - 1 + ADJ_HINGE_DOF0 : NV);
895
+ #pragma unroll 1
896
+ for (; i < NV; i = i < 5 ? i + 1 : (hb ? __ffs(hb) - 1 + ADJ_HINGE_DOF0 : NV)) {
897
+ const int bi = i < 6 ? 1 : i - ADJ_HINGE_DOF0;
898
+ if (i >= 6) hb &= hb - 1u;
899
+ const float sg = (m2 >> bi) & 1u ? 1.f : -1.f, vi = sg * s.v[i], ai = sg * s.a[i], li = sg * s.lam[i];
900
+ const float* z = i < 6 ? s.zr[i - 3] : s.z[bi];
901
+ float r[3], col[3];
902
+ for (int t = 0; t < 3; t++) r[t] = p[t] - s.X[bi][t];
903
+ cross(z, r, col);
904
+ for (int t = 0; t < 3; t++) {
905
+ Vv[t] += vi * col[t]; Va[t] += ai * col[t]; Vl[t] += li * col[t];
906
+ Ov[t] += vi * z[t]; Oa[t] += ai * z[t]; Ol[t] += li * z[t];
907
+ }
908
+ }
909
+ float Wv[3], Wa[3], Wl[3], cot[13], fg[12]; // cot = (d bar, p bar, frame bar): adj_contact_geom's cotangent
910
+ contact_psi_vjp(Vv, Va, Vl, fr, mu, dim, zone, d, D, dD, k, b, imp, dimp, Wv, Wa, Wl, cot, cot + 4);
911
+ cot[1] = cot[2] = cot[3] = 0.f;
912
+ contact_pbar_motion(Wv, Wa, Wl, Ov, Oa, Ol, cot + 1);
913
+ for (int t = 0; t < 12; t++) fg[t] = 0.f;
914
+ if (zone) { // the primitive's VJP (it replays again) and the geoms' pose cotangents on their bodies
915
+ float d2, p2[3], fr2[9], nu2, gb[12];
916
+ adj_pair_geom(pair, slot, s.gx, s.gq, &d2, p2, fr2, &nu2, cot, gb);
917
+ if (b1) geom_to_body_vjp(s.gx[g1], s.X[b1], gb, gb + 3, fg, fg + 3);
918
+ geom_to_body_vjp(s.gx[g2], s.X[b2], gb + 6, gb + 9, fg + 6, fg + 9);
919
+ }
920
+ for (int t = 0; t < 3; t++) {
921
+ cs[t] = Wv[t]; cs[3 + t] = Wa[t]; cs[6 + t] = Wl[t]; cs[9 + t] = p[t];
922
+ }
923
+ for (int t = 0; t < 12; t++) cs[12 + t] = fg[t];
924
+ #ifdef DK_ADJ_DEBUG
925
+ if (dbg) { // replay, cotangents, rows (x, kink, force) and the state groups' diagnostics (reference.adjoint_groups)
926
+ dbg[DBG_CON_DIST + c] = d;
927
+ dbg[DBG_CON_DIST_BAR + c] = cot[0];
928
+ dbg[DBG_CON_BR + c] = (float)br;
929
+ for (int t = 0; t < 3; t++) { dbg[DBG_CON_POS + 3 * c + t] = p[t]; dbg[DBG_CON_POS_BAR + 3 * c + t] = cot[1 + t]; }
930
+ for (int t = 0; t < 9; t++) dbg[DBG_CON_FRAME_BAR + 9 * c + t] = cot[4 + t];
931
+ float vf[3], af[3], F[3] = {0.f, 0.f, 0.f}, kink = DBG_NO_ROW;
932
+ for (int j = 0; j < 3; j++) { vf[j] = dot3(fr + 3 * j, Vv); af[j] = dot3(fr + 3 * j, Va); }
933
+ for (int e = 0; e < (dim == 3 ? 4 : 1); e++) {
934
+ const int t = 1 + (e >> 1);
935
+ const float sm = dim == 3 ? ((e & 1) ? -mu : mu) : 0.f;
936
+ const float uv = vf[0] + sm * vf[t], ua = af[0] + sm * af[t], aref = -k * imp * d - b * uv, x = ua - aref;
937
+ dbg[DBG_CON_X + 4 * c + e] = x;
938
+ kink = fminf(kink, fabsf(x) / fmaxf(fabsf(ua) + fabsf(aref), 1e-30f));
939
+ if ((zone >> e) & 1u)
940
+ for (int q = 0; q < 3; q++) F[q] += -D * x * (fr[q] + sm * fr[3 * t + q]);
941
+ }
942
+ for (int q = 0; q < 3; q++) dbg[DBG_CON_FORCE + 3 * c + q] = F[q];
943
+ dbg[DBG_CON_KINK + c] = kink;
944
+ float basis = DBG_NO_ROW, sfree = DBG_NO_ROW, a1[3], a2[3], w[3];
945
+ const int t1 = c_gtype[g1], t2 = c_gtype[g2];
946
+ zaxis_rn(s.gq[g1], a1);
947
+ zaxis_rn(s.gq[g2], a2);
948
+ if (t1 != 0) basis = fabsf(fabsf(fr[1]) - 0.5f); // self contact: make_frame's basis test on n_y
949
+ else if (t2 == 2) { // plane-capsule: the projected axis length beta against 0.5
950
+ const float na = dot3(fr, a2);
951
+ for (int q = 0; q < 3; q++) w[q] = a2[q] - fr[q] * na;
952
+ basis = fabsf(sqrtf(dot3(w, w)) - 0.5f);
953
+ }
954
+ if (t1 == 2 && t2 == 2 && (br & ADJ_BR_FREE1) && (br & ADJ_BR_FREE2)) {
955
+ cross(a1, a2, w);
956
+ sfree = sqrtf(dot3(w, w));
957
+ }
958
+ dbg[DBG_CON_BASIS + c] = basis;
959
+ dbg[DBG_CON_SIN_FREE + c] = sfree;
960
+ }
961
+ #endif
962
+ (void)nu;
963
+ return d;
964
+ }
965
+
966
+ // A5 / A6, contacts: the collision geoms' world poses from the body poses (geom_poses of the forward,
967
+ // so the replay is bitwise its collision) and the root's rotation axes, then the tape's contacts in batches of 32 with
968
+ // one lane per contact (adj_contact_one into the lane's registers; row offsets as substep_pre: the limit rows first,
969
+ // then per contact 4 pyramid rows (condim 3) or 1, rows past NEFC dropped), and one lane per body that sums the batch
970
+ // in contact order, each contact's words broadcast from its lane by shuffles (no shared scratch, 3200 B per world;
971
+ // the body-1 words only for a self contact; the batch loops are uniform for the compiler, see below): for each contact
972
+ // whose support holds its dof, G_i = s_i (v_i W_v + a*_i W_a + lam_i W_lam), P_v,i += s_i col_i . W_v,
973
+ // f bar += z_i x G_i, tau bar += z_i x ((p - x_i) x G_i) (contact_dof_vjp; lane 1: the root translations and rotation
974
+ // dof 3, lanes 0 and 31: rotation dofs 4 and 5, handed to lane 1 after the batch), and the geometry's pose cotangents
975
+ // of its body. Adds to s.fb, s.tb (bodies) and s.Pv (dofs): a fixed order, independent of scheduling. DK_ADJ_STAGE 2:
976
+ // plane contacts only (records with self contacts set ADJ_ROWS_SKIPPED). DBG: the debug build's pass by source, which
977
+ // writes every contact's debug entries (also without a quadratic row) to dbg; production: <false> (see adj_limits)
978
+ template <bool DBG>
979
+ __device__ __noinline__ void adj_contacts(Adj& s, int lane, float* dbg_in) {
980
+ LANE_BOUND(lane);
981
+ float* const dbg = DBG ? dbg_in : nullptr;
982
+ (void)dbg; // no debug entries without -DDK_ADJ_DEBUG
983
+ // ncon through votes (uniform_int, step.py), and UNIFORM for the per-contact branches: the batch loops and the
984
+ // shuffles in them are then uniform for the compiler (no divergence checks; see step.py UNIFORM). Without the votes
985
+ // the shuffles cost 5% of k_adjoint (RTX 3090, at 6 worlds per SM)
986
+ const int ncon = uniform_int(s.hdr & 255, 8), nlim = ((unsigned)s.hdr >> 16) & 255;
987
+ for (int g = lane; g < NGEOMC; g += 32) { // geom_poses (step.py)
988
+ const int b = c_gbody[g];
989
+ geom_pose(g, s.Q[b], s.X[b], s.gx[g], s.gq[g]);
990
+ }
991
+ if (lane < 3) {
992
+ const float e[3] = {lane == 0 ? 1.f : 0.f, lane == 1 ? 1.f : 0.f, lane == 2 ? 1.f : 0.f};
993
+ qrot(s.Q[1], e, s.zr[lane]);
994
+ }
995
+ #ifdef DK_ADJ_DEBUG
996
+ if (dbg) {
997
+ for (int g = lane; g < NGEOMC; g += 32)
998
+ for (int k = 0; k < 4; k++) {
999
+ if (k < 3) dbg[DBG_GEOM_X + 3 * g + k] = s.gx[g][k];
1000
+ dbg[DBG_GEOM_Q + 4 * g + k] = s.gq[g][k];
1001
+ }
1002
+ for (int b = lane; b < NB; b += 32)
1003
+ for (int k = 0; k < 4; k++) {
1004
+ if (k < 3) dbg[DBG_BODY_X + 3 * b + k] = s.X[b][k];
1005
+ dbg[DBG_BODY_Q + 4 * b + k] = s.Q[b][k];
1006
+ }
1007
+ }
1008
+ #endif
1009
+ __syncwarp();
1010
+ APROF_COUNT(APROF_COUNT_CONTACTS, ncon);
1011
+ APROF(APROF_CONTACT_SETUP);
1012
+ const unsigned below = (1u << lane) - 1u;
1013
+ const bool body = lane >= 1 && lane < NB, rot = lane == 0 || lane == 31;
1014
+ const int rb = body ? lane : 1, rk = lane == 0 ? 1 : (lane == 31 ? 2 : 0), di = rb >= 2 ? c_dadr[rb] : 3 + rk;
1015
+ int ntri = 0; // condim-3 contacts before the batch
1016
+ for (int c0 = 0; c0 < ncon; c0 += 32) {
1017
+ const int c = c0 + lane, nb = min(32, ncon - c0);
1018
+ const bool on = c < ncon;
1019
+ const unsigned e = on ? (s.con[c >> 1] >> (16 * (c & 1))) & 0xFFFFu : 0u;
1020
+ const int pair = e & 511u, slot = e >> 9, dim = on ? PDIM(pair) : 0;
1021
+ const unsigned b3 = __ballot_sync(0xffffffffu, dim == 3);
1022
+ const int r0 = nlim + c + 3 * (ntri + __popc(b3 & below)); // the contact's first row
1023
+ ntri += __popc(b3);
1024
+ const bool use = on && (DK_ADJ_STAGE >= 3 || c_gbody[PG1(pair)] == 0);
1025
+ unsigned zone = 0u;
1026
+ if (use && r0 < NEFC) {
1027
+ const int nr = min(dim == 3 ? 4 : 1, NEFC - r0), w = r0 >> 5;
1028
+ unsigned long long zz = s.zone[w];
1029
+ if (w + 1 < (NEFC + 31) / 32) zz |= (unsigned long long)s.zone[w + 1] << 32;
1030
+ zone = (unsigned)(zz >> (r0 & 31)) & ((1u << nr) - 1u);
1031
+ }
1032
+ bool bad = false;
1033
+ int cb = -1; // body 1 | body 2 << 8 of a contact with a quadratic row, -1: nothing to add
1034
+ float cw[CS_N]; // the lane's contact (adj_contact_one), read by the body lanes by shuffles
1035
+ #pragma unroll
1036
+ for (int k = 0; k < CS_N; k++) cw[k] = 0.f;
1037
+ if (use && (zone || dbg)) { // a contact without a quadratic row adds nothing (MuJoCo Warp's _contact_any_active)
1038
+ bad = !(adj_contact_one(s, c, pair, slot, zone, cw, dbg) < 0.f);
1039
+ if (zone) cb = c_gbody[PG1(pair)] | c_gbody[PG2(pair)] << 8;
1040
+ }
1041
+ const unsigned skip = __ballot_sync(0xffffffffu, on && !use), mis = __ballot_sync(0xffffffffu, bad);
1042
+ if (lane == 0) s.flags |= (skip ? (int)ADJ_ROWS_SKIPPED : 0) | (mis ? (int)ADJ_REPLAY_MISMATCH : 0);
1043
+ __syncwarp();
1044
+ APROF_COUNT(APROF_COUNT_CONTACTS_ACTIVE, __popc(__ballot_sync(0xffffffffu, cb >= 0)));
1045
+ APROF(APROF_CONTACT_ROWS);
1046
+ float f[3] = {0.f, 0.f, 0.f}, t[3] = {0.f, 0.f, 0.f}, pt[3] = {0.f, 0.f, 0.f}, pv = 0.f;
1047
+ #pragma unroll 1
1048
+ for (int j = 0; j < nb; j++) { // the batch in contact order
1049
+ const int cj = __shfl_sync(0xffffffffu, cb, j);
1050
+ if (UNIFORM(cj < 0)) continue;
1051
+ const int c1 = cj & 255, c2 = cj >> 8;
1052
+ float w[CS_N];
1053
+ #pragma unroll
1054
+ for (int k = 0; k < 12; k++) w[k] = __shfl_sync(0xffffffffu, cw[k], j);
1055
+ const unsigned i2 = (c_ancmask[c2] >> rb) & 1u, i1 = (c_ancmask[c1] >> rb) & 1u;
1056
+ if ((body || rot) && i1 != i2) { // this lane's dof in the support (contact_dof_vjp)
1057
+ const float sg = i2 ? 1.f : -1.f, vi = sg * s.v[di], ai = sg * s.a[di], li = sg * s.lam[di];
1058
+ const float* z = rb >= 2 ? s.z[rb] : s.zr[rk];
1059
+ float G[3], r[3], wv[3], col[3], u[3], x[3], y[3];
1060
+ for (int k = 0; k < 3; k++) {
1061
+ wv[k] = w[k];
1062
+ G[k] = vi * wv[k] + ai * w[3 + k] + li * w[6 + k];
1063
+ r[k] = w[9 + k] - s.X[rb][k];
1064
+ }
1065
+ cross(z, r, col);
1066
+ pv += sg * dot3(col, wv);
1067
+ cross(z, G, u);
1068
+ cross(r, G, x);
1069
+ cross(z, x, y);
1070
+ for (int k = 0; k < 3; k++) { f[k] += u[k]; t[k] += y[k]; }
1071
+ if (lane == 1)
1072
+ for (int k = 0; k < 3; k++) pt[k] += sg * wv[k]; // the root translations: columns e_k, no pose term
1073
+ }
1074
+ if (UNIFORM(c1 != 0)) { // the floor, body 0, takes no pose cotangent
1075
+ #pragma unroll
1076
+ for (int k = 12; k < 18; k++) w[k] = __shfl_sync(0xffffffffu, cw[k], j);
1077
+ if (body && rb == c1)
1078
+ for (int k = 0; k < 3; k++) { f[k] += w[12 + k]; t[k] += w[15 + k]; }
1079
+ }
1080
+ #pragma unroll
1081
+ for (int k = 18; k < 24; k++) w[k] = __shfl_sync(0xffffffffu, cw[k], j);
1082
+ if (body && rb == c2)
1083
+ for (int k = 0; k < 3; k++) { f[k] += w[18 + k]; t[k] += w[21 + k]; }
1084
+ }
1085
+ float o[7] = {f[0], f[1], f[2], t[0], t[1], t[2], pv}, o0[7], o31[7]; // root rotations 4, 5: to lane 1
1086
+ for (int k = 0; k < 7; k++) { o0[k] = __shfl_sync(0xffffffffu, o[k], 0); o31[k] = __shfl_sync(0xffffffffu, o[k], 31); }
1087
+ if (body) {
1088
+ if (lane == 1) {
1089
+ for (int k = 0; k < 3; k++) {
1090
+ f[k] += o0[k] + o31[k]; t[k] += o0[3 + k] + o31[3 + k]; s.Pv[k] += pt[k];
1091
+ }
1092
+ s.Pv[4] += o0[6];
1093
+ s.Pv[5] += o31[6];
1094
+ }
1095
+ for (int k = 0; k < 3; k++) { s.fb[rb][k] += f[k]; s.tb[rb][k] += t[k]; }
1096
+ s.Pv[di] += pv;
1097
+ }
1098
+ __syncwarp();
1099
+ APROF(APROF_CONTACT_REDUCE);
1100
+ }
1101
+ }
1102
+ #endif
1103
+
1104
+ #ifdef DK_ADJ_DEBUG
1105
+ __device__ void dbg_put(float* dst, const float* src, int n, float sg, int lane) {
1106
+ for (int i = lane; i < n; i += 32) dst[i] = sg * src[i];
1107
+ }
1108
+ // dst = sg dof_to_qpos(P; xi) (NQ words)
1109
+ __device__ void dbg_qpos(float* dst, const float* P, const float* q, float sg, int lane) {
1110
+ for (int i = lane; i < NV; i += 32) {
1111
+ if (i < 3) dst[i] = sg * P[i];
1112
+ else if (i >= 6) dst[i + 1] = sg * P[i];
1113
+ }
1114
+ if (lane == 0) {
1115
+ float g[4] = {0.f, P[3], P[4], P[5]}, t[4];
1116
+ qmul(q + 3, g, t);
1117
+ for (int k = 0; k < 4; k++) dst[3 + k] = sg * 2.f * t[k];
1118
+ }
1119
+ }
1120
+ // the built-in check of the solves: r(a*) = ID(q, v, a*) + arm a* - tau - J'f from the bodies' channel-1 forces right
1121
+ // after A4 (bVl = F1, bWl = N1), summed over the subtrees as the forward does; tau from ctrl, J'f = s.jtf (adj_jtf, the
1122
+ // replayed rows' forces; 0 with DK_ADJ_STAGE 1)
1123
+ __device__ void adj_residual(Adj& s, const float* ctrl, float* dbg, int lane) {
1124
+ const int b = lane, d = b < NB ? c_depth[b] : -1;
1125
+ if (b >= 1 && b < NB)
1126
+ for (int k = 0; k < 3; k++) { s.dF[b][k] = s.bVl[b][k]; s.dN[b][k] = s.bWl[b][k]; }
1127
+ __syncwarp();
1128
+ for (int L = MAXD - 1; L >= 1; L--) {
1129
+ if (d == L)
1130
+ for (int i = 0; i < c_nchild[b]; i++) {
1131
+ int c = c_child[3 * b + i];
1132
+ accumulate(s.X[b], s.X[c], s.dF[c], s.dN[c], s.dF[b], s.dN[b]);
1133
+ }
1134
+ __syncwarp();
1135
+ }
1136
+ if (b >= 1 && b < NB) torques(b, s.Q[b], s.dF[b], s.dN[b], s.did);
1137
+ __syncwarp();
1138
+ float rr = 0.f, tt = 0.f, ii = 0.f, ff = 0.f;
1139
+ for (int i = lane; i < NV; i += 32) {
1140
+ float tau = 0.f;
1141
+ if (i >= 6 && ctrl) {
1142
+ tau = c_kp[i] * (ctrl[i - 6] - s.q[i + 1]) - c_kv[i] * s.v[i];
1143
+ tau = fminf(fmaxf(tau, -c_frclim[i]), c_frclim[i]);
1144
+ }
1145
+ float r = s.did[i] + c_armature[i] * s.a[i] - tau - s.jtf[i];
1146
+ dbg[DBG_RESID + i] = r;
1147
+ rr += r * r; tt += tau * tau; ii += s.did[i] * s.did[i]; ff += s.jtf[i] * s.jtf[i];
1148
+ }
1149
+ rr = warp_sum(rr); tt = warp_sum(tt); ii = warp_sum(ii); ff = warp_sum(ff);
1150
+ if (lane == 0) {
1151
+ dbg[DBG_RESID_NORM] = sqrtf(rr); dbg[DBG_TAU_NORM] = sqrtf(tt); dbg[DBG_ID_NORM] = sqrtf(ii);
1152
+ dbg[DBG_MA_NORM] = s.ma_norm; dbg[DBG_JTF_NORM] = sqrtf(ff);
1153
+ }
1154
+ __syncwarp();
1155
+ }
1156
+ #if DK_ADJ_STAGE >= 2
1157
+ // J'f of the replayed rows for the residual check, one lane per dof, from the debug entries of adj_limits and
1158
+ // adj_contacts (written by other lanes before the caller's __syncwarp): the limit row's sigma f, and s_i col_i . F_c
1159
+ // of every contact c whose support holds the dof (F_c: its force sum_e -D x_e u_e at its point)
1160
+ __device__ void adj_jtf(Adj& s, const float* dbg, int lane) {
1161
+ const int ncon = s.hdr & 255;
1162
+ for (int i = lane; i < NV; i += 32) {
1163
+ const int bi = c_dofbody[i];
1164
+ float acc = 0.f;
1165
+ if (i >= 6) {
1166
+ const float q = s.q[i + 1];
1167
+ acc = (q - c_jrange[2 * i] < c_jrange[2 * i + 1] - q ? 1.f : -1.f) * dbg[DBG_LIM_FORCE + i];
1168
+ }
1169
+ for (int c = 0; c < ncon; c++) {
1170
+ const int pair = (s.con[c >> 1] >> (16 * (c & 1))) & 511u;
1171
+ const unsigned m1 = c_ancmask[c_gbody[PG1(pair)]], m2 = c_ancmask[c_gbody[PG2(pair)]];
1172
+ if (!(((m1 ^ m2) >> bi) & 1u)) continue;
1173
+ const float sg = (m2 >> bi) & 1u ? 1.f : -1.f, *F = dbg + DBG_CON_FORCE + 3 * c, *p = dbg + DBG_CON_POS + 3 * c;
1174
+ if (i < 3) { acc += sg * F[i]; continue; }
1175
+ const float* z = i < 6 ? s.zr[i - 3] : s.z[bi];
1176
+ float r[3], col[3];
1177
+ for (int t = 0; t < 3; t++) r[t] = p[t] - s.X[bi][t];
1178
+ cross(z, r, col);
1179
+ acc += sg * dot3(col, F);
1180
+ }
1181
+ s.jtf[i] = acc;
1182
+ }
1183
+ __syncwarp();
1184
+ }
1185
+ #endif
1186
+ #endif
1187
+
1188
+ // the world body (at rest), and the debug build's zero vector; the caller syncs
1189
+ __device__ void adj_init(Adj& s, int lane) {
1190
+ #ifdef DK_ADJ_DEBUG
1191
+ for (int i = lane; i < NV; i += 32) { s.zero[i] = 0.f; s.jtf[i] = 0.f; } // DK_ADJ_STAGE 1 has no rows
1192
+ #endif
1193
+ if (lane == 0) { s.Q[0][0] = 1.f; s.Q[0][1] = s.Q[0][2] = s.Q[0][3] = 0.f; s.flags = 0; }
1194
+ if (lane < 3) {
1195
+ s.X[0][lane] = s.z[0][lane] = s.W[0][lane] = s.V[0][lane] = s.AL[0][lane] = s.A[0][lane] = 0.f;
1196
+ s.AL2[0][lane] = s.A2[0][lane] = s.Wl[0][lane] = s.Vl[0][lane] = s.Wy[0][lane] = s.Vy[0][lane] = 0.f;
1197
+ }
1198
+ }
1199
+
1200
+ // one substep's VJP (A0-A8): s.qbar, s.vbar hold the cotangents of its output state and become those of its input;
1201
+ // s.ubar accumulates. rec: its tape record. dbg, ctrl: -DDK_ADJ_DEBUG (this world's debug record of the substep, the
1202
+ // world's ctrl); null otherwise
1203
+ __device__ void adj_substep(Adj& s, const float* rec, int lane, float* dbg, const float* ctrl) {
1204
+ // A0
1205
+ for (int i = lane; i < NQ; i += 32) s.q[i] = __ldcs(rec + OFF_QPOS + i);
1206
+ for (int i = lane; i < NV; i += 32) {
1207
+ float a = __ldcs(rec + OFF_QACC + i), aadv = __ldcs(rec + OFF_QADV + i);
1208
+ s.v[i] = __ldcs(rec + OFF_QVEL + i); s.a[i] = a; s.aadv[i] = aadv; s.at[i] = a - aadv;
1209
+ }
1210
+ if (lane < (NV + 31) / 32) s.clamp[lane] = __float_as_uint(__ldcs(rec + OFF_CLAMP + lane));
1211
+ if (lane < (NEFC + 31) / 32) s.zone[lane] = __float_as_uint(__ldcs(rec + OFF_ZONE + lane));
1212
+ for (int i = lane; i < (MAXCON + 1) / 2; i += 32) s.con[i] = __float_as_uint(__ldcs(rec + OFF_CON + i));
1213
+ if (lane == 0) {
1214
+ unsigned hd = __float_as_uint(__ldcs(rec + OFF_HDR));
1215
+ s.hdr = (int)hd;
1216
+ s.flags |= (int)__float_as_uint(__ldcs(rec + OFF_FLAGS));
1217
+ if (DK_ADJ_STAGE < 2 && (hd & 0xFFFFu)) s.flags |= ADJ_ROWS_SKIPPED; // contacts (ncon) or rows (nefc)
1218
+ }
1219
+ __syncwarp();
1220
+ APROF(APROF_RECORD);
1221
+ adj_poses(s, lane); // A3: poses and channel 1
1222
+ APROF(APROF_POSES);
1223
+ #ifdef DK_ADJ_DEBUG
1224
+ if (dbg) { dbg_put(dbg + DBG_G_QPOS_OUT, s.qbar, NQ, 1.f, lane); dbg_put(dbg + DBG_G_QVEL_OUT, s.vbar, NV, 1.f, lane); }
1225
+ __syncwarp(); // lane 0 of adj_integrator overwrites qbar[3..6], vbar[3..5] that other lanes just read
1226
+ #endif
1227
+ adj_integrator(s, lane); // A1
1228
+ APROF(APROF_INTEGRATOR);
1229
+ #ifdef DK_ADJ_DEBUG
1230
+ if (dbg) {
1231
+ dbg_put(dbg + DBG_ADJ_QPOS_INT, s.qbar, NQ, 1.f, lane); dbg_put(dbg + DBG_ADJ_QVEL_INT, s.vbar, NV, 1.f, lane);
1232
+ dbg_put(dbg + DBG_ADJ_QACC_ADV, s.abar, NV, 1.f, lane);
1233
+ }
1234
+ #endif
1235
+ adj_solves(s, rec, lane); // A1, A2 (marks solve_Q inside)
1236
+ APROF(APROF_SOLVE_H);
1237
+ #ifdef DK_ADJ_DEBUG
1238
+ if (dbg) { // the split of P by source: the RNE's channel 1 (lambda) and 2 (-y) alone, then the actuator
1239
+ dbg_put(dbg + DBG_Y, s.y, NV, 1.f, lane); dbg_put(dbg + DBG_ADJ_QACC, s.abar, NV, 1.f, lane);
1240
+ dbg_put(dbg + DBG_LAM, s.lam, NV, 1.f, lane); dbg_put(dbg + DBG_W_DIR, s.at, NV, 1.f, lane);
1241
+ #if DK_ADJ_STAGE >= 2
1242
+ // the constraint rows alone: the limit rows (direct P terms), then the contacts (their pose cotangents through the
1243
+ // pose sweep, with zero RNE seeds: adj_tree_down then leaves f bar = tau bar = 0), and their forces J'f
1244
+ adj_tree_down(s, s.zero, s.zero, lane);
1245
+ for (int i = lane; i < NV; i += 32) { s.Pq[i] = 0.f; s.Pv[i] = 0.f; }
1246
+ __syncwarp();
1247
+ adj_limits<true>(s, lane, dbg);
1248
+ dbg_qpos(dbg + DBG_RES_QPOS_LIMIT, s.Pq, s.q, 1.f, lane); dbg_put(dbg + DBG_RES_QVEL_LIMIT, s.Pv, NV, 1.f, lane);
1249
+ __syncwarp();
1250
+ for (int i = lane; i < NV; i += 32) { s.Pq[i] = 0.f; s.Pv[i] = 0.f; }
1251
+ __syncwarp();
1252
+ adj_contacts<true>(s, lane, dbg);
1253
+ adj_tree_up(s, s.zero, s.zero, lane);
1254
+ dbg_qpos(dbg + DBG_RES_QPOS_CONTACT, s.Pq, s.q, 1.f, lane);
1255
+ dbg_put(dbg + DBG_RES_QVEL_CONTACT, s.Pv, NV, 1.f, lane);
1256
+ __syncwarp();
1257
+ adj_jtf(s, dbg, lane);
1258
+ for (int i = lane; i < NV; i += 32) { s.Pq[i] = 0.f; s.Pv[i] = 0.f; }
1259
+ __syncwarp();
1260
+ #endif
1261
+ adj_tree_down(s, s.lam, s.zero, lane);
1262
+ adj_residual(s, ctrl, dbg, lane);
1263
+ adj_tree_up(s, s.lam, s.zero, lane);
1264
+ dbg_qpos(dbg + DBG_RES_QPOS_RNE, s.Pq, s.q, 1.f, lane); dbg_put(dbg + DBG_RES_QVEL_RNE, s.Pv, NV, 1.f, lane);
1265
+ __syncwarp();
1266
+ for (int i = lane; i < NV; i += 32) { s.Pq[i] = 0.f; s.Pv[i] = 0.f; }
1267
+ adj_tree_down(s, s.zero, s.ny, lane);
1268
+ adj_tree_up(s, s.zero, s.ny, lane);
1269
+ dbg_qpos(dbg + DBG_ADJ_QPOS_M, s.Pq, s.q, -1.f, lane); // P of the seed -y is -grad_q[y' M a~]
1270
+ __syncwarp();
1271
+ for (int i = lane; i < NV; i += 32) {
1272
+ float lt = LAM_ACT(s, i);
1273
+ s.tmp[i] = c_kp[i] * lt;
1274
+ dbg[DBG_RES_QVEL_ACT + i] = i >= 6 ? c_kv[i] * (DK_ADJ_CLAMP_KV ? lt : s.lam[i]) : 0.f;
1275
+ if (i >= 6) dbg[DBG_GRAD_CTRL_K + i - 6] = c_kp[i] * lt;
1276
+ s.Pq[i] = 0.f; s.Pv[i] = 0.f;
1277
+ }
1278
+ __syncwarp();
1279
+ dbg_qpos(dbg + DBG_RES_QPOS_ACT, s.tmp, s.q, 1.f, lane);
1280
+ __syncwarp();
1281
+ }
1282
+ #endif
1283
+ adj_tree_down(s, s.lam, s.ny, lane); // A3 (channel 2, twists), A4
1284
+ APROF(APROF_TREE_DOWN);
1285
+ #if DK_ADJ_STAGE >= 2
1286
+ adj_limits<false>(s, lane, nullptr); // A5, A6: P_q, P_v of the limit rows' dofs (marks limits)
1287
+ adj_contacts<false>(s, lane, nullptr); // A5, A6: the contacts' pose cotangents s.fb / s.tb, P_v of the support dofs
1288
+ // (marks contact_setup, then contact_rows and contact_reduce per batch)
1289
+ #endif
1290
+ adj_tree_up(s, s.lam, s.ny, lane); // A7
1291
+ APROF(APROF_TREE_UP);
1292
+ adj_compose(s, lane); // A8
1293
+ APROF(APROF_COMPOSE);
1294
+ #ifdef DK_ADJ_DEBUG
1295
+ if (dbg) { dbg_put(dbg + DBG_GRAD_QPOS_IN, s.qbar, NQ, 1.f, lane); dbg_put(dbg + DBG_GRAD_QVEL_IN, s.vbar, NV, 1.f, lane); }
1296
+ __syncwarp();
1297
+ #endif
1298
+ }
1299
+ """
1300
+
1301
+ ADJ_KERNEL = r"""
1302
+ #ifdef DK_PROFILE
1303
+ // PROF_PHASES summed over the worlds of every launch since it was last zeroed (zero at load): the host zeroes it
1304
+ // (cudaMemcpyToSymbol) before the launch it profiles and reads it right after (the adjoint check binary, which also
1305
+ // prints the launches since the zero; nablaengine.checks.run rejects a reading that is not of one launch)
1306
+ __device__ unsigned long long g_aprof[NAPROF];
1307
+ #endif
1308
+ // the adjoint of one control step (nsub substeps) per world: tape = nw * nsub records (record w * nsub + k), gq_out /
1309
+ // gv_out the cotangents of the step's output qpos / qvel, gq_in / gv_in / gctrl the gradients of its input qpos, qvel
1310
+ // and ctrl (summed over the substeps), info the union of the records' flags, ADJ_ROWS_SKIPPED and ADJ_REPLAY_MISMATCH.
1311
+ // fric: the worlds' foot friction (the foot pairs' mu, as the forward). dbg, ctrl: -DDK_ADJ_DEBUG (nw * nsub records of
1312
+ // DBG_WORDS, ctrl for the residual check), may be null. DK_ADJ_CLAMP_KV=2: ctrl (nw * nu, the control step's) is
1313
+ // required, and clamp_soft (ADJ_SOFT_PARAM) is the soft clamp's delta
1314
+ __global__ void k_adjoint(int nw, int nsub, const float* tape, const float* fric, const float* com, const float* gq_out,
1315
+ const float* gv_out, float* gq_in, float* gv_in, float* gctrl, int* info, float* dbg,
1316
+ const float* ctrl ADJ_SOFT_PARAM) {
1317
+ extern __shared__ __align__(16) unsigned char dk_smem[]; // dynamic, as the forward
1318
+ Adj& s = *reinterpret_cast<Adj*>(dk_smem);
1319
+ const int lane = threadIdx.x & 31, w = blockIdx.x; // (& 31: see host.py k_substep)
1320
+ if (w >= nw) return;
1321
+ #ifdef DK_PROFILE
1322
+ if (lane < NAPROF) s.aprof[lane] = 0;
1323
+ #endif
1324
+ APROF_START();
1325
+ adj_init(s, lane);
1326
+ for (int i = lane; i < NQ; i += 32) s.qbar[i] = gq_out[(size_t)w * NQ + i];
1327
+ for (int i = lane; i < NV; i += 32) s.vbar[i] = gv_out[(size_t)w * NV + i];
1328
+ for (int i = lane; i < NV - 6; i += 32) s.ubar[i] = 0.f;
1329
+ if (lane < 3) s.com[lane] = com[w * 3 + lane];
1330
+ if (lane == 0) s.fric = fric ? fric[w] : 0.f;
1331
+ #if DK_ADJ_CLAMP_KV == 2
1332
+ for (int i = lane; i < NV - 6; i += 32) s.u[i] = ctrl[(size_t)w * (NV - 6) + i];
1333
+ if (lane == 0) s.soft = clamp_soft;
1334
+ #endif
1335
+ __syncwarp();
1336
+ APROF(APROF_IO);
1337
+ for (int k = nsub - 1; k >= 0; k--) {
1338
+ const size_t r = (size_t)w * nsub + k;
1339
+ adj_substep(s, tape + r * REC_WORDS, lane, dbg ? dbg + r * DBG_WORDS : nullptr,
1340
+ ctrl ? ctrl + (size_t)w * (NV - 6) : nullptr);
1341
+ }
1342
+ for (int i = lane; i < NQ; i += 32) gq_in[(size_t)w * NQ + i] = s.qbar[i];
1343
+ for (int i = lane; i < NV; i += 32) gv_in[(size_t)w * NV + i] = s.vbar[i];
1344
+ for (int i = lane; i < NV - 6; i += 32) gctrl[(size_t)w * (NV - 6) + i] = s.ubar[i];
1345
+ if (lane == 0) info[w] = s.flags;
1346
+ #ifdef DK_PROFILE
1347
+ APROF(APROF_IO);
1348
+ if (lane < NAPROF) atomicAdd(&g_aprof[lane], (unsigned long long)s.aprof[lane]);
1349
+ #endif
1350
+ }
1351
+
1352
+ #ifndef DK_ADJ_WORLDS_PER_SM
1353
+ #define DK_ADJ_WORLDS_PER_SM -1 // -1: adj_worlds_per_sm()'s choice for the GPU; 0: as many as fit; N > 0: at most N
1354
+ #endif
1355
+ // host: the worlds-per-SM cap of a k_adjoint launch on the current device: DK_ADJ_WORLDS_PER_SM if >= 0, else the
1356
+ // choice for the GPU. V100 (sm_70): 4 (at 15740 B per world, when 6 fitted: 6 -> 4 gave 5.1 -> 4.5 ms per control
1357
+ // step; with 5 or 6 worlds some warps share a scheduler and slow down; at 10108 B 9 fit and 8 / 9 run 6-11% faster
1358
+ // than 4, not adopted: V100 is not a target GPU); the RTX 3090 (sm_86) gains up to
1359
+ // the 9 that fit, so no cap elsewhere (0). -1 if the device cannot be queried, with the CUDA error in *err
1360
+ // (cudaSuccess otherwise; err may be null)
1361
+ static inline int adj_worlds_per_sm(cudaError_t* err = nullptr) {
1362
+ cudaError_t e = cudaSuccess;
1363
+ int dev = 0, major = 0, minor = 0;
1364
+ if (DK_ADJ_WORLDS_PER_SM < 0) {
1365
+ e = cudaGetDevice(&dev);
1366
+ if (e == cudaSuccess) e = cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
1367
+ if (e == cudaSuccess) e = cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
1368
+ }
1369
+ if (err) *err = e;
1370
+ if (e != cudaSuccess) return -1;
1371
+ if (DK_ADJ_WORLDS_PER_SM >= 0) return DK_ADJ_WORLDS_PER_SM;
1372
+ return major == 7 && minor == 0 ? 4 : 0;
1373
+ }
1374
+ // host: the dynamic shared memory of a k_adjoint launch on the current device; also sets k_adjoint's opt-in to it on
1375
+ // that device (cudaFuncSetAttribute: once per device is enough, e.g. with the constant upload, and not per launch).
1376
+ // worlds_per_sm: -1 (default) adj_worlds_per_sm()'s choice, 0 no cap (sizeof(Adj)), N > 0 at most N worlds per SM:
1377
+ // (shared memory per SM / N - 1 KB) rounded down to 256 B (1 KB: the per-block reservation of sm_80 and later; 256 B:
1378
+ // the allocation granularity, 128 B on sm_86), more than the kernel needs (the rest of the SM's shared memory is left
1379
+ // unused: limiting the occupancy by the carveout instead, with a larger L1, measured slower on V100), in signed
1380
+ // arithmetic and never below sizeof(Adj) (a cap above what fits is no cap) nor above the device's per-block opt-in
1381
+ // limit. Returns 0 on failure, with the CUDA error in *err (cudaSuccess otherwise; err may be null): no current device,
1382
+ // a refused attribute query or opt-in (e.g. sizeof(Adj) above the opt-in limit), or worlds_per_sm < -1
1383
+ // (cudaErrorInvalidValue). Callers must check for 0: a launch with 0 bytes is not rejected, the kernel would use shared
1384
+ // memory it was not given. Launch: k_adjoint<<<nw, 32, smem, stream>>>(...)
1385
+ static inline size_t adj_launch_smem(int worlds_per_sm = -1, cudaError_t* err = nullptr) {
1386
+ cudaError_t e = cudaSuccess;
1387
+ if (worlds_per_sm == -1) worlds_per_sm = adj_worlds_per_sm(&e);
1388
+ else if (worlds_per_sm < -1) e = cudaErrorInvalidValue;
1389
+ long long smem = (long long)sizeof(Adj);
1390
+ int dev = 0, optin = 0, per_sm = 0;
1391
+ if (e == cudaSuccess) e = cudaGetDevice(&dev);
1392
+ if (e == cudaSuccess) e = cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev);
1393
+ if (e == cudaSuccess && worlds_per_sm > 0) {
1394
+ e = cudaDeviceGetAttribute(&per_sm, cudaDevAttrMaxSharedMemoryPerMultiprocessor, dev);
1395
+ long long want = ((long long)per_sm / worlds_per_sm - 1024) / 256 * 256; // < 0 for large worlds_per_sm
1396
+ if (want > optin) want = optin;
1397
+ if (e == cudaSuccess && want > smem) smem = want;
1398
+ }
1399
+ if (e == cudaSuccess) e = cudaFuncSetAttribute(k_adjoint, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem);
1400
+ if (err) *err = e;
1401
+ return e == cudaSuccess ? (size_t)smem : 0;
1402
+ }
1403
+ """
1404
+
1405
+
1406
+
1407
+ def capbox_dual_source():
1408
+ """step.py's capsule-box terrain geometry (terrain_capbox_segs with capbox_segs, capbox_point, terrain_sphere_box
1409
+ with sphere_box) as templates over the scalar type (name_t), generated from their text: with T = D1
1410
+ (nablaengine.dual) the contact adjoint replays a capsule-box terrain contact once per pose direction of the capsule
1411
+ (ADJ_CAPBOX_DUAL), the candidate parameter's slide included."""
1412
+ import re
1413
+ names = ("sphere_box", "capbox_segs", "capbox_point", "terrain_sphere_box", "terrain_capbox_segs")
1414
+ texts = []
1415
+ src = step.STEP_DEVICE + step.TERRAIN_DEVICE + step.capbox_segs_source()
1416
+ for nm in names:
1417
+ m = re.search(r"__device__ (?:__noinline__ )?(?:void|int) " + nm + r"\(", src)
1418
+ if m is None:
1419
+ raise RuntimeError(f"capbox_dual_source: no {nm}")
1420
+ a = m.start()
1421
+ b = src.index("\n}\n", a) + 3
1422
+ texts.append(src[a:b])
1423
+ body = "\n".join(texts)
1424
+ body = re.sub(r"\bfloat\b", "T", body)
1425
+ body = re.sub(r"\b(fabs|sqrt|fmin|fmax)f\(", r"t_\1(", body)
1426
+ body = re.sub(r"\b(mv3|mtv3|mm3|mmt3|dot3|safe_div)\(", r"t_\1(", body)
1427
+ for nm in names:
1428
+ body = re.sub(r"\b" + nm + r"\(", nm + "_t(", body)
1429
+ body = re.sub(r"__device__ (__noinline__ )?(void|int) ", r"template <class T>\n__device__ \1\2 ", body)
1430
+ return "// step.py's capsule-box terrain geometry over a scalar type (adjoint.capbox_dual_source)\n" + body + "\n"
1431
+
1432
+
1433
+ ADJ_CAPBOX_DUAL = """ if (box && gt == 2 && cot) { // capsule-box (adjoint.ADJ_CAPBOX_DUAL): the contact replayed over duals (D1) once per
1434
+ // pose direction of the capsule (cbter_dir_vjp; DK_CAPBOX_COOP: in adj_contacts' cooperative pass instead)
1435
+ #if !CB_COOP_ON
1436
+ const float* b = ter_box(e);
1437
+ float nbar[3];
1438
+ make_frame_vjp(fr, cot + 4, nbar);
1439
+ for (int j = 0; j < 6; j++) gb[6 + j] = cbter_dir_vjp(j, k, b, p2, axis, sz, cot, nbar);
1440
+ #endif
1441
+ return br;
1442
+ }
1443
+ """
1444
+
1445
+ ADJ_CAPBOX_DUAL_LOOP = (""" for (int j = 0; j < 6; j++) gb[6 + j] = cbter_dir_vjp(j, k, b, p2, axis, sz, cot, nbar);
1446
+ """, """ D1 B[15]; // (adjoint.ADJ_CAPBOX_DUAL_LOOP: cbter_dir_vjp's body, the duals of the box once)
1447
+ for (int t = 0; t < 15; t++) B[t] = D1(b[t]);
1448
+ for (int j = 0; j < 6; j++) {
1449
+ D1 P[3], A[3], segs[2], C[3], dd, pp[3], nn[3];
1450
+ float ea[3] = {0.f, 0.f, 0.f}, ta[3];
1451
+ ea[j % 3] = 1.f;
1452
+ cross(ea, axis, ta);
1453
+ for (int t = 0; t < 3; t++) {
1454
+ P[t] = D1(p2[t], j < 3 && t == j ? 1.f : 0.f);
1455
+ A[t] = D1(axis[t], j >= 3 ? ta[t] : 0.f);
1456
+ }
1457
+ terrain_capbox_segs_t<D1>(P, A, D1(sz[1]), B, segs);
1458
+ capbox_point_t<D1>(P, A, D1(sz[1]), B, segs[k], C);
1459
+ terrain_sphere_box_t<D1>(C, D1(sz[0]), B, &dd, pp, nn);
1460
+ float g = cot[0] * dd.d;
1461
+ for (int t = 0; t < 3; t++) g += cot[1 + t] * pp[t].d + nbar[t] * nn[t].d;
1462
+ gb[6 + j] = g;
1463
+ }
1464
+ """)
1465
+ ADJ_CAPBOX_DUAL_TREE = ADJ_CAPBOX_DUAL.replace(*ADJ_CAPBOX_DUAL_LOOP)
1466
+ assert ADJ_CAPBOX_DUAL_TREE != ADJ_CAPBOX_DUAL
1467
+
1468
+ CBTER_DIR_VJP = """// (adjoint.CBTER_DIR_VJP) pose direction j of the capsule in a terrain capsule-box contact, gb[6 + j]
1469
+ __device__ __noinline__ float cbter_dir_vjp(int j, int k, const float* b, const float* p2, const float* axis,
1470
+ const float* sz, const float* cot, const float* nbar) {
1471
+ D1 B[15];
1472
+ for (int t = 0; t < 15; t++) B[t] = D1(b[t]);
1473
+ D1 P[3], A[3], segs[2], C[3], dd, pp[3], nn[3];
1474
+ float ea[3] = {0.f, 0.f, 0.f}, ta[3];
1475
+ ea[j % 3] = 1.f;
1476
+ cross(ea, axis, ta);
1477
+ for (int t = 0; t < 3; t++) {
1478
+ P[t] = D1(p2[t], j < 3 && t == j ? 1.f : 0.f);
1479
+ A[t] = D1(axis[t], j >= 3 ? ta[t] : 0.f);
1480
+ }
1481
+ terrain_capbox_segs_t<D1>(P, A, D1(sz[1]), B, segs);
1482
+ capbox_point_t<D1>(P, A, D1(sz[1]), B, segs[k], C);
1483
+ terrain_sphere_box_t<D1>(C, D1(sz[0]), B, &dd, pp, nn);
1484
+ float g = cot[0] * dd.d;
1485
+ for (int t = 0; t < 3; t++) g += cot[1 + t] * pp[t].d + nbar[t] * nn[t].d;
1486
+ return g;
1487
+ }
1488
+
1489
+ """
1490
+
1491
+ CBTER_DIR_VJP_TREE = CBTER_DIR_VJP.replace("__device__ __noinline__ float cbter_dir_vjp(",
1492
+ "__device__ __forceinline__ float cbter_dir_vjp(")
1493
+ assert CBTER_DIR_VJP_TREE != CBTER_DIR_VJP
1494
+
1495
+ ADJ_TERRAIN_HOOKS = (
1496
+ ("""// adj_contact_geom for contact (pair, slot) of the engine's pair table""",
1497
+ adjoint_contact.TERRAIN_DEVICE.lstrip("\n") + """
1498
+ // adj_contact_geom for contact (pair, slot) of the engine's pair table"""),
1499
+ (""" int g1 = PG1(pair), g2 = PG2(pair);
1500
+ return adj_contact_geom(""",
1501
+ """ if (pair >= NPAIR)
1502
+ return adj_terrain_geom(slot, 0u, c_gtype[PG2(pair)], c_gsize + 3 * PG2(pair), gx[PG2(pair)], gq[PG2(pair)], dist,
1503
+ pos, fr, nu, cot, gb);
1504
+ int g1 = PG1(pair), g2 = PG2(pair);
1505
+ return adj_contact_geom("""),
1506
+ (""" unsigned con[(MAXCON + 1) / 2]; // the record's contact table: pair | slot << 9 per 16 bits
1507
+ """,
1508
+ """ unsigned con[(MAXCON + 1) / 2]; // the record's contact table: pair | slot << 10 per 16 bits (terrain build)
1509
+ unsigned telem[(MAXCON + 1) / 2]; // the contacts' terrain elements, 16 bits each
1510
+ """),
1511
+ (""" for (int i = lane; i < (MAXCON + 1) / 2; i += 32) s.con[i] = __float_as_uint(__ldcs(rec + OFF_CON + i));
1512
+ """,
1513
+ """ for (int i = lane; i < (MAXCON + 1) / 2; i += 32) s.con[i] = __float_as_uint(__ldcs(rec + OFF_CON + i));
1514
+ for (int i = lane; i < (MAXCON + 1) / 2; i += 32) s.telem[i] = __float_as_uint(__ldcs(rec + OFF_TELEM + i));
1515
+ """),
1516
+ (""" const int pair = e & 511u, slot = e >> 9, dim = on ? PDIM(pair) : 0;""",
1517
+ """ const unsigned x = on ? (s.telem[c >> 1] >> (16 * (c & 1))) & 0xFFFFu : 0u;
1518
+ const int pair = e & 1023u, slot = (int)(e >> 10 | x << 8), dim = on ? PDIM(pair) : 0;"""),
1519
+ (""" const int pair = (s.con[c >> 1] >> (16 * (c & 1))) & 511u;""",
1520
+ """ const int pair = (s.con[c >> 1] >> (16 * (c & 1))) & 1023u;"""),
1521
+ )
1522
+
1523
+
1524
+ ADJ_NATIVE_HOOKS = (
1525
+ (""" unsigned telem[(MAXCON + 1) / 2]; // the contacts' terrain elements, 16 bits each
1526
+ """,
1527
+ """ unsigned telem[(MAXCON + 1) / 2]; // the contacts' terrain elements, 16 bits each
1528
+ unsigned taux[MAXCON]; // native heightfield contacts: the candidate ids
1529
+ """),
1530
+ (""" for (int i = lane; i < (MAXCON + 1) / 2; i += 32) s.telem[i] = __float_as_uint(__ldcs(rec + OFF_TELEM + i));
1531
+ """,
1532
+ """ for (int i = lane; i < (MAXCON + 1) / 2; i += 32) s.telem[i] = __float_as_uint(__ldcs(rec + OFF_TELEM + i));
1533
+ for (int i = lane; i < MAXCON; i += 32) s.taux[i] = __float_as_uint(__ldcs(rec + OFF_TAUX + i));
1534
+ """),
1535
+ ("""// a geom's pose cotangent (xbar, tbar = gb + 6 j of adj_contact_geom) onto its body's:""",
1536
+ """// adj_pair_geom with a terrain contact's candidate id
1537
+ __device__ __forceinline__ int adj_pair_geom_aux(int pair, int slot, unsigned aux, const float (*gx)[3],
1538
+ const float (*gq)[4], float* dist, float* pos, float* fr, float* nu,
1539
+ const float* cot, float* gb) {
1540
+ if (pair >= NPAIR)
1541
+ return adj_terrain_geom(slot, aux, c_gtype[PG2(pair)], c_gsize + 3 * PG2(pair), gx[PG2(pair)], gq[PG2(pair)], dist,
1542
+ pos, fr, nu, cot, gb);
1543
+ return adj_pair_geom(pair, slot, gx, gq, dist, pos, fr, nu, cot, gb);
1544
+ }
1545
+
1546
+ // a geom's pose cotangent (xbar, tbar = gb + 6 j of adj_contact_geom) onto its body's:"""),
1547
+ ("""adj_pair_geom(pair, slot, s.gx, s.gq, &d, p, fr, &nu, nullptr, nullptr)""",
1548
+ """adj_pair_geom_aux(pair, slot, s.taux[c], s.gx, s.gq, &d, p, fr, &nu, nullptr, nullptr)"""),
1549
+ ("""adj_pair_geom(pair, slot, s.gx, s.gq, &d2, p2, fr2, &nu2, cot, gb)""",
1550
+ """adj_pair_geom_aux(pair, slot, s.taux[c], s.gx, s.gq, &d2, p2, fr2, &nu2, cot, gb)"""),
1551
+ )
1552
+
1553
+ ADJ_TREE_CHOL_HOOKS = (
1554
+ (" tri_solve_packed(s.L, s.y, lane);\n", " chol_tree_solve(s.L, s.y, lane); // (DK_TREE_CHOL: L_Q is R)\n"),
1555
+ (" tri_mul_llt(s.L, s.a, s.tmp, s.did, lane);\n",
1556
+ " tri_mul_rtr(s.L, s.a, s.tmp, s.did, lane); // (DK_TREE_CHOL: L_Q is R)\n"),
1557
+ )
1558
+ ADJ_TREE_CHOL_NEWTON_HOOKS = (
1559
+ (" tri_solve_packed(s.L, s.lam, lane);\n", " chol_tree_solve(s.L, s.lam, lane); // (DK_TREE_CHOL: L_H is R)\n"),
1560
+ )
1561
+
1562
+
1563
+ def tree_chol_hooks(m):
1564
+ """The adjoint's DK_TREE_CHOL hooks for model m (() when off; the forward's: step.tree_chol_hooks)."""
1565
+ st = step.tree_chol_stages(m)
1566
+ if st is None:
1567
+ return ()
1568
+ return ADJ_TREE_CHOL_HOOKS + (ADJ_TREE_CHOL_NEWTON_HOOKS if st["newton"] else ())
1569
+
1570
+
1571
+ ADJ_BOUNDS_BLOCK = """// ADJ_MAXNREG (defined and > 0): k_adjoint's register cap as __maxnreg__(N) (nvcc 12.4+); this block is inserted
1572
+ // only where the build target sets it (nablaengine.cuda.adjoint_defines: sm_103 120; tree_adj_cap_defines: sm_90 168 on
1573
+ // terrain builds). Register allocation only: the
1574
+ // gradients are bitwise those of the uncapped build.
1575
+ #if defined(ADJ_MAXNREG) && ADJ_MAXNREG > 0
1576
+ #if __CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__ < 1204
1577
+ #error "ADJ_MAXNREG: __maxnreg__ needs nvcc 12.4 or newer"
1578
+ #endif
1579
+ #define ADJ_BOUNDS __maxnreg__(ADJ_MAXNREG)
1580
+ #else
1581
+ #define ADJ_BOUNDS
1582
+ #endif
1583
+ """
1584
+ ADJ_KERNEL_DECL = "__global__ void k_adjoint("
1585
+
1586
+
1587
+ def with_adj_bounds(src):
1588
+ """src (a unit's text with the G1 k_adjoint) with ADJ_BOUNDS_BLOCK before k_adjoint and k_adjoint declared with
1589
+ ADJ_BOUNDS (its register cap under -DADJ_MAXNREG=N). Only for the units that get that define (cuda.adjoint_defines)."""
1590
+ assert src.count(ADJ_KERNEL_DECL) == 1, "with_adj_bounds: one k_adjoint definition expected"
1591
+ return src.replace(ADJ_KERNEL_DECL, ADJ_BOUNDS_BLOCK + "__global__ void ADJ_BOUNDS k_adjoint(")
1592
+
1593
+
1594
+ def cuda_source(m, max_contacts=None, terrain=None, params=None, max_rows=None, motor=None, bam=None):
1595
+ """The device code of the forward and the adjoint as one compilation unit, with k_adjoint's launch helpers
1596
+ (adj_launch_smem; no __global__ forward kernel, no host main). terrain: (TerrainConfig, robot geoms) for a terrain
1597
+ build (nablaengine.terrain; step.step_header). Models outside the G1's structure get model_hooks' edits. params:
1598
+ a nablaengine.params.PhysicsParams (per-world parameters: world_params; none: the text unchanged). max_contacts,
1599
+ max_rows: the capacities per world (step.check_capacity; None: the defaults, the text unchanged). motor: a
1600
+ nablaengine.motor.MotorLimits (torque-speed limits: motor_hooks; None: the text unchanged). $DK_TREE_CHOL
1601
+ (step.tree_chol; default 0: the text unchanged) applies the tree-sparse factorizations' hooks. bam: a
1602
+ nablaengine.actuators.Bam (the BAM servo model's forward: bam_hooks; None: the text unchanged)."""
1603
+ step.check_capacity(m, max_contacts, max_rows, terrain)
1604
+ condim4.check(m, terrain, params)
1605
+ maxd = source.max_depth(m)
1606
+ adj = adjoint_contact.source(m) + ADJ_DEVICE + ADJ_KERNEL
1607
+ if terrain is not None:
1608
+ adj = step.apply_hooks(adj, ADJ_TERRAIN_HOOKS)
1609
+ adj = step.apply_hooks(adj, (
1610
+ ("__device__ __noinline__ int adj_terrain_geom(", DUAL_DEVICE + capbox_dual_source() + CBTER_DIR_VJP_TREE
1611
+ + "__device__ __noinline__ int adj_terrain_geom("),
1612
+ (" if (!cot) return br;\n const float* pb = cot + 1;\n",
1613
+ " if (!cot) return br;\n" + ADJ_CAPBOX_DUAL_TREE + " const float* pb = cot + 1;\n")))
1614
+ adj = step.object_hooks(adj, step.OBJECT_ADJ_HOOKS, terrain)
1615
+ if terrain[0].mode == "native":
1616
+ adj = step.apply_hooks(adj, ADJ_NATIVE_HOOKS)
1617
+ src = model_hooks.apply(condim4.apply(step.apply_hooks(
1618
+ source.header(m, maxd, 1) + step.EXTRA_HEADER + step.step_header(m, max_contacts, terrain, max_rows)
1619
+ + tape.header(m, max_contacts, tape.kind(terrain), max_rows, motor is not None) + header(m) + source.DEVICE
1620
+ + step.terrain_source(step.STEP_DEVICE + step.STEP_KERNEL, terrain) + adj,
1621
+ step.capacity_hooks(m, max_rows, terrain) + elliptic.hooks(m, step.STEP_DEVICE + step.STEP_KERNEL)
1622
+ + elliptic.adj_hooks(m) + motor_hooks.hooks(m, motor)), m), m)
1623
+ import mujoco
1624
+ if terrain is not None and any(int(m.geom_type[g]) == mujoco.mjtGeom.mjGEOM_BOX for g, _, _ in terrain[1]):
1625
+ src = model_hooks._apply(src, model_hooks.terrain_box_geom_hooks(m))
1626
+ robot_cb, terrain_cb = "cbt_dir_vjp(" in src, "cbter_dir_vjp(" in src
1627
+ if robot_cb or terrain_cb:
1628
+ src = model_hooks._apply(src, model_hooks.capbox_coop_hooks(model_hooks.tree_coop_dispatch(robot_cb, terrain_cb),
1629
+ model_hooks.tree_coop_dev(robot_cb)))
1630
+ src = step.apply_hooks(src, step.tree_chol_hooks(m) + tree_chol_hooks(m))
1631
+ from nablaengine.g1_engine import world_params
1632
+ from nablaengine.model import invweight
1633
+ src = invweight.apply(src, m, step.collision_geoms(m))
1634
+ src = world_params.apply(src, m, params, "engine", terrain[0].com_words() if terrain is not None else 3)
1635
+ if bam is not None:
1636
+ from nablaengine._optional import BAM, load
1637
+ bam_hooks = load("nablaengine.g1_engine", BAM, "bam_hooks")
1638
+ src = bam_hooks.engine(src, bam, m.nv)
1639
+ from nablaengine.g1_engine import exact_replay, replay_guard
1640
+ src = exact_replay.apply(src, m)
1641
+ return replay_guard.apply(src, m, terrain)
1642
+
1643
+
1644
+ def engine_constants(m, foot_pairs, terrain=None, com_body=None):
1645
+ """(constants as one float32 array, [(symbol, kind, count, width)] in packing order, sizes) for the host loader
1646
+ (scripts/engine_step_check.py loader()), as engine_step_check packs them (terrain: as cuda_source; com_body:
1647
+ source.constants')."""
1648
+ c1, _ = source.constants(m, com_body)
1649
+ c2 = step.pair_constants(m, foot_pairs, terrain)
1650
+ dofbody, mask = step.extra_constants(m)
1651
+ halves, alay = step.ancmask_packed(m, mask)
1652
+ consts = np.concatenate([c1, c2, dofbody.astype(np.float32), halves])
1653
+ sizes = {"nb": m.nbody, "nv": m.nv, "one": 1, "nv2": 2 * m.nv}
1654
+ lays = (list(source.const_layout(m)) + [(s, k, n, 1) for s, k, n in step.const_layout(m, terrain)]
1655
+ + [("c_dofbody", "i", "nv", 1), alay])
1656
+ from nablaengine.g1_engine import mesh
1657
+ mc = mesh.constants(m)
1658
+ if mc:
1659
+ consts = np.concatenate([consts] + mc)
1660
+ lays += [(s, k, n, 1) for s, k, n in mesh.layout(m)]
1661
+ return consts, lays, sizes