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,1124 @@
1
+ """MuJoCo's noslip post-pass on the forest engine (opt.noslip_iterations > 0, opt.noslip_tolerance): forward and adjoint.
2
+
3
+ The pass follows MuJoCo 3.17's mj_solNoSlip and its use in mj_fwdConstraint (engine_solver.c, engine_forward.c;
4
+ github.com/google-deepmind/mujoco, Apache License 2.0; the algorithm is reimplemented here in float32, no code is
5
+ copied). After the Newton solve, with the Newton forces f* of every row:"""
6
+
7
+ import mujoco
8
+ import numpy as np
9
+
10
+ NS_FLAG_NONCONV = 1 << 8
11
+ NS_FLAG_OVERFLOW = 1 << 9
12
+ NS_FLAG_SKIPPED = 1 << 10
13
+ ADJ_NOSLIP = 1 << 14
14
+ NS_STATUS = dict(free=0, upper=1, lower=2, newton=3)
15
+ CON_WORDS = 13
16
+
17
+
18
+ def enabled(m):
19
+ """True when model m asks for the noslip pass."""
20
+ return int(m.opt.noslip_iterations) > 0
21
+
22
+
23
+ def ns_cap(m, max_contacts=None):
24
+ """Friction-direction capacity per world: the frictionloss rows plus (2 or, with condim-4 pairs, 3) per contact,
25
+ at most 128."""
26
+ from nablaengine.forest_engine import step
27
+ nc = max_contacts or step.maxcon(m)
28
+ per = 3 if bool((m.pair_dim == 4).any()) else 2
29
+ return int(min(int((m.dof_frictionloss > 0).sum()) + per * nc, 128))
30
+
31
+
32
+ def problems(m):
33
+ """Reasons the forest engine's noslip pass does not take model m (empty: supported, or noslip off)."""
34
+ if not enabled(m):
35
+ return []
36
+ out = []
37
+ if int(m.opt.cone) == int(mujoco.mjtCone.mjCONE_ELLIPTIC):
38
+ out.append("elliptic cone (the noslip pass is implemented for the pyramidal cone)")
39
+ if m.neq:
40
+ out.append("equality constraints (their rows join islands and need the adjoint's split; not verified)")
41
+ if m.ntendon:
42
+ out.append("tendons (tendon limit / frictionloss rows; not verified)")
43
+ if m.nbody > 32:
44
+ out.append("more than 31 bodies (forest_engine.nb64; not verified)")
45
+ if m.nv > 64:
46
+ out.append("more than 64 dofs (forest_engine.nv128; not verified)")
47
+ if mujoco.mjtDisableBit.mjDSBL_ISLAND & int(m.opt.disableflags):
48
+ out.append("islands disabled (the pass runs per island, MuJoCo's default)")
49
+ return out
50
+
51
+
52
+ def check(m):
53
+ p = problems(m)
54
+ if p:
55
+ raise ValueError("noslip (opt.noslip_iterations > 0) on the forest engine: not supported for this model: "
56
+ + "; ".join(p))
57
+
58
+
59
+ PARAM_FIELDS = ("object_size", "torso_mass", "torso_inertia", "dof_damping", "foot_solref", "foot_solimp",
60
+ "foot_torsional")
61
+
62
+
63
+ def resolve_pairs(m, spec):
64
+ """noslip_pairs to a sorted tuple of pair indices, or None when it selects every pair (the unrestricted text).
65
+ spec: "objects" (the pairs with a geom on an unactuated tree rooted in a free joint and the other geom on another
66
+ body that is not the world: robot / object and object / object contacts, not object / floor), or an iterable of
67
+ pair indices, pair names, or (name, name) of two bodies or two geoms."""
68
+ import mujoco
69
+ if spec is None:
70
+ return None
71
+ O = mujoco.mjtObj
72
+ if isinstance(spec, str):
73
+ if spec != "objects":
74
+ raise ValueError(f"noslip_pairs={spec!r}: a rule is 'objects', else a list of pairs")
75
+ act_trees = {int(m.body_rootid[m.jnt_bodyid[m.actuator_trnid[a, 0]]]) for a in range(m.nu)
76
+ if m.actuator_trntype[a] == mujoco.mjtTrn.mjTRN_JOINT}
77
+
78
+ def obj(b):
79
+ r = int(m.body_rootid[b])
80
+ return (b > 0 and r not in act_trees and m.body_jntnum[r] == 1
81
+ and m.jnt_type[m.body_jntadr[r]] == mujoco.mjtJoint.mjJNT_FREE)
82
+ sel = []
83
+ for p in range(m.npair):
84
+ b1, b2 = int(m.geom_bodyid[m.pair_geom1[p]]), int(m.geom_bodyid[m.pair_geom2[p]])
85
+ if b1 > 0 and b2 > 0 and (obj(b1) or obj(b2)) and m.body_rootid[b1] != m.body_rootid[b2]:
86
+ sel.append(p)
87
+ else:
88
+ sel = set()
89
+ for e in spec:
90
+ if isinstance(e, (int, np.integer)):
91
+ if not 0 <= int(e) < m.npair:
92
+ raise ValueError(f"noslip_pairs: pair index {e} outside 0 .. {m.npair - 1}")
93
+ sel.add(int(e))
94
+ elif isinstance(e, str):
95
+ p = mujoco.mj_name2id(m, O.mjOBJ_PAIR, e)
96
+ if p < 0:
97
+ raise ValueError(f"noslip_pairs: no pair named {e!r}")
98
+ sel.add(p)
99
+ else:
100
+ a, b = e
101
+ ga, gb = mujoco.mj_name2id(m, O.mjOBJ_GEOM, a), mujoco.mj_name2id(m, O.mjOBJ_GEOM, b)
102
+ if ga >= 0 and gb >= 0:
103
+ hit = [p for p in range(m.npair) if {int(m.pair_geom1[p]), int(m.pair_geom2[p])} == {ga, gb}]
104
+ else:
105
+ ba, bb = mujoco.mj_name2id(m, O.mjOBJ_BODY, a), mujoco.mj_name2id(m, O.mjOBJ_BODY, b)
106
+ if ba < 0 or bb < 0:
107
+ raise ValueError(f"noslip_pairs: {e!r} names neither two geoms nor two bodies")
108
+ hit = [p for p in range(m.npair) if {int(m.geom_bodyid[m.pair_geom1[p]]),
109
+ int(m.geom_bodyid[m.pair_geom2[p]])} == {ba, bb}]
110
+ if not hit:
111
+ raise ValueError(f"noslip_pairs: no contact pair between {a!r} and {b!r}")
112
+ sel.update(hit)
113
+ sel = tuple(sorted(sel))
114
+ if not sel:
115
+ raise ValueError("noslip_pairs selects no contact pair")
116
+ return None if len(sel) == m.npair else sel
117
+
118
+
119
+ def mask_text(m, pairs):
120
+ """The pair mask of a restricted build (c_nsmask, NS_PAIR) or, for None, NS_PAIR true."""
121
+ if pairs is None:
122
+ return "#define NS_PAIR(pr) true // (every pair: MuJoCo's noslip)\n"
123
+ w = [0] * ((m.npair + 31) // 32)
124
+ for p in pairs:
125
+ w[p >> 5] |= 1 << (p & 31)
126
+ return (f"__device__ const unsigned c_nsmask[{len(w)}] = {{{', '.join(f'{x}u' for x in w)}}}; // noslip_pairs\n"
127
+ "#define NS_PAIR(pr) ((c_nsmask[(pr) >> 5] >> ((pr) & 31)) & 1u)\n")
128
+
129
+
130
+ def check_foot(m, params, foot_pairs, pairs):
131
+ """ValueError for foot parameters (PhysicsParams foot_*) with foot pairs in the noslip rows."""
132
+ if not params or not any(f.startswith("foot_") for f in params.fields):
133
+ return
134
+ fp = {int(p) for p in np.asarray(foot_pairs if foot_pairs is not None else [], int).ravel()}
135
+ sel = set(range(m.npair)) if pairs is None else set(pairs)
136
+ both = sorted(fp & {p for p in sel if int(m.pair_dim[p]) >= 3})
137
+ if both:
138
+ raise ValueError(f"noslip: the foot parameters ({[f for f in params.fields if f.startswith('foot_')]}) need the"
139
+ f" foot pairs outside the noslip rows (noslip_pairs); in them: {both[:8]}")
140
+
141
+
142
+ def check_params(m, params, pairs=None):
143
+ """ValueError for PhysicsParams fields the noslip build does not take (params: a PhysicsParams or None)."""
144
+ if not params:
145
+ return
146
+ bad = [f for f in params.fields if f not in PARAM_FIELDS]
147
+ if bad:
148
+ raise ValueError(f"noslip (opt.noslip_iterations > 0): PhysicsParams {bad} not supported (it takes "
149
+ f"{PARAM_FIELDS}; dof_armature, gravity, xfrc: their lam1 terms of the second pass are missing)")
150
+
151
+
152
+ PFOOT_PARTIALS = " if (PFOOT(pair) && zone) { // the foot pair's parameters (world_params)\n"
153
+
154
+
155
+ def params_hooks(src):
156
+ """The world_params text with noslip: the foot pairs' parameter partials in pass A only."""
157
+ return _rep(src, PFOOT_PARTIALS, " if (PFOOT(pair) && zone && !s.ns_pass) { // the foot pair's parameters "
158
+ "(world_params; noslip: pass A only)\n")
159
+
160
+
161
+ def defines(m, max_contacts=None):
162
+ tol = float(np.float32(m.opt.noslip_tolerance))
163
+ return (f"#define NOSLIP 1 // forest_engine.noslip: MuJoCo's noslip post-pass\n"
164
+ f"#define NS_ITER {int(m.opt.noslip_iterations)} // opt.noslip_iterations\n"
165
+ f"#define NS_TOL {tol!r}f // opt.noslip_tolerance\n"
166
+ f"#define NS_CAP {ns_cap(m, max_contacts)} // friction directions per world\n"
167
+ f"#define NS_NSR ((NS_CAP + 31) / 32)\n"
168
+ f"#define NS_FLAG_NONCONV {NS_FLAG_NONCONV}u\n#define NS_FLAG_OVERFLOW {NS_FLAG_OVERFLOW}u\n"
169
+ f"#define NS_FLAG_SKIPPED {NS_FLAG_SKIPPED}u\n#define NS_CON_WORDS {CON_WORDS}\n")
170
+
171
+
172
+
173
+ HAND = """ // forest_engine.noslip: the pass's scratch (k_post)
174
+ float ns_f[NEFC]; // the rows' forces (Newton, then noslip)
175
+ float ns_f0[NEFC]; // the Newton forces f*
176
+ float ns_Z[NS_CAP][NV]; // L^-1 g_k of direction k
177
+ float ns_A[NS_CAP][NS_CAP]; // A = Z' Z = G M^-1 G'
178
+ int ns_dir[NS_CAP]; // direction k: its first row | pair t << 10 (3: a frictionloss row) | contact << 12
179
+ int ns_dst[NS_CAP]; // its final status (noslip.NS_STATUS)
180
+ int ns_k0[MAXCON]; // contact c's first direction
181
+ int ns_isl[NB]; // tree (root body) -> island representative, -1: no rows
182
+ float ns_scale[NB]; // island representative -> 1 / trace(M) over its dofs
183
+ """
184
+
185
+ FWD_DECL = """
186
+ #if NOSLIP
187
+ template <class S> __device__ void noslip_pass(S& s, int lane, float* rec); // (forest_engine.noslip)
188
+ #endif
189
+ """
190
+
191
+ FWD_DEVICE = r"""
192
+ // ---------------------------------------------------------------- noslip (forest_engine.noslip)
193
+ __device__ __forceinline__ int ns_tree(int b) { return b > 0 ? c_root[b] : -1; }
194
+ __device__ __forceinline__ int ns_find(int* par, int x) { while (par[x] != x) x = par[x]; return x; }
195
+
196
+ // L x = b, then L' x = x (in place; packed lower L, shared vector b)
197
+ __device__ __noinline__ void ns_llt_solve(const float* L, float* b, int lane) {
198
+ for (int k = 0; k < NV; k++) {
199
+ const float bk = b[k] / L[TRI(k, k)];
200
+ __syncwarp();
201
+ if (lane == 0) b[k] = bk;
202
+ for (int i = k + 1 + lane; i < NV; i += 32) b[i] -= L[TRI(i, k)] * bk;
203
+ __syncwarp();
204
+ }
205
+ for (int k = NV - 1; k >= 0; k--) {
206
+ const float bk = b[k] / L[TRI(k, k)];
207
+ __syncwarp();
208
+ if (lane == 0) b[k] = bk;
209
+ for (int i = lane; i < k; i += 32) b[i] -= L[TRI(k, i)] * bk;
210
+ __syncwarp();
211
+ }
212
+ }
213
+
214
+ // direction k's row g (pair t of contact c: g = J_{2t} - J_{2t+1} = 2 mu_t T_t; a frictionloss row: e_dof) dotted with
215
+ // the shared vector v
216
+ template <class S>
217
+ __device__ __forceinline__ float ns_gdot(const S& s, int dir, const float* v) {
218
+ const int r0 = dir & 1023, t = (dir >> 10) & 3, c = dir >> 12;
219
+ if (t == 3) return v[s.efc_a[r0]];
220
+ const float mu = t == 2 ? 0.f : s.con_mu[c];
221
+ float mt = mu;
222
+ #if HAS_CONDIM4
223
+ if (t == 2) mt = PMUS(s.con_pair[c]);
224
+ #endif
225
+ float acc = 0.f;
226
+ const int nd = s.con_nd[c];
227
+ for (int k = 0; k < nd; k++) acc += s.con_J[c][1 + t][k] * v[s.con_dof[c][k]];
228
+ return 2.f * mt * acc;
229
+ }
230
+
231
+ template <class S>
232
+ __device__ void noslip_pass(S& s, int lane, float* rec) {
233
+ if constexpr (!dk_is_ptr<decltype(s.qsm)>::value) { // the fused forward: no scratch, no pass (flagged)
234
+ if (rec && lane == 0) __stcs(rec + OFF_NSHDR, __uint_as_float(NS_FLAG_SKIPPED));
235
+ return;
236
+ } else {
237
+ // the world's struct Hand from k_post's pointer into it (post_world_on: s.qsm = g.qsm, also for Hand::big)
238
+ Hand& g = *reinterpret_cast<Hand*>(reinterpret_cast<char*>(const_cast<float*>(s.qsm)) - offsetof(Hand, qsm));
239
+ const unsigned FULL = 0xffffffffu, below = (1u << lane) - 1u;
240
+ const int nefc = s.nefc, ncon = uniform_int(min(s.ncon, MAXCON), CON_BITS);
241
+ float* F = g.ns_f;
242
+ // the Newton forces f* (the rows' -s'(jar)), the tape's a*
243
+ for (int r = lane; r < nefc; r += 32) {
244
+ float ds, dd, c;
245
+ row_eval(s, r, s.efc_jar[r], &ds, &dd, &c);
246
+ F[r] = -ds;
247
+ g.ns_f0[r] = -ds;
248
+ }
249
+ if (rec) tape_put(rec + OFF_NSQN, s.qacc, NV, OFF_NSHDR - OFF_NSQN, lane);
250
+ __syncwarp();
251
+ // L = chol(M); tmp = qacc of the dual (MuJoCo's AR f + b): M^-1 (qfrc_smooth + J' f*)
252
+ rows_jtf(s, F, s.tmp, lane);
253
+ for (int i = lane; i < NV; i += 32) s.tmp[i] += s.qsm[i];
254
+ for (int e = lane; e < NTRI; e += 32) s.L[e] = s.M[e];
255
+ __syncwarp();
256
+ CHOL_M_SOLVE(s.L, s.L, s.tmp, lane, s.cbuf);
257
+ if (rec) tape_put(rec + OFF_LM, s.L, NTRI, REC_WORDS - OFF_LM, lane);
258
+ // directions: the frictionloss rows (the first NFLOSS rows), then per contact of condim >= 3 its row pairs
259
+ int nd = NFLOSS;
260
+ for (int k = lane; k < NFLOSS && k < NS_CAP; k += 32) g.ns_dir[k] = k | 3 << 10;
261
+ for (int c0 = 0; c0 < ncon; c0 += 32) {
262
+ const int c = c0 + lane;
263
+ const int np = c < ncon && s.con_dim[c] >= 3 && NS_PAIR(s.con_pair[c]) ? min(s.con_dim[c] - 1, s.con_nrow[c] / 2) : 0;
264
+ int inc = np;
265
+ for (int o = 1; o < 32; o <<= 1) {
266
+ const int t = __shfl_up_sync(FULL, inc, o);
267
+ if (lane >= o) inc += t;
268
+ }
269
+ const int k0 = nd + inc - np;
270
+ if (c < ncon) g.ns_k0[c] = k0;
271
+ for (int t = 0; t < np; t++)
272
+ if (k0 + t < NS_CAP) g.ns_dir[k0 + t] = (s.con_row[c] + 2 * t) | t << 10 | c << 12;
273
+ nd += __shfl_sync(FULL, inc, 31);
274
+ }
275
+ const int ndir = min(nd, NS_CAP);
276
+ unsigned hdr = nd > NS_CAP ? NS_FLAG_OVERFLOW : 0u;
277
+ // islands (lane 0): trees joined by the contacts; a tree with a row is constrained; scale = 1 / trace(M) per island
278
+ if (lane == 0) {
279
+ int* par = g.ns_isl;
280
+ unsigned long long used = 0ull;
281
+ for (int b = 0; b < NB; b++) par[b] = b;
282
+ for (int r = 0; r < nefc; r++) {
283
+ const int kind = s.efc_kind[r], a = s.efc_a[r];
284
+ if (kind <= 1) { used |= 1ull << ns_tree(c_dofbody[a]); continue; }
285
+ const int pr = s.con_pair[a], t1 = ns_tree(c_gbody[PG1(pr)]), t2 = ns_tree(c_gbody[PG2(pr)]);
286
+ if (t1 >= 0) used |= 1ull << t1;
287
+ if (t2 >= 0) used |= 1ull << t2;
288
+ if (t1 >= 0 && t2 >= 0) {
289
+ const int x = ns_find(par, t1), y = ns_find(par, t2);
290
+ if (x != y) par[max(x, y)] = min(x, y);
291
+ }
292
+ }
293
+ for (int b = 0; b < NB; b++) g.ns_scale[b] = 0.f;
294
+ for (int i = 0; i < NV; i++) {
295
+ const int t = ns_tree(c_dofbody[i]);
296
+ if ((used >> t) & 1ull) g.ns_scale[ns_find(par, t)] += s.M[TRI(i, i)];
297
+ }
298
+ for (int b = 0; b < NB; b++) {
299
+ g.ns_scale[b] = 1.f / fmaxf(1e-15f, g.ns_scale[b]);
300
+ par[b] = (used >> b) & 1ull ? ns_find(par, b) : -1; // (ascending b: a parent is below its child)
301
+ }
302
+ }
303
+ __syncwarp();
304
+ // per direction (lane k & 31, register k >> 5): Z = L^-1 g in global scratch, residual, mid / bound, island
305
+ float rr[NS_NSR], yy[NS_NSR], mm[NS_NSR];
306
+ int isl[NS_NSR], st[NS_NSR];
307
+ #pragma unroll
308
+ for (int t = 0; t < NS_NSR; t++) {
309
+ const int k = lane + 32 * t;
310
+ rr[t] = yy[t] = mm[t] = 0.f; isl[t] = -1; st[t] = 0;
311
+ if (k >= ndir) continue;
312
+ const int dir = g.ns_dir[k], r0 = dir & 1023, tt = (dir >> 10) & 3, c = dir >> 12;
313
+ float* z = g.ns_Z[k];
314
+ for (int i = 0; i < NV; i++) z[i] = 0.f;
315
+ if (tt == 3) {
316
+ z[s.efc_a[r0]] = 1.f;
317
+ isl[t] = g.ns_isl[ns_tree(c_dofbody[s.efc_a[r0]])];
318
+ rr[t] = s.tmp[s.efc_a[r0]] - s.efc_aref[r0];
319
+ yy[t] = F[r0]; mm[t] = c_floss[s.efc_a[r0]];
320
+ } else {
321
+ float mt = s.con_mu[c];
322
+ #if HAS_CONDIM4
323
+ if (tt == 2) mt = PMUS(s.con_pair[c]);
324
+ #endif
325
+ const int ndc = s.con_nd[c];
326
+ for (int q = 0; q < ndc; q++) z[s.con_dof[c][q]] = 2.f * mt * s.con_J[c][1 + tt][q];
327
+ const int pr = s.con_pair[c], t1 = ns_tree(c_gbody[PG1(pr)]);
328
+ isl[t] = g.ns_isl[t1 >= 0 ? t1 : ns_tree(c_gbody[PG2(pr)])];
329
+ rr[t] = ns_gdot(s, dir, s.tmp) - (s.efc_aref[r0] - s.efc_aref[r0 + 1]);
330
+ mm[t] = 0.5f * (F[r0] + F[r0 + 1]); yy[t] = 0.5f * (F[r0] - F[r0 + 1]);
331
+ }
332
+ for (int i = 0; i < NV; i++) { // forward substitution in place
333
+ float x = z[i];
334
+ for (int j = 0; j < i; j++) x -= s.L[TRI(i, j)] * z[j];
335
+ z[i] = x / s.L[TRI(i, i)];
336
+ }
337
+ }
338
+ __syncwarp();
339
+ for (int q = lane; q < ndir * ndir; q += 32) { // A = Z' Z (each pair once, both halves: symmetric)
340
+ const int a = q / ndir, b = q - a * ndir;
341
+ if (b < a) continue;
342
+ float acc = 0.f;
343
+ for (int i = 0; i < NV; i++) acc += g.ns_Z[a][i] * g.ns_Z[b][i];
344
+ g.ns_A[a][b] = acc;
345
+ g.ns_A[b][a] = acc;
346
+ }
347
+ __syncwarp();
348
+ // the sweeps; islands (representative body ids < 64) by bits; the improvement of island j on lane j & 31
349
+ unsigned long long live = 0ull;
350
+ #pragma unroll
351
+ for (int t = 0; t < NS_NSR; t++) if (isl[t] >= 0) live |= 1ull << isl[t];
352
+ for (int o = 16; o > 0; o >>= 1) live |= __shfl_xor_sync(FULL, live, o);
353
+ // every island with rows takes part (MuJoCo: also the ones without friction directions; they stop after 2 sweeps)
354
+ unsigned long long all = 0ull;
355
+ for (int r = lane; r < nefc; r += 32) {
356
+ const int kind = s.efc_kind[r], a = s.efc_a[r];
357
+ int tr;
358
+ if (kind <= 1) tr = ns_tree(c_dofbody[a]);
359
+ else { const int pr = s.con_pair[a]; tr = ns_tree(c_gbody[PG1(pr)]); if (tr < 0) tr = ns_tree(c_gbody[PG2(pr)]); }
360
+ all |= 1ull << g.ns_isl[tr];
361
+ }
362
+ for (int o = 16; o > 0; o >>= 1) all |= __shfl_xor_sync(FULL, all, o);
363
+ unsigned long long done = 0ull;
364
+ int niter = 0;
365
+ for (int it = 0; it < NS_ITER; it++) {
366
+ if ((all & ~done) == 0ull) break;
367
+ float imp[2] = {0.f, 0.f};
368
+ if (it == 0) // 0.5 sum f^2 R over the island's rows
369
+ for (int r0 = 0; r0 < nefc; r0 += 32) {
370
+ const int r = r0 + lane;
371
+ float term = 0.f;
372
+ int j = -1;
373
+ if (r < nefc) {
374
+ const int kind = s.efc_kind[r], a = s.efc_a[r];
375
+ int tr;
376
+ if (kind <= 1) tr = ns_tree(c_dofbody[a]);
377
+ else { const int pr = s.con_pair[a]; tr = ns_tree(c_gbody[PG1(pr)]); if (tr < 0) tr = ns_tree(c_gbody[PG2(pr)]); }
378
+ j = g.ns_isl[tr];
379
+ term = 0.5f * F[r] * F[r] / s.efc_D[r];
380
+ }
381
+ for (int q = 0; q < 32; q++) {
382
+ const float tq = __shfl_sync(FULL, term, q);
383
+ const int jq = __shfl_sync(FULL, j, q);
384
+ if (jq >= 0 && (jq & 31) == lane) imp[jq >> 5] += tq;
385
+ }
386
+ }
387
+ #pragma unroll 1
388
+ for (int k = 0; k < ndir; k++) {
389
+ const int ow = k & 31, tk = k >> 5;
390
+ float r = rr[0], y = yy[0], m = mm[0];
391
+ int ik = isl[0];
392
+ #pragma unroll
393
+ for (int t = 1; t < NS_NSR; t++)
394
+ if (tk == t) { r = rr[t]; y = yy[t]; m = mm[t]; ik = isl[t]; }
395
+ r = __shfl_sync(FULL, r, ow); y = __shfl_sync(FULL, y, ow); m = __shfl_sync(FULL, m, ow);
396
+ ik = __shfl_sync(FULL, ik, ow);
397
+ if ((done >> ik) & 1ull) continue;
398
+ const float akk = g.ns_A[k][k];
399
+ const bool fl = k < NFLOSS;
400
+ float yn, chg;
401
+ int bnd = 0;
402
+ if (fl) {
403
+ const float ainv = 1.f / fmaxf(1e-15f, akk);
404
+ yn = y - r * ainv;
405
+ if (yn < -m) yn = -m; else if (yn > m) yn = m;
406
+ const float d = yn - y;
407
+ chg = 0.5f * d * d / ainv + d * r;
408
+ } else {
409
+ if (akk < 1e-15f) yn = 0.f;
410
+ else {
411
+ yn = y - r / akk;
412
+ if (yn < -m) { yn = -m; bnd = 2; } else if (yn > m) { yn = m; bnd = 1; }
413
+ }
414
+ const float d = yn - y;
415
+ chg = 0.5f * akk * d * d + d * r;
416
+ if (chg > 1e-10f) { yn = y; chg = 0.f; bnd = -1; } // (the cost went up: restored, status kept)
417
+ }
418
+ if ((ik & 31) == lane) imp[ik >> 5] -= chg;
419
+ const float d = yn - y;
420
+ if (d != 0.f) {
421
+ const float* Ak = g.ns_A[k];
422
+ #pragma unroll
423
+ for (int t = 0; t < NS_NSR; t++) {
424
+ const int kp = lane + 32 * t;
425
+ if (kp < ndir) rr[t] += Ak[kp] * d;
426
+ }
427
+ }
428
+ if (lane == ow)
429
+ #pragma unroll
430
+ for (int t = 0; t < NS_NSR; t++)
431
+ if (tk == t) { yy[t] = yn; if (bnd >= 0) st[t] = bnd; }
432
+ }
433
+ niter = it + 1;
434
+ // per island: stop when the scaled improvement is below the tolerance
435
+ unsigned long long stop = 0ull;
436
+ #pragma unroll
437
+ for (int h = 0; h < 2; h++) {
438
+ const int j = lane + 32 * h;
439
+ if (j < NB && ((all & ~done) >> j) & 1ull && imp[h] * g.ns_scale[j] < NS_TOL) stop |= 1ull << j;
440
+ }
441
+ for (int o = 16; o > 0; o >>= 1) stop |= __shfl_xor_sync(FULL, stop, o);
442
+ done |= stop;
443
+ }
444
+ if ((all & ~done) != 0ull) hdr |= NS_FLAG_NONCONV;
445
+ // the final forces and statuses
446
+ #pragma unroll
447
+ for (int t = 0; t < NS_NSR; t++) {
448
+ const int k = lane + 32 * t;
449
+ if (k >= ndir) continue;
450
+ const int dir = g.ns_dir[k], r0 = dir & 1023;
451
+ if (((dir >> 10) & 3) == 3) F[r0] = yy[t];
452
+ else { F[r0] = mm[t] + yy[t]; F[r0 + 1] = mm[t] - yy[t]; }
453
+ g.ns_dst[k] = st[t];
454
+ }
455
+ __syncwarp();
456
+ if (rec) {
457
+ for (int c = lane; c < MAXCON; c += 32) {
458
+ unsigned w = 0u;
459
+ if (c < ncon && s.con_dim[c] >= 3) {
460
+ const int np = min(s.con_dim[c] - 1, s.con_nrow[c] / 2), k0 = g.ns_k0[c];
461
+ const bool sel = NS_PAIR(s.con_pair[c]); // (a pair outside noslip_pairs: its rows keep the Newton forces)
462
+ for (int t = 0; t < np; t++) w |= (unsigned)(sel && k0 + t < ndir ? g.ns_dst[k0 + t] : 3) << (2 * t);
463
+ }
464
+ __stcs(rec + OFF_NSST + c, __uint_as_float(w));
465
+ }
466
+ tape_put(rec + OFF_NSF, F, nefc, OFF_NSDF - OFF_NSF, lane);
467
+ tape_put(rec + OFF_NSJAR, s.efc_jar, nefc, OFF_LM - OFF_NSJAR, lane); // (the Newton x = J a* - aref of the rows)
468
+ for (int r = lane; r < OFF_NSJAR - OFF_NSDF; r += 32) __stcs(rec + OFF_NSDF + r, r < nefc ? F[r] - g.ns_f0[r] : 0.f);
469
+ if (lane == 0) __stcs(rec + OFF_NSHDR, __uint_as_float(hdr | (unsigned)min(niter, 255)));
470
+ }
471
+ // qacc = M^-1 (qfrc_smooth + J' f), M qacc, and the rows' forces for the contact forces
472
+ rows_jtf(s, F, s.tmp, lane);
473
+ for (int i = lane; i < NV; i += 32) s.tmp[i] += s.qsm[i];
474
+ __syncwarp();
475
+ ns_llt_solve(s.L, s.tmp, lane);
476
+ for (int i = lane; i < NV; i += 32) s.qacc[i] = s.tmp[i];
477
+ __syncwarp();
478
+ matvec(s.M, s.qacc, s.Ma, lane);
479
+ for (int r = lane; r < nefc; r += 32) s.efc_jv[r] = F[r];
480
+ __syncwarp();
481
+ }
482
+ }
483
+ """
484
+
485
+ PRE_ANCHOR = (" __stcs(rec + OFF_CON + i, __uint_as_float(e));\n }\n}\n")
486
+ PRE_ADD = (" __stcs(rec + OFF_CON + i, __uint_as_float(e));\n }\n"
487
+ " if (rec) { // tape (forest_engine.noslip): each contact's position, frame and its rows' D\n"
488
+ " __syncwarp();\n"
489
+ " for (int i = lane; i < MAXCON; i += 32) {\n"
490
+ " float* o = rec + OFF_NSCON + NS_CON_WORDS * i;\n"
491
+ " const bool v = i < ncon;\n"
492
+ " for (int t = 0; t < 3; t++) __stcs(o + t, v ? s.con_pos[i][t] : 0.f);\n"
493
+ " for (int t = 0; t < 9; t++) __stcs(o + 3 + t, v ? s.con_frame[i][t] : 0.f);\n"
494
+ " __stcs(o + 12, v && s.con_nrow[i] > 0 ? s.efc_D[s.con_row[i]] : 0.f);\n"
495
+ " }\n"
496
+ " }\n}\n")
497
+
498
+ PRE_ANCHOR_W1 = (" __stcs(rec + OFF_CON + i, __uint_as_float(e));\n }\n } // warp 1 (or the only warp)\n")
499
+
500
+ ZONE_BLOCK = (" if (rec) { // tape: the final zones and their Hessian factor, before the implicitfast solve overwrites L\n"
501
+ " unsigned z = zone_word(s, lane);\n"
502
+ " if (lane < (NEFC + 31) / 32) __stcs(rec + OFF_ZONE + lane, __uint_as_float(z));\n"
503
+ " tape_put(rec + OFF_LH, s.L, NTRI, OFF_LQ - OFF_LH, lane);\n"
504
+ " }\n")
505
+ NITER = " if (niter_out && lane == 0) *niter_out = it;\n"
506
+ OFORCE_EVAL = (" for (int r = lane; r < s.nefc; r += 32) {\n"
507
+ " float ds, dd, cst;\n"
508
+ " row_eval(s, r, s.efc_jar[r], &ds, &dd, &cst);\n"
509
+ " s.efc_jv[r] = -ds;\n"
510
+ " }\n"
511
+ " __syncwarp();\n"
512
+ " const int nc = min(s.ncon, MAXCON);\n")
513
+ LQ_PUT = " tape_put(rec + OFF_LQ, s.L, NTRI, REC_WORDS - OFF_LQ, lane);\n"
514
+ POST_ANCHOR = "template <class S>\n__device__ void substep_post(S& s, int iterations, int lane, int* niter_out, float* rec) {\n"
515
+ HAND_ANCHOR = " SimNfull big; // k_post's state of a world whose contacts or rows exceed SimN's capacity\n"
516
+
517
+
518
+ def _rep(src, a, b, n=1):
519
+ assert src.count(a) == n, f"noslip anchor found {src.count(a)} times (want {n}): {a[:80]!r}"
520
+ return src.replace(a, b)
521
+
522
+
523
+ def apply_forward(src, m, max_contacts=None, pairs=None):
524
+ """The engine text (adjoint.cuda_source's) with the forward pass; asserts every anchor."""
525
+ src = _rep(src, "#define REC_WORDS", defines(m, max_contacts) + mask_text(m, pairs) + "#define REC_WORDS")
526
+ src = _rep(src, HAND_ANCHOR, HAND_ANCHOR + HAND)
527
+ if src.count(PRE_ANCHOR) == 0 and src.count(PRE_ANCHOR_W1) == 1:
528
+ src = _rep(src, PRE_ANCHOR_W1, PRE_ADD[:-len("}\n")] + " } // warp 1 (or the only warp)\n")
529
+ else:
530
+ src = _rep(src, PRE_ANCHOR, PRE_ADD)
531
+ src = _rep(src, ZONE_BLOCK, "")
532
+ src = _rep(src, NITER, NITER + ZONE_BLOCK + " noslip_pass(s, lane, rec); // (forest_engine.noslip)\n")
533
+ src = _rep(src, OFORCE_EVAL, " const int nc = min(s.ncon, MAXCON); // (noslip_pass left the rows' forces)\n")
534
+ src = _rep(src, LQ_PUT, " tape_put(rec + OFF_LQ, s.L, NTRI, OFF_NSQN - OFF_LQ, lane);\n")
535
+ src = _rep(src, POST_ANCHOR, FWD_DECL + POST_ANCHOR)
536
+ i = src.index("struct SimP {")
537
+ j = src.index("\n};\n", i) + 4
538
+ src = src[:j] + FWD_DEVICE + src[j:]
539
+ return src
540
+
541
+
542
+
543
+ ADJ_DOC = """
544
+ The adjoint of a noslip substep (implicit function theorem at the converged point, the active set frozen: the Newton
545
+ rows' zones as the engine's adjoint, and the pyramid pairs' statuses of the noslip pass: free, at +m, at -m).
546
+
547
+ Unknowns: the Newton acceleration a* (Newton's stationarity r_N(a*) = M a* - tau - J' f*(a*) = 0, f* = -D x on the
548
+ quadratic zones) and the noslip acceleration a with the free pairs' y_S:
549
+ R1 = M a - tau - J' f_ns = 0, f_ns = f* on the other rows, (m + y, m - y) on the pairs (m = (f*_0 + f*_1) / 2,
550
+ y = y_S free, y = +-m bound),
551
+ R2 = g_k . (a + b v) = 0 for the free pairs (g_k = J_0 - J_1 = 2 mu T_k; aref_0 - aref_1 = -b g_k v).
552
+ Given a bar (from the integrator: a enters implicitfast), the KKT adjoint [M G_S'; G_S 0] [lam1; lam2] = [a bar; 0]
553
+ gives lam1 = L^-T (I - Q Q') L^-1 a bar and lam2 = R^-1 Q' L^-1 a bar from the CGS2 QR Z = Q R of the free directions
554
+ Z = L^-1 G_S' (L = chol(M) from the tape; directions with |z| <= 1e-3 |z0| after the projection are dependent and get
555
+ lam2 = 0: the step is consistent for any lam2 of the redundant set). f* enters R1 through the mids and the fixed rows:
556
+ f*_bar_e = phi_e = l_n + sigma_t mu_t l_t on the rows of pair t (sigma 0 free, +-1 bound, l = J lam1), J_e lam1 on
557
+ every other row (limits, frictionless contacts, untouched pairs). With psi_e = phi_e - J_e lam1 (nonzero on pyramid
558
+ rows only), lam_N = H^-1 a*_bar, a*_bar = -sum_zone D_e J_e' phi_e, so lam_N + lam1 = H^-1 (M lam1 - sum_zone D_e J_e'
559
+ psi_e) (L_H, L_M from the tape).
560
+
561
+ The explicit partials, without the cancellation of two large terms (with pairs at the cone's bound lam1 and lamN
562
+ can be 100x the gradient and opposite): lam1 (R1 at a_ns) + lamN (r_N at a*) = lam_tot (r_N at a*) + lam1 (R1 at a_ns
563
+ minus r_N at a*), the latter's bias, actuator and Jacobian-value terms cancelling exactly:
564
+ pass A the engine's residual VJP at (a*, lam_tot, -y): RNE and actuator terms, the integrator's M(q) term at
565
+ a_ns - a_adv (channel 2), the limit rows with lam_tot, the contacts' Psi = sum_zone D x_e (u_e . V_lam_tot +
566
+ psi_e) (psi_e = phi_e - J_e lam1: the noslip cotangent beyond lam1's own);
567
+ pass B lam1' M(q) (a_ns - a*) (channel 2 with seed lam1, no channel 1), the contacts' geometry terms
568
+ Psi = -sum_e (f_ns,e - f*_e) (u_e . V_lam1) + sum_t kappa_t T_t . (V_a + b V_v) (V_a of a_ns; kappa_t = 2 mu_t
569
+ lam2_t); no actuator, damping or limit terms.
570
+ Not differentiated (refused: forest_engine.noslip.problems / adjoint.cuda_source): the elliptic cone, frictionloss
571
+ rows (the forest adjoint has none), equality and tendon rows, per-world parameters, the surrogates, terrain.
572
+ """
573
+
574
+ ADJ_STRUCT_ANCHOR = "#if DK_ADJ_CLAMP_KV == 2\n float u[NU], soft;"
575
+ ADJ_STRUCT = (" // forest_engine.noslip: a*, a_ns, lam1, lam_tot, scratch, the free directions' QR in L^-1 space, per contact\n"
576
+ " // the rows' f_ns - f*, psi and kappa (2 mu lam2), and the pass (1: B, 0: A)\n"
577
+ " float ns_qn[NV], ns_an[NV], ns_l1[NV], ns_lN[NV], ns_u[NV], ns_w[NV], ns_g[NV], ns_zero[NV], ns_h[NS_QC];\n"
578
+ " float ns_B[32][NV], ns_Q[NS_QC][NV], ns_R[NS_QC * (NS_QC + 1) / 2]; // a batch of L^-1 g, Q, R\n"
579
+ " float ns_Hb[32][NS_QC], ns_n0[32]; // the batch's Gram-Schmidt coefficients, squared norms\n int ns_dk[32]; // Q column -> its direction; direction -> contact | pair << 8\n"
580
+ " float ns_fns[MAXCON][6], ns_phi[MAXCON][6], ns_kap[MAXCON][3];\n"
581
+ " int ns_col[MAXCON][3], ns_pass;\n" + ADJ_STRUCT_ANCHOR)
582
+
583
+ ADJ_DEVICE = r"""
584
+ // ---------------------------------------------------------------- noslip adjoint (forest_engine.noslip)
585
+ // contact rows on dof i: J_u,i = s_i u . col_i, and the angular one s_i u . z_i (0 for translations and slides)
586
+ __device__ __forceinline__ void ns_dof_col(const Adj& s, int pair, const float* p, int i, float* col, float* ang) {
587
+ const int b1 = c_gbody[PG1(pair)], b2 = c_gbody[PG2(pair)];
588
+ const unsigned m1 = c_ancmask[b1], m2 = c_ancmask[b2];
589
+ const int bi = c_dofbody[i];
590
+ for (int t = 0; t < 3; t++) col[t] = ang[t] = 0.f;
591
+ if (!(((m1 ^ m2) >> bi) & 1u)) return;
592
+ const float sg = (m2 >> bi) & 1u ? 1.f : -1.f;
593
+ const int jt = JT_OF(bi), k = i - c_dadr[bi];
594
+ if (jt == JFREE && k < 3) { col[k] = sg; return; }
595
+ float z[3], r[3];
596
+ if (jt == JFREE) {
597
+ const float ek[3] = {k == 3 ? 1.f : 0.f, k == 4 ? 1.f : 0.f, k == 5 ? 1.f : 0.f};
598
+ qrot(s.Q[bi], ek, z);
599
+ } else qrot(s.Q[bi], c_axis + 3 * bi, z);
600
+ if (jt == JSLIDE) { for (int t = 0; t < 3; t++) col[t] = sg * z[t]; return; }
601
+ for (int t = 0; t < 3; t++) r[t] = p[t] - s.X[bi][t];
602
+ cross(z, r, col);
603
+ for (int t = 0; t < 3; t++) { col[t] *= sg; ang[t] = sg * z[t]; }
604
+ }
605
+
606
+ // b = L^-1 b in place (packed lower L, shared b)
607
+ __device__ __noinline__ void ns_fwd_solve(const float* L, float* b, int lane) {
608
+ for (int k = 0; k < NV; k++) {
609
+ const float bk = b[k] / L[TRI(k, k)];
610
+ __syncwarp();
611
+ if (lane == 0) b[k] = bk;
612
+ for (int i = k + 1 + lane; i < NV; i += 32) b[i] -= L[TRI(i, k)] * bk;
613
+ __syncwarp();
614
+ }
615
+ }
616
+ __device__ __noinline__ void ns_bwd_solve(const float* L, float* b, int lane) {
617
+ for (int k = NV - 1; k >= 0; k--) {
618
+ const float bk = b[k] / L[TRI(k, k)];
619
+ __syncwarp();
620
+ if (lane == 0) b[k] = bk;
621
+ for (int i = lane; i < k; i += 32) b[i] -= L[TRI(k, i)] * bk;
622
+ __syncwarp();
623
+ }
624
+ }
625
+
626
+ // the noslip stage after adj_solves (s.abar = a bar of the noslip acceleration): lam1 (s.ns_l1), lamN (s.ns_lN), and
627
+ // per contact ns_fns, ns_phi, ns_kap (noslip.ADJ_DOC)
628
+ __device__ __noinline__ void adj_noslip(Adj& s, const float* rec, int lane) {
629
+ LANE_BOUND(lane);
630
+ const int ncon = s.hdr & 255, nlim = ((unsigned)s.hdr >> 18) & 63;
631
+ for (int i = lane; i < NV; i += 32) s.ns_u[i] = s.abar[i];
632
+ for (int e = lane; e < NTRI; e += 32) s.L[e] = __ldcs(rec + OFF_LM + e);
633
+ __syncwarp();
634
+ ns_fwd_solve(s.L, s.ns_u, lane);
635
+ // the free directions (contact by contact, pair by pair) in batches of 32, one lane per direction: their rows g
636
+ // (ns_B), Z = L^-1 g, classical Gram-Schmidt twice against the columns so far (Q in ns_Q, coefficients in ns_Hb),
637
+ // then right-looking modified Gram-Schmidt within the batch. A direction whose residual norm is above 1e-3 of its
638
+ // own norm becomes the next unit column (R in ns_R); dependent directions get lam2 = 0. (Was: one direction at a time
639
+ // on the whole warp, 16 of the backward's 42 ms on the G1.)
640
+ int rank = 0;
641
+ for (int b0 = 0;; b0 += 32) {
642
+ int nS = 0, r0 = nlim;
643
+ for (int i = lane; i < 32 * NV; i += 32) (&s.ns_B[0][0])[i] = 0.f;
644
+ __syncwarp();
645
+ for (int c = 0; c < ncon; c++) {
646
+ const unsigned e = s.con[c];
647
+ const int pair = e & 0xFFFFu, dim = PDIM(pair);
648
+ const int nr = max(0, min(dim >= 3 ? (dim == 4 ? 6 : 4) : 1, NEFC - r0));
649
+ const int rc = r0;
650
+ r0 += dim >= 3 ? (dim == 4 ? 6 : 4) : 1;
651
+ unsigned zone = 0u;
652
+ if (nr > 0) {
653
+ const int w = rc >> 5;
654
+ unsigned long long zz = s.zone[w];
655
+ if (w + 1 < (NEFC + 31) / 32) zz |= (unsigned long long)s.zone[w + 1] << 32;
656
+ zone = (unsigned)(zz >> (rc & 31)) & ((1u << nr) - 1u);
657
+ }
658
+ if (b0 == 0) {
659
+ if (lane < 6) s.ns_fns[c][lane] = lane < nr ? __ldcs(rec + OFF_NSDF + rc + lane) : 0.f; // (f_ns - f*)
660
+ if (lane < 3) { s.ns_col[c][lane] = -1; s.ns_kap[c][lane] = 0.f; }
661
+ if (lane < 6) s.ns_phi[c][lane] = 0.f;
662
+ }
663
+ if (!zone || dim < 3) continue;
664
+ const unsigned st = __float_as_uint(__ldcs(rec + OFF_NSST + c));
665
+ const int np = min(dim - 1, nr / 2);
666
+ unsigned fm = 0u; // the free pairs
667
+ for (int t = 0; t < np; t++)
668
+ if (((st >> (2 * t)) & 3u) == 0u) fm |= 1u << t;
669
+ if (!fm) continue;
670
+ const int n = __popc(fm);
671
+ if (nS + n > b0 && nS < b0 + 32) { // a direction of this batch
672
+ const float* cw = rec + OFF_NSCON + NS_CON_WORDS * c;
673
+ float p[3], fr[9];
674
+ for (int t = 0; t < 3; t++) p[t] = __ldcs(cw + t);
675
+ for (int t = 0; t < 9; t++) fr[t] = __ldcs(cw + 3 + t);
676
+ const float mu = PFOOT(pair) ? s.fric : PMU(pair);
677
+ #if HAS_CONDIM4
678
+ const float mus = dim == 4 ? PMUS(pair) : 0.f;
679
+ #else
680
+ const float mus = 0.f;
681
+ #endif
682
+ for (int i = lane; i < NV; i += 32) {
683
+ float col[3], ang[3];
684
+ ns_dof_col(s, pair, p, i, col, ang);
685
+ int k = nS;
686
+ for (int t = 0; t < 3; t++)
687
+ if ((fm >> t) & 1u) {
688
+ if (k >= b0 && k < b0 + 32)
689
+ s.ns_B[k - b0][i] = t == 2 ? 2.f * mus * dot3(fr, ang) : 2.f * mu * dot3(fr + 3 * (1 + t), col);
690
+ k++;
691
+ }
692
+ }
693
+ if (lane == 0)
694
+ for (int t = 0, k = nS; t < 3; t++)
695
+ if ((fm >> t) & 1u) { if (k >= b0 && k < b0 + 32) s.ns_dk[k - b0] = c | t << 8; k++; }
696
+ }
697
+ nS += n;
698
+ }
699
+ const int nb = min(32, nS - b0);
700
+ if (nb <= 0) break;
701
+ __syncwarp();
702
+ if (lane < nb) { // this lane's direction: Z = L^-1 g, |z|^2, CGS2 against the columns so far
703
+ float* z = s.ns_B[lane];
704
+ for (int i = 0; i < NV; i++) {
705
+ float x = z[i];
706
+ for (int j = 0; j < i; j++) x -= s.L[TRI(i, j)] * z[j];
707
+ z[i] = x / s.L[TRI(i, i)];
708
+ }
709
+ float n0 = 0.f;
710
+ for (int i = 0; i < NV; i++) n0 += z[i] * z[i];
711
+ s.ns_n0[lane] = n0;
712
+ for (int j = 0; j < rank; j++) s.ns_Hb[lane][j] = 0.f;
713
+ for (int pass = 0; pass < 2; pass++)
714
+ for (int j = 0; j < rank; j++) {
715
+ const float* q = s.ns_Q[j];
716
+ float h = 0.f;
717
+ for (int i = 0; i < NV; i++) h += q[i] * z[i];
718
+ for (int i = 0; i < NV; i++) z[i] -= h * q[i];
719
+ s.ns_Hb[lane][j] += h;
720
+ }
721
+ }
722
+ __syncwarp();
723
+ for (int k = 0; k < nb; k++) { // within the batch: right-looking MGS
724
+ const float* z = s.ns_B[k];
725
+ float n1 = 0.f;
726
+ for (int i = lane; i < NV; i += 32) n1 += z[i] * z[i];
727
+ n1 = sqrtf(warp_sum(n1));
728
+ if (!(rank < NS_QC && n1 > 1e-3f * sqrtf(s.ns_n0[k]))) continue; // (uniform: warp_sum)
729
+ for (int i = lane; i < NV; i += 32) s.ns_Q[rank][i] = z[i] / n1;
730
+ for (int j = lane; j < rank; j += 32) s.ns_R[TRI(rank, j)] = s.ns_Hb[k][j];
731
+ if (lane == 0) {
732
+ s.ns_R[TRI(rank, rank)] = n1;
733
+ s.ns_col[s.ns_dk[k] & 255][s.ns_dk[k] >> 8] = rank;
734
+ }
735
+ __syncwarp();
736
+ const int k2 = k + 1 + lane;
737
+ if (k2 < nb) { // the later directions of the batch against q
738
+ float* z2 = s.ns_B[k2];
739
+ const float* q = s.ns_Q[rank];
740
+ float h = 0.f;
741
+ for (int i = 0; i < NV; i++) h += q[i] * z2[i];
742
+ for (int i = 0; i < NV; i++) z2[i] -= h * q[i];
743
+ s.ns_Hb[k2][rank] = h;
744
+ }
745
+ rank++;
746
+ __syncwarp();
747
+ }
748
+ if (nb < 32) break;
749
+ }
750
+ // lam2 (on the independent columns) = R^-1 Q' u; w = u - Q Q' u; lam1 = L^-T w
751
+ for (int q = 0; q < 2; q++) {
752
+ const int j = lane + 32 * q;
753
+ if (j < rank) { const float* qj = s.ns_Q[j]; float acc = 0.f; for (int i = 0; i < NV; i++) acc += qj[i] * s.ns_u[i]; s.ns_h[j] = acc; }
754
+ }
755
+ __syncwarp();
756
+ for (int i = lane; i < NV; i += 32) {
757
+ float acc = s.ns_u[i];
758
+ for (int j = 0; j < rank; j++) acc -= s.ns_h[j] * s.ns_Q[j][i];
759
+ s.ns_l1[i] = acc;
760
+ }
761
+ if (lane == 0)
762
+ for (int j = rank - 1; j >= 0; j--) {
763
+ float x = s.ns_h[j];
764
+ for (int k = j + 1; k < rank; k++) x -= s.ns_R[TRI(k, j)] * s.ns_w[k];
765
+ s.ns_w[j] = x / s.ns_R[TRI(j, j)];
766
+ }
767
+ __syncwarp();
768
+ ns_bwd_solve(s.L, s.ns_l1, lane);
769
+ // kappa, phi, and g = M lam1 - sum_zone D_e J_e' psi_e
770
+ for (int c = 0; c < ncon; c++) {
771
+ const unsigned e = s.con[c];
772
+ const int pair = e & 0xFFFFu, dim = PDIM(pair);
773
+ if (lane < 3 && s.ns_col[c][lane] >= 0) {
774
+ const float mu = PFOOT(pair) ? s.fric : PMU(pair);
775
+ #if HAS_CONDIM4
776
+ const float mt = lane == 2 ? PMUS(pair) : mu;
777
+ #else
778
+ const float mt = mu;
779
+ #endif
780
+ s.ns_kap[c][lane] = 2.f * mt * s.ns_w[s.ns_col[c][lane]];
781
+ }
782
+ }
783
+ for (int i = lane; i < NV; i += 32) s.ns_g[i] = 0.f;
784
+ __syncwarp();
785
+ int r0 = nlim;
786
+ for (int c = 0; c < ncon; c++) {
787
+ const unsigned e = s.con[c];
788
+ const int pair = e & 0xFFFFu, dim = PDIM(pair);
789
+ const int nr = max(0, min(dim >= 3 ? (dim == 4 ? 6 : 4) : 1, NEFC - r0));
790
+ const int rc = r0;
791
+ r0 += dim >= 3 ? (dim == 4 ? 6 : 4) : 1;
792
+ unsigned zone = 0u;
793
+ if (nr > 0) {
794
+ const int w = rc >> 5;
795
+ unsigned long long zz = s.zone[w];
796
+ if (w + 1 < (NEFC + 31) / 32) zz |= (unsigned long long)s.zone[w + 1] << 32;
797
+ zone = (unsigned)(zz >> (rc & 31)) & ((1u << nr) - 1u);
798
+ }
799
+ if (!zone && !NS_ALL_ROWS) continue; // (cone_mu: every contact's rows have a slope weight)
800
+ const unsigned st = dim >= 3 ? __float_as_uint(__ldcs(rec + OFF_NSST + c)) : 0u;
801
+ const float* cw = rec + OFF_NSCON + NS_CON_WORDS * c;
802
+ float p[3], fr[9];
803
+ for (int t = 0; t < 3; t++) p[t] = __ldcs(cw + t);
804
+ for (int t = 0; t < 9; t++) fr[t] = __ldcs(cw + 3 + t);
805
+ const float D = __ldcs(cw + 12), mu = PFOOT(pair) ? s.fric : PMU(pair);
806
+ #if HAS_CONDIM4
807
+ const float mus = dim == 4 ? PMUS(pair) : 0.f;
808
+ #else
809
+ const float mus = 0.f;
810
+ #endif
811
+ float l[4] = {0.f, 0.f, 0.f, 0.f}; // n, t1, t2, r rows times lam1
812
+ for (int i = lane; i < NV; i += 32) {
813
+ float col[3], ang[3];
814
+ ns_dof_col(s, pair, p, i, col, ang);
815
+ const float li = s.ns_l1[i];
816
+ l[0] += dot3(fr, col) * li; l[1] += dot3(fr + 3, col) * li; l[2] += dot3(fr + 6, col) * li;
817
+ l[3] += dot3(fr, ang) * li;
818
+ }
819
+ for (int q = 0; q < 4; q++) l[q] = warp_sum(l[q]);
820
+ float phi[6] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f}, psi[6] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
821
+ if (dim < 3) phi[0] = l[0];
822
+ else
823
+ for (int t = 0; t < nr / 2; t++) {
824
+ const float mt = t == 2 ? mus : mu, lt = t == 2 ? l[3] : l[1 + t];
825
+ const float le0 = l[0] + mt * lt, le1 = l[0] - mt * lt;
826
+ const unsigned sx = (st >> (2 * t)) & 3u;
827
+ const float ph = sx == 0u ? l[0] : sx == 1u ? le0 : le1;
828
+ phi[2 * t] = sx == 3u ? le0 : ph;
829
+ phi[2 * t + 1] = sx == 3u ? le1 : ph;
830
+ psi[2 * t] = phi[2 * t] - le0;
831
+ psi[2 * t + 1] = phi[2 * t + 1] - le1;
832
+ }
833
+ if (lane < 6) s.ns_phi[c][lane] = psi[lane]; // (pass A's offsets: psi = phi - J lam1)
834
+ float cn = 0.f, ct[3] = {0.f, 0.f, 0.f};
835
+ for (int q = 0; q < nr; q++) {
836
+ const float wq = NS_ROW_W(rc + q, (zone >> q) & 1u, (zone >> (q & ~1)) & 3u); // (a row's slope weight)
837
+ if (wq == 0.f) continue;
838
+ cn += wq * psi[q];
839
+ const int t = q >> 1;
840
+ if (dim >= 3) ct[t] += wq * ((q & 1) ? -1.f : 1.f) * (t == 2 ? mus : mu) * psi[q];
841
+ }
842
+ if (cn != 0.f || ct[0] != 0.f || ct[1] != 0.f || ct[2] != 0.f)
843
+ for (int i = lane; i < NV; i += 32) {
844
+ float col[3], ang[3];
845
+ ns_dof_col(s, pair, p, i, col, ang);
846
+ s.ns_g[i] += D * (cn * dot3(fr, col) + ct[0] * dot3(fr + 3, col) + ct[1] * dot3(fr + 6, col)
847
+ + ct[2] * dot3(fr, ang));
848
+ }
849
+ __syncwarp();
850
+ }
851
+ // w = M lam1 - g (M = L L'), lam_tot = H^-1 w, lamN = lam_tot - lam1
852
+ for (int i = lane; i < NV; i += 32) {
853
+ float acc = 0.f;
854
+ for (int k = i; k < NV; k++) acc += s.L[TRI(k, i)] * s.ns_l1[k];
855
+ s.ns_u[i] = acc;
856
+ }
857
+ __syncwarp();
858
+ for (int i = lane; i < NV; i += 32) {
859
+ float acc = 0.f;
860
+ for (int k = 0; k <= i; k++) acc += s.L[TRI(i, k)] * s.ns_u[k];
861
+ s.ns_w[i] = acc - s.ns_g[i];
862
+ }
863
+ __syncwarp();
864
+ for (int e = lane; e < NTRI; e += 32) s.L[e] = __ldcs(rec + OFF_LH + e);
865
+ __syncwarp();
866
+ NS_TOT_SOLVE(s.L, s.ns_w, lane); // (lam_tot = H^-1 w; the surrogate's cone_mu: H_mu, surrogate_hooks)
867
+ for (int i = lane; i < NV; i += 32) s.ns_lN[i] = s.ns_w[i]; // lam_tot = lamN + lam1
868
+ __syncwarp();
869
+ }
870
+ """
871
+
872
+ PSI_DEVICE = r"""
873
+ // pass A: contact_psi_vjp with the offset psi_e of each row added to u_e . V_lam in the force-value terms
874
+ __device__ __forceinline__ void contact_psi_phi(const float* Vv, const float* Va, const float* Vl, const float* fr,
875
+ float mu, int dim, unsigned zone, float d, float D, float dD, float k,
876
+ float b, float imp, float dimp, const float* phi, float* Wv, float* Wa,
877
+ float* Wl, float* dbar, float* frbar
878
+ #if HAS_CONDIM4
879
+ , const float* Ov, const float* Oa, const float* Ol, float mus,
880
+ float* AWv, float* AWa, float* AWl
881
+ #endif
882
+ ) {
883
+ float vf[3], af[3], lf[3];
884
+ #pragma unroll
885
+ for (int j = 0; j < 3; j++) {
886
+ vf[j] = dot3(fr + 3 * j, Vv); af[j] = dot3(fr + 3 * j, Va); lf[j] = dot3(fr + 3 * j, Vl);
887
+ }
888
+ float g = k * imp * d, gd = k * (imp + dimp * d);
889
+ float cl[3] = {0.f, 0.f, 0.f}, ca[3] = {0.f, 0.f, 0.f}, db = 0.f;
890
+ #pragma unroll
891
+ for (int e = 0; e < 4; e++) {
892
+ if (!((zone >> e) & 1u) || (e > 0 && dim < 3)) continue;
893
+ const int t = 1 + (e >> 1);
894
+ float sm = (e & 1) ? -mu : mu;
895
+ float uv = vf[0], ua = af[0], ul = lf[0];
896
+ if (dim >= 3) { uv += sm * vf[t]; ua += sm * af[t]; ul += sm * lf[t]; }
897
+ const float uw = ul + phi[e];
898
+ float x = ua + g + b * uv, Dx = D * x, Dl = D * uw;
899
+ cl[0] += Dx; ca[0] += Dl;
900
+ if (dim >= 3) { cl[t] += sm * Dx; ca[t] += sm * Dl; }
901
+ db += uw * (dD * x + D * gd);
902
+ }
903
+ #if HAS_CONDIM4
904
+ float awl = 0.f, awa = 0.f;
905
+ if (dim == 4) {
906
+ const float wv = dot3(fr, Ov), wa = dot3(fr, Oa), wl = dot3(fr, Ol);
907
+ #pragma unroll
908
+ for (int e = 4; e < 6; e++) {
909
+ if (!((zone >> e) & 1u)) continue;
910
+ const float sm = (e & 1) ? -mus : mus;
911
+ const float uv = vf[0] + sm * wv, ua = af[0] + sm * wa, ul = lf[0] + sm * wl, uw = ul + phi[e];
912
+ const float x = ua + g + b * uv, Dx = D * x, Dl = D * uw;
913
+ cl[0] += Dx; ca[0] += Dl;
914
+ awl += sm * Dx; awa += sm * Dl;
915
+ db += uw * (dD * x + D * gd);
916
+ }
917
+ }
918
+ #pragma unroll
919
+ for (int i = 0; i < 3; i++) { AWl[i] = awl * fr[i]; AWa[i] = awa * fr[i]; AWv[i] = b * AWa[i]; }
920
+ #endif
921
+ #pragma unroll
922
+ for (int i = 0; i < 3; i++) {
923
+ Wl[i] = cl[0] * fr[i] + cl[1] * fr[3 + i] + cl[2] * fr[6 + i];
924
+ Wa[i] = ca[0] * fr[i] + ca[1] * fr[3 + i] + ca[2] * fr[6 + i];
925
+ Wv[i] = b * Wa[i];
926
+ }
927
+ float ab[3] = {Va[0] + b * Vv[0], Va[1] + b * Vv[1], Va[2] + b * Vv[2]};
928
+ #pragma unroll
929
+ for (int j = 0; j < 3; j++)
930
+ #pragma unroll
931
+ for (int i = 0; i < 3; i++) frbar[3 * j + i] = cl[j] * Vl[i] + ca[j] * ab[i];
932
+ #if HAS_CONDIM4
933
+ #pragma unroll
934
+ for (int i = 0; i < 3; i++) frbar[i] += awl * Ol[i] + awa * (Oa[i] + b * Ov[i]);
935
+ #endif
936
+ *dbar = db;
937
+ }
938
+
939
+ // pass B: Psi = -sum_e f_e (u_e . V_lam) + sum_t kappa_t T_t . (V_a + b V_v) (f: f_ns - f* of the rows, V_lam of
940
+ // lam1, V_a of the noslip acceleration); no distance term
941
+ __device__ __forceinline__ void contact_psi_ns(const float* Vv, const float* Va, const float* Vl, const float* fr,
942
+ float mu, int dim, float b, const float* fns, const float* kap,
943
+ float* Wv, float* Wa, float* Wl, float* dbar, float* frbar
944
+ #if HAS_CONDIM4
945
+ , const float* Ov, const float* Oa, const float* Ol, float mus,
946
+ float* AWv, float* AWa, float* AWl
947
+ #endif
948
+ ) {
949
+ float cl[3] = {0.f, 0.f, 0.f}, ca[3] = {0.f, 0.f, 0.f};
950
+ #pragma unroll
951
+ for (int e = 0; e < 4; e++) {
952
+ if (e > 0 && dim < 3) continue;
953
+ const int t = 1 + (e >> 1);
954
+ const float sm = (e & 1) ? -mu : mu, f = fns[e];
955
+ cl[0] -= f;
956
+ if (dim >= 3) cl[t] -= sm * f;
957
+ }
958
+ if (dim >= 3) { ca[1] = kap[0]; ca[2] = kap[1]; }
959
+ #if HAS_CONDIM4
960
+ float awl = 0.f, awa = 0.f;
961
+ if (dim == 4) {
962
+ #pragma unroll
963
+ for (int e = 4; e < 6; e++) {
964
+ const float sm = (e & 1) ? -mus : mus, f = fns[e];
965
+ cl[0] -= f;
966
+ awl -= sm * f;
967
+ }
968
+ awa = kap[2];
969
+ }
970
+ #pragma unroll
971
+ for (int i = 0; i < 3; i++) { AWl[i] = awl * fr[i]; AWa[i] = awa * fr[i]; AWv[i] = b * AWa[i]; }
972
+ #endif
973
+ #pragma unroll
974
+ for (int i = 0; i < 3; i++) {
975
+ Wl[i] = cl[0] * fr[i] + cl[1] * fr[3 + i] + cl[2] * fr[6 + i];
976
+ Wa[i] = ca[0] * fr[i] + ca[1] * fr[3 + i] + ca[2] * fr[6 + i];
977
+ Wv[i] = b * Wa[i];
978
+ }
979
+ float ab[3] = {Va[0] + b * Vv[0], Va[1] + b * Vv[1], Va[2] + b * Vv[2]};
980
+ #pragma unroll
981
+ for (int j = 0; j < 3; j++)
982
+ #pragma unroll
983
+ for (int i = 0; i < 3; i++) frbar[3 * j + i] = cl[j] * Vl[i] + ca[j] * ab[i];
984
+ #if HAS_CONDIM4
985
+ #pragma unroll
986
+ for (int i = 0; i < 3; i++) frbar[i] += awl * Ol[i] + awa * (Oa[i] + b * Ov[i]);
987
+ #endif
988
+ *dbar = 0.f;
989
+ }
990
+ """
991
+
992
+ PSI_CALL4 = (" contact_psi_vjp(Vv, Va, Vl, fr, mu, dim, zone, d, D, dD, k, b, imp, dimp, Wv, Wa, Wl, cot, cot + 4, Ov, Oa, Ol,\n"
993
+ " dim == 4 ? PMUS(pair) : 0.f, AWv, AWa, AWl);\n")
994
+ PSI_CALL3 = " contact_psi_vjp(Vv, Va, Vl, fr, mu, dim, zone, d, D, dD, k, b, imp, dimp, Wv, Wa, Wl, cot, cot + 4);\n"
995
+ PSI_NEW4 = (" if (s.ns_pass) // (forest_engine.noslip: the two passes' contact terms)\n"
996
+ " contact_psi_ns(Vv, Va, Vl, fr, mu, dim, b, s.ns_fns[c], s.ns_kap[c], Wv, Wa, Wl, cot, cot + 4, Ov, Oa,\n"
997
+ " Ol, dim == 4 ? PMUS(pair) : 0.f, AWv, AWa, AWl);\n"
998
+ " else\n"
999
+ " contact_psi_phi(Vv, Va, Vl, fr, mu, dim, zone, d, D, dD, k, b, imp, dimp, s.ns_phi[c], Wv, Wa, Wl, cot,\n"
1000
+ " cot + 4, Ov, Oa, Ol, dim == 4 ? PMUS(pair) : 0.f, AWv, AWa, AWl);\n")
1001
+ PSI_NEW3 = (" if (s.ns_pass) // (forest_engine.noslip: the two passes' contact terms)\n"
1002
+ " contact_psi_ns(Vv, Va, Vl, fr, mu, dim, b, s.ns_fns[c], s.ns_kap[c], Wv, Wa, Wl, cot, cot + 4);\n"
1003
+ " else\n"
1004
+ " contact_psi_phi(Vv, Va, Vl, fr, mu, dim, zone, d, D, dD, k, b, imp, dimp, s.ns_phi[c], Wv, Wa, Wl, cot,\n"
1005
+ " cot + 4);\n")
1006
+
1007
+ FLAGS_ANCHOR = " s.flags |= (int)__float_as_uint(__ldcs(rec + OFF_FLAGS));\n"
1008
+ FLAGS_ADD = FLAGS_ANCHOR + (" if (__float_as_uint(__ldcs(rec + OFF_NSHDR)) & (NS_FLAG_NONCONV | NS_FLAG_OVERFLOW | NS_FLAG_SKIPPED))\n"
1009
+ f" s.flags |= {ADJ_NOSLIP}; // (noslip.ADJ_NOSLIP)\n")
1010
+ A0_ANCHOR = " if (lane < (NEFC + 31) / 32) s.zone[lane] = __float_as_uint(__ldcs(rec + OFF_ZONE + lane));\n"
1011
+ A0_ADD = A0_ANCHOR + (" for (int i = lane; i < NV; i += 32) { // (noslip: a_ns kept, the main pass at the Newton a*; at =\n"
1012
+ " s.ns_an[i] = s.a[i]; s.ns_qn[i] = __ldcs(rec + OFF_NSQN + i); s.a[i] = s.ns_qn[i]; // a_ns - a_adv)\n"
1013
+ " }\n")
1014
+ PASSES_OLD = " adj_tree_down(s, s.lam, s.ny, lane); // A3 (channel 2, twists), A4\n"
1015
+ PASSES_NEW = """ // forest_engine.noslip: lam1, lam_tot = lamN + lam1, psi, kappa, f_ns - f*; pass A: the Newton residual's VJP at a*
1016
+ // with lam_tot (contacts: psi offsets) and the integrator's -y at a_ns - a_adv; pass B (after A8): lam1's terms
1017
+ adj_noslip(s, rec, lane);
1018
+ for (int i = lane; i < NV; i += 32) s.lam[i] = s.ns_lN[i];
1019
+ if (lane == 0) s.ns_pass = 0;
1020
+ __syncwarp();
1021
+ adj_tree_down(s, s.lam, s.ny, lane); // A3 (channel 2, twists), A4
1022
+ """
1023
+ COMPOSE_OLD = " adj_compose(s, lane); // A8\n APROF(APROF_COMPOSE);\n"
1024
+ COMPOSE_NEW = COMPOSE_OLD + """ // pass B (forest_engine.noslip): lam1' M(q) (a_ns - a*) as channel 2 (seed lam1, accelerations a_ns - a*), the
1025
+ // contacts' -lam1' J' (f_ns - f*) and lam2' G (a_ns + b v) (geometry only); no channel 1, actuator or limit terms
1026
+ for (int i = lane; i < NV; i += 32) {
1027
+ s.at[i] = s.ns_an[i] - s.ns_qn[i]; s.a[i] = s.ns_an[i]; s.lam[i] = s.ns_l1[i]; s.ny[i] = 0.f; s.ns_zero[i] = 0.f;
1028
+ }
1029
+ if (lane == 0) s.ns_pass = 1;
1030
+ __syncwarp();
1031
+ adj_poses(s, lane);
1032
+ adj_tree_down(s, s.ns_zero, s.ns_l1, lane);
1033
+ #if DK_ADJ_STAGE >= 2 && DK_ADJ_CONTACTS
1034
+ adj_contacts<false>(s, lane, nullptr);
1035
+ #endif
1036
+ adj_tree_up(s, s.ns_zero, s.ns_l1, lane);
1037
+ for (int i = lane; i < NV; i += 32) s.lam[i] = 0.f;
1038
+ __syncwarp();
1039
+ adj_compose(s, lane);
1040
+ """
1041
+ SUBSTEP_ANCHOR = "// one substep's VJP (A0-A8)"
1042
+
1043
+
1044
+ def apply_adjoint(src, m, surrogate=False):
1045
+ src = _rep(src, "#define REC_WORDS", "#define NS_QC (NV < NS_CAP ? NV : NS_CAP) // (noslip adjoint) QR columns\n"
1046
+ "#define NS_ROW_W(r, z, zp) ((z) ? 1.f : 0.f) // a contact row's weight in lam_tot's psi term: its zone\n"
1047
+ "#define NS_TOT_SOLVE(L, w, lane) tri_solve_packed(L, w, lane)\n#define NS_ALL_ROWS 0\n"
1048
+ "#ifdef DK_ADJ_DEBUG\n#error \"forest_engine.noslip: no -DDK_ADJ_DEBUG build\"\n#endif\n"
1049
+ "#if DK_CLAMP_IMPLICIT == 2\n#error \"forest_engine.noslip: not with DK_CLAMP_IMPLICIT=2\"\n#endif\n"
1050
+ "#define REC_WORDS")
1051
+ src = _rep(src, ADJ_STRUCT_ANCHOR, ADJ_STRUCT)
1052
+ src = _rep(src, "__device__ __forceinline__ float adj_contact_one(", PSI_DEVICE
1053
+ + "__device__ __forceinline__ float adj_contact_one(")
1054
+ if not surrogate:
1055
+ if src.count(PSI_CALL4):
1056
+ src = _rep(src, PSI_CALL4, PSI_NEW4)
1057
+ src = _rep(src, PSI_CALL3, PSI_NEW3)
1058
+ src = _rep(src, A0_ANCHOR, A0_ADD)
1059
+ src = _rep(src, FLAGS_ANCHOR, FLAGS_ADD)
1060
+ src = _rep(src, PASSES_OLD, PASSES_NEW)
1061
+ src = _rep(src, COMPOSE_OLD, COMPOSE_NEW)
1062
+ src = _rep(src, SUBSTEP_ANCHOR, ADJ_DEVICE + SUBSTEP_ANCHOR)
1063
+ return src
1064
+
1065
+
1066
+ def apply(src, m, max_contacts=None, pairs=None, surrogate=False):
1067
+ """The engine text with the noslip pass, forward and adjoint (adjoint.cuda_source); pairs: resolve_pairs'.
1068
+ surrogate: a contact_surrogate build (surrogate_hooks follows surrogate.apply)."""
1069
+ src = apply_forward(src, m, max_contacts, pairs)
1070
+ return apply_adjoint(src, m, surrogate)
1071
+
1072
+
1073
+ SUR_DOC = """
1074
+ noslip with the contact-gradient surrogates (init(contact_surrogate=True), backward cone_mu > 0): the main (Newton)
1075
+ solve's contact rows take the surrogate's central-path relaxation exactly as without noslip (surrogate.py): pass A's
1076
+ contact partials weight the slope terms by w_e and the force-value terms by the zone bit, and lam_tot = H_mu^-1 (M lam1
1077
+ - sum_e w_e D_e J_e' psi_e) with the surrogate's relaxed Hessian H_mu (every row of a contact with a quadratic row;
1078
+ psi_e = phi_e - J_e lam1 on every row, also of the contacts without a quadratic row: as the main solve's linearized
1079
+ law, the noslip pass sees their forces move). The noslip pass's own discrete state
1080
+ (the pairs at the cone's bound or free) stays exact. impulse_clip scales pass A's contact partials by the Newton
1081
+ forces' impulse; pass B is not clipped. cone_mu = 0 and no clip: the exact noslip adjoint's arithmetic.
1082
+ Not with per-world parameters (not verified).
1083
+ """
1084
+
1085
+
1086
+ def surrogate_hooks(src):
1087
+ """A noslip build's text after surrogate.apply (SUR_DOC): the two passes' dispatch inside the surrogate's wrapper,
1088
+ contact_psi_vjp_sur_phi, the relaxed weights and Hessian of lam_tot."""
1089
+ import re
1090
+ i = src.index("__device__ __forceinline__ float contact_psi_vjp_sur(")
1091
+ j = src.index("\n}\n", i) + 3
1092
+ f = src[i:j].replace("contact_psi_vjp_sur(", "contact_psi_vjp_sur_phi(", 1)
1093
+ f = f.replace("float* Wl, float* dbar, float* frbar, float smu", "float* Wl, float* dbar, float* frbar, float smu,\n"
1094
+ " const float* phi", 1)
1095
+ assert f.count("const float Dx = D * x, Dl = D * ul;") == 2 and f.count("db += ul * (") == 2
1096
+ f = f.replace("const float Dx = D * x, Dl = D * ul;", "const float Dx = D * x, Dl = D * (ul + phi[e]);")
1097
+ f = f.replace("db += ul * (", "db += (ul + phi[e]) * (")
1098
+ src = src[:j] + "// pass A with the surrogates (forest_engine.noslip.SUR_DOC): psi offsets as contact_psi_phi\n" + f + src[j:]
1099
+ for call, new, a4 in ((PSI_CALL4, PSI_NEW4, True), (PSI_CALL3, PSI_NEW3, False)):
1100
+ inner = "".join(" " + line + "\n" for line in call.rstrip("\n").split("\n"))
1101
+ if not src.count(inner):
1102
+ continue
1103
+ src = _rep(src, inner, "".join(" " + line + "\n" for line in new.rstrip("\n").split("\n")))
1104
+ pat = re.compile(r" const float fm = contact_psi_vjp_sur\(Vv, Va, Vl, fr, mu, dim, zone, d, D, dD, k, b, imp, dimp, Wv, Wa, Wl, cot,\n"
1105
+ r"\s+cot \+ 4, s\.sur_mu(?P<a4>[^;]*)\);\n")
1106
+ def sub(mt):
1107
+ a4 = mt.group("a4")
1108
+ ns4 = ", Ov, Oa, Ol, dim == 4 ? PMUS(pair) : 0.f, AWv, AWa, AWl" if a4 else ""
1109
+ return (" float fm = 0.f; // (noslip: pass B's contact terms unclipped, fm 0)\n"
1110
+ " if (s.ns_pass)\n"
1111
+ f" contact_psi_ns(Vv, Va, Vl, fr, mu, dim, b, s.ns_fns[c], s.ns_kap[c], Wv, Wa, Wl, cot, cot + 4{ns4});\n"
1112
+ " else\n"
1113
+ " fm = contact_psi_vjp_sur_phi(Vv, Va, Vl, fr, mu, dim, zone, d, D, dD, k, b, imp, dimp, Wv, Wa, Wl, cot,\n"
1114
+ f" cot + 4, s.sur_mu, s.ns_phi[c]{a4});\n")
1115
+ src, n = pat.subn(sub, src)
1116
+ assert n >= 1, "noslip.surrogate_hooks: the surrogate's psi call"
1117
+ src = _rep(src, "#define NS_ROW_W(r, z, zp) ((z) ? 1.f : 0.f) // a contact row's weight in lam_tot's psi term: its zone\n",
1118
+ "#define NS_ROW_W(r, z, zp) (s.sur_mu > 0.f ? sur_weight(__ldcs(rec + OFF_NSJAR + (r)), s.sur_mu) "
1119
+ ": ((z) ? 1.f : 0.f)) // (cone_mu: the central-path weight)\n")
1120
+ src = _rep(src, "#define NS_ALL_ROWS 0\n", "#define NS_ALL_ROWS (s.sur_mu > 0.f)\n")
1121
+ src = _rep(src, "#define NS_TOT_SOLVE(L, w, lane) tri_solve_packed(L, w, lane)\n",
1122
+ "#define NS_TOT_SOLVE(L, w, lane) do { if (s.sur_mu > 0.f) { __syncwarp(); adj_sur_hessian(s, lane); "
1123
+ "chol_solve_compact(L, L, w, lane); } else tri_solve_packed(L, w, lane); } while (0)\n")
1124
+ return src