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,1944 @@
1
+ """More than 64 dofs in the forest engine (capability H4: at most 128; the dense factor: a dense correctness
2
+ baseline, at most 64 bodies)."""
3
+ import re
4
+
5
+ NOTE = " // (nv128: NV > 64)"
6
+
7
+
8
+ def needed(m):
9
+ return m.nv > 64
10
+
11
+
12
+ DEVICE = r"""
13
+ #define NDL ((NV + 31) / 32) // (nv128: NV > 64) dofs per lane: lane l holds the dofs l, l + 32, ..
14
+ // (nv128: NV > 64) chol_solve_dense: CHOL_SOLVE's contract (A, L packed lower triangles TRI(i, j) in shared memory, L
15
+ // may alias A; b, a shared NV vector, solved in place; L keeps the true diagonal) for any NV. A left-looking (Crout)
16
+ // factorization in place in L: column k's pivot on every lane from row k (broadcast loads), lane l the entries of rows
17
+ // l, l + 32, .. below it from the finished columns (dot products over shared memory), two __syncwarp() per column;
18
+ // then the forward and backward solves with NDL entries per lane in registers (column k broadcast by __shfl_sync).
19
+ // Explicit roundings: k_substep, k_pre and k_post agree bitwise. The design's stage-1 baseline (~NV^3 / 192 FMAs per
20
+ // lane, NV serial steps): correct, not fast
21
+ #define DFMS(a, b, c) __fmaf_rn(-(a), (b), (c))
22
+ #define DMUL(a, b) __fmul_rn((a), (b))
23
+ __device__ __noinline__ void chol_solve_dense(const float* A, float* L, float* b, int lane) {
24
+ if (A != L) {
25
+ __syncwarp();
26
+ for (int e = lane; e < NTRI; e += 32) L[e] = A[e];
27
+ }
28
+ __syncwarp();
29
+ for (int k = 0; k < NV; k++) {
30
+ const float* Lk = L + TRI(k, 0);
31
+ float s = Lk[k];
32
+ for (int j = 0; j < k; j++) s = DFMS(Lk[j], Lk[j], s);
33
+ const float dkk = fmaxf(s, 1e-30f);
34
+ float inv;
35
+ asm("rsqrt.approx.ftz.f32 %0, %1;" : "=f"(inv) : "f"(dkk));
36
+ inv = DMUL(inv, DFMS(DMUL(DMUL(0.5f, dkk), inv), inv, 1.5f)); // one Newton step
37
+ for (int i = k + 1 + lane; i < NV; i += 32) {
38
+ float* Li = L + TRI(i, 0);
39
+ float e = Li[k];
40
+ for (int j = 0; j < k; j++) e = DFMS(Li[j], Lk[j], e);
41
+ Li[k] = DMUL(e, inv);
42
+ }
43
+ __syncwarp(); // (every lane has read L_kk)
44
+ if (lane == (k & 31)) L[TRI(k, k)] = DMUL(dkk, inv);
45
+ __syncwarp();
46
+ }
47
+ float y[NDL];
48
+ #pragma unroll
49
+ for (int t = 0; t < NDL; t++) {
50
+ const int r = lane + 32 * t;
51
+ y[t] = r < NV ? b[r] : 0.f;
52
+ }
53
+ for (int k = 0; k < NV; k++) { // forward: L y = b, column-wise
54
+ float v = y[0];
55
+ #pragma unroll
56
+ for (int t = 1; t < NDL; t++)
57
+ if ((k >> 5) == t) v = y[t];
58
+ const float yk = __fdiv_rn(__shfl_sync(0xffffffffu, v, k & 31), L[TRI(k, k)]);
59
+ #pragma unroll
60
+ for (int t = 0; t < NDL; t++) {
61
+ const int r = lane + 32 * t;
62
+ if (r == k) y[t] = yk;
63
+ else if (r > k && r < NV) y[t] = DFMS(L[TRI(r, k)], yk, y[t]);
64
+ }
65
+ }
66
+ for (int k = NV - 1; k >= 0; k--) { // backward: L' x = y (row k of L, contiguous)
67
+ float v = y[0];
68
+ #pragma unroll
69
+ for (int t = 1; t < NDL; t++)
70
+ if ((k >> 5) == t) v = y[t];
71
+ const float xk = __fdiv_rn(__shfl_sync(0xffffffffu, v, k & 31), L[TRI(k, k)]);
72
+ #pragma unroll
73
+ for (int t = 0; t < NDL; t++) {
74
+ const int r = lane + 32 * t;
75
+ if (r == k) y[t] = xk;
76
+ else if (r < k) y[t] = DFMS(L[TRI(k, r)], xk, y[t]);
77
+ }
78
+ }
79
+ __syncwarp();
80
+ #pragma unroll
81
+ for (int t = 0; t < NDL; t++) {
82
+ const int r = lane + 32 * t;
83
+ if (r < NV) b[r] = y[t];
84
+ }
85
+ __syncwarp();
86
+ }
87
+ #undef DFMS
88
+ #undef DMUL
89
+ """
90
+
91
+ DENSE_FN = "__device__ __noinline__ void chol_solve_dense(const float* A, float* L, float* b, int lane) {\n"
92
+
93
+
94
+ def dchol(nv):
95
+ """$DK_NV128_DCHOL at source generation (more than 64 dofs): the form of chol_solve_dense, the dense Newton
96
+ factor (and the dense CHOL_SOLVE / surrogate H_mu uses): blk (default: dense_blk, block columns of
97
+ $DK_NV128_DCHOL_W dofs, default 8 up to 72 dofs and 12 beyond) or crout (the dense factor's left-looking loop). Both do the
98
+ same operations in the same order: the factor and the solution are bitwise equal. Microbenchmark (V100, cycles per
99
+ factor + solve, W = 8 / 12 / 16): nv 65 42k / 41k / 48k, 77 46k / 45k / 43k, 89 57k / 53k / 51k, 101 71k / 67k /
100
+ 65k, 113 87k / 81k / 84k, 128 106k / 100k / 110k; in the engine (k_post, forward call) S1 107 / 97 ms (W 8 / 12),
101
+ S3 19.1 / 21.2 ms (W 8 / 16)."""
102
+ import os
103
+ raw = os.environ.get("DK_NV128_DCHOL", "") or "blk"
104
+ if raw not in ("blk", "crout"):
105
+ raise ValueError(f"DK_NV128_DCHOL={raw!r}: blk or crout")
106
+ w = int(os.environ.get("DK_NV128_DCHOL_W", "") or (8 if nv <= 72 else 12))
107
+ if not 1 <= w <= 32:
108
+ raise ValueError(f"DK_NV128_DCHOL_W={w}: 1 .. 32")
109
+ return raw, w
110
+
111
+
112
+ def dense_blk(nv, W):
113
+ """chol_solve_dense as a register-blocked factor (the register-blocked factor) with chol_solve_dense's contract and its operations in
114
+ the same order (bitwise the same L and x). Block columns of W dofs, left-looking: the rows j0 .. NV - 1 of block
115
+ column [j0, j0 + W) in registers (lane l: rows j0 + l + 32 t, a<t>_<c>: column j0 + c), first the update by the
116
+ finished columns 0 .. j0 - 1 (a loop over p: the lane's L[i][p], the broadcast L[j0 + c][p], one FMA per register,
117
+ p ascending as the Crout dot products), then right-looking inside the block with shuffles (the pivot from lane c,
118
+ the scaled column entry of row j0 + c' from lane c'), then the block stored. Every entry (i, k) gets
119
+ e = A_ik - sum_j L_ij L_kj with j ascending and the same FMA operands as the Crout form, the pivot formula is
120
+ chol_solve_dense's. The two triangular solves form y / L_kk as RN(1 / L_kk) refined by one residual step
121
+ (Markstein: the correctly rounded quotient, = __fdiv_rn barring over- / underflow), the reciprocals before the
122
+ chains, the pivots by 32-row segments (the pivot's register a compile-time index). Microbenchmark (V100, dense SPD,
123
+ 4096 worlds; cycles per factor + solve): nv 113 392k -> 81k (W = 12), nv 65 153k -> 42k (W = 8)."""
124
+ ndl = (nv + 31) // 32
125
+ F = "0xffffffffu"
126
+ o = ["// (nv128 stage 6) chol_solve_dense, register-blocked: see forest_engine.nv128.dense_blk",
127
+ "#define BFMS(a, b, c) __fmaf_rn(-(a), (b), (c))", "#define BMUL(a, b) __fmul_rn((a), (b))",
128
+ DENSE_FN.rstrip("\n"),
129
+ " if (A != L) {\n __syncwarp();\n for (int e = lane; e < NTRI; e += 32) L[e] = A[e];\n }",
130
+ " __syncwarp();"]
131
+ for J in range((nv + W - 1) // W):
132
+ j0, nj = W * J, min(W, nv - W * J)
133
+ NT = (nv - j0 + 31) // 32
134
+ o.append(f" {{ // block column {J}: columns {j0} .. {j0 + nj - 1}, rows {j0} .. NV - 1")
135
+ for t in range(NT):
136
+ o.append(f" const int i{t} = {j0 + 32 * t} + lane, t{t} = TRI(min(i{t}, NV - 1), 0);")
137
+ regs = [f"a{t}_{c} = {f'i{t} < NV' if t else f'lane >= {c}'} ? L[t{t} + {j0 + c}] : 0.f"
138
+ for t in range(NT) for c in range(nj)]
139
+ o.append(" float " + ", ".join(regs) + ";")
140
+ if j0:
141
+ o.append("#pragma unroll 2")
142
+ o.append(f" for (int p = 0; p < {j0}; p++) {{ // the finished columns")
143
+ o.append(" " + " ".join(f"const float x{t} = L[t{t} + p];" for t in range(NT)))
144
+ for c in range(nj):
145
+ o.append(f" {{ const float l = L[{(j0 + c) * (j0 + c + 1) // 2} + p]; "
146
+ + " ".join(f"a{t}_{c} = BFMS(x{t}, l, a{t}_{c});" for t in range(NT)) + " }")
147
+ o.append(" }")
148
+ for c in range(nj):
149
+ o.append(f" {{ const float dkk = fmaxf(__shfl_sync({F}, a0_{c}, {c}), 1e-30f); // pivot {j0 + c}")
150
+ o.append(" float inv;")
151
+ o.append(' asm("rsqrt.approx.ftz.f32 %0, %1;" : "=f"(inv) : "f"(dkk));')
152
+ o.append(" inv = BMUL(inv, BFMS(BMUL(BMUL(0.5f, dkk), inv), inv, 1.5f)); // one Newton step")
153
+ o.append(" " + " ".join(f"const float x{t} = BMUL(a{t}_{c}, inv);" for t in range(NT)))
154
+ o.append(f" a0_{c} = lane == {c} ? BMUL(dkk, inv) : x0;"
155
+ + "".join(f" a{t}_{c} = x{t};" for t in range(1, NT)))
156
+ for c2 in range(c + 1, nj):
157
+ o.append(f" {{ const float l = __shfl_sync({F}, x0, {c2}); "
158
+ + " ".join(f"a{t}_{c2} = BFMS(x{t}, l, a{t}_{c2});" for t in range(NT)) + " }")
159
+ o.append(" }")
160
+ for t in range(NT):
161
+ for c in range(nj):
162
+ o.append(f" if ({f'i{t} < NV' if t else f'lane >= {c} && i0 < NV'}) L[t{t} + {j0 + c}] = a{t}_{c};")
163
+ o.append(" __syncwarp();")
164
+ o.append(" }")
165
+ o += [f" float y[{ndl}], rc[{ndl}];", f" int rb[{ndl}]; // the lane's rows' starts TRI(r, 0) (clamped)",
166
+ "#pragma unroll", f" for (int t = 0; t < {ndl}; t++) {{",
167
+ " const int r = lane + 32 * t, rc_ = min(r, NV - 1);", " y[t] = r < NV ? b[r] : 0.f;",
168
+ " rb[t] = TRI(rc_, 0);", " rc[t] = __frcp_rn(L[rb[t] + rc_]);", " }"]
169
+ for s in range(ndl):
170
+ o.append(f" for (int k = {32 * s}; k < {min(32 * s + 32, nv)}; k++) {{ // forward: L y = b, pivots {32 * s} ..")
171
+ o.append(f" const float a = __shfl_sync({F}, y[{s}], k & 31), r = __shfl_sync({F}, rc[{s}], k & 31), "
172
+ "d = L[TRI(k, k)];")
173
+ o.append(" const float q = BMUL(a, r), yk = __fmaf_rn(r, __fmaf_rn(-d, q, a), q); // (= a / d)")
174
+ for t in range(s, ndl):
175
+ if t == s:
176
+ o.append(f" {{ const float u = BFMS(L[rb[{t}] + min(k, lane + {32 * t})], yk, y[{t}]);\n"
177
+ f" y[{t}] = lane + {32 * t} == k ? yk : (lane + {32 * t} > k && lane + {32 * t} < NV ? u : y[{t}]); }}")
178
+ else:
179
+ o.append(f" {{ const float u = BFMS(L[rb[{t}] + k], yk, y[{t}]);\n"
180
+ f" y[{t}] = lane + {32 * t} < NV ? u : y[{t}]; }}")
181
+ o.append(" }")
182
+ for s in reversed(range(ndl)):
183
+ o.append(f" for (int k = {min(32 * s + 31, nv - 1)}; k >= {32 * s}; k--) {{ // backward: L' x = y, pivots .. {32 * s}")
184
+ o.append(f" const float a = __shfl_sync({F}, y[{s}], k & 31), r = __shfl_sync({F}, rc[{s}], k & 31), "
185
+ "d = L[TRI(k, k)];")
186
+ o.append(" const float q = BMUL(a, r), xk = __fmaf_rn(r, __fmaf_rn(-d, q, a), q);")
187
+ o.append(" const int tk = TRI(k, 0);")
188
+ for t in range(s + 1):
189
+ if t == s:
190
+ o.append(f" {{ const float u = BFMS(L[tk + min(k, lane + {32 * t})], xk, y[{t}]);\n"
191
+ f" y[{t}] = lane + {32 * t} == k ? xk : (lane + {32 * t} < k ? u : y[{t}]); }}")
192
+ else:
193
+ o.append(f" y[{t}] = BFMS(L[tk + lane + {32 * t}], xk, y[{t}]);")
194
+ o.append(" }")
195
+ o += [" __syncwarp();", "#pragma unroll", f" for (int t = 0; t < {ndl}; t++) {{",
196
+ " const int r = lane + 32 * t;", " if (r < NV) b[r] = y[t];", " }", " __syncwarp();", "}",
197
+ "#undef BFMS", "#undef BMUL"]
198
+ return "\n".join(o) + "\n"
199
+
200
+
201
+ def _dense_swap(src, nv):
202
+ form, w = dchol(nv)
203
+ if form != "blk":
204
+ return src
205
+ if src.count(DENSE_FN) != 1:
206
+ raise RuntimeError("nv128: chol_solve_dense not found once")
207
+ i = src.index(DENSE_FN)
208
+ end = "\n#undef DFMS\n#undef DMUL\n"
209
+ j = src.index(end, i)
210
+ assert src[j - 1] == "}"
211
+ return (src[:i] + "#undef DFMS\n#undef DMUL\n" + dense_blk(nv, w) + "#define DFMS(a, b, c) __fmaf_rn(-(a), (b), (c))\n"
212
+ "#define DMUL(a, b) __fmul_rn((a), (b))" + src[j:])
213
+
214
+
215
+ COPY_DEV = r"""// (nv128 stage 6) L = M (NTRI entries; entry e by lane e mod 32, as the plain loop) with 8 loads in flight per lane:
216
+ // M is in Hand (global memory) in the split forward, and the loop's one load at a time made the copy 0.5M cycles per
217
+ // world-substep of S1 (nv 113)
218
+ __device__ __forceinline__ void nv128_copy(float* L, const float* M, int lane) {
219
+ for (int e0 = 0; e0 < NTRI; e0 += 256) {
220
+ float v[8];
221
+ #pragma unroll
222
+ for (int u = 0; u < 8; u++) v[u] = e0 + 32 * u + lane < NTRI ? M[e0 + 32 * u + lane] : 0.f;
223
+ #pragma unroll
224
+ for (int u = 0; u < 8; u++)
225
+ if (e0 + 32 * u + lane < NTRI) L[e0 + 32 * u + lane] = v[u];
226
+ }
227
+ }
228
+ """
229
+ COPY_SITES = (
230
+ (" for (int e = lane; e < NTRI; e += 32) s.L[e] = s.M[e]; // (nv128: L = M, entry e by lane e mod 32, unstaged)\n",
231
+ " nv128_copy(s.L, s.M, lane); // (nv128: L = M, entry e by lane e mod 32; stage 6: loads in flight)\n"),
232
+ (" for (int e = lane; e < NTRI; e += 32) s.L[e] = s.M[e];\n __syncwarp();\n",
233
+ " nv128_copy(s.L, s.M, lane); // (nv128 stage 6)\n __syncwarp();\n"),
234
+ (" for (int q = lane; q < NNZ_LH; q += 32) s.L.v[q] = s.M[nvc_tri[q]]; // (nv128 stage 5: L = M on the closure)\n",
235
+ " for (int q0 = 0; q0 < NNZ_LH; q0 += 256) { // (nv128 stage 5: L = M on the closure; stage 6: loads in flight)\n"
236
+ " float v_[8];\n#pragma unroll\n"
237
+ " for (int u = 0; u < 8; u++) v_[u] = q0 + 32 * u + lane < NNZ_LH ? s.M[nvc_tri[q0 + 32 * u + lane]] : 0.f;\n"
238
+ "#pragma unroll\n for (int u = 0; u < 8; u++)\n"
239
+ " if (q0 + 32 * u + lane < NNZ_LH) s.L.v[q0 + 32 * u + lane] = v_[u];\n }\n"),
240
+ )
241
+ NDL_LINE = "#define NDL ((NV + 31) / 32) // (nv128: NV > 64) dofs per lane: lane l holds the dofs l, l + 32, ..\n"
242
+
243
+
244
+ def _copy_swap(src):
245
+ if src.count(NDL_LINE) != 1:
246
+ raise RuntimeError("nv128: NDL's definition not found once")
247
+ src = src.replace(NDL_LINE, NDL_LINE + COPY_DEV)
248
+ for a, b in COPY_SITES:
249
+ src = src.replace(a, b)
250
+ return src
251
+
252
+
253
+ def tri_solve(ndl):
254
+ """tri_solve_packed with ndl entries per lane, written as the two-entry form (for its two entries the same text:
255
+ scalar registers y0 .., rows clamped to a valid one, selects, #pragma unroll 5), the entries 2, 3 likewise. (A form
256
+ with arrays y[NDL] matched it bitwise in a standalone test, but forced onto the nv 59 control scene it gave wrong
257
+ position gradients in 3 of 256 worlds inside k_adjoint; not understood.)"""
258
+ T = range(ndl)
259
+ rows = "\n".join(f" const int r{t} = min(lane + {32 * t}, NV - 1); // (clamped to a valid row)" if t else
260
+ " const int r0 = lane;" for t in T)
261
+ has = "\n".join(f" const bool has{t} = lane + {32 * t} < NV;" for t in T if t)
262
+ starts = " const int " + ", ".join(f"t{t} = TRI(r{t}, 0)" for t in T) + "; // the rows' starts"
263
+ init = " float " + ", ".join("y0 = b[r0]" if t == 0 else f"y{t} = has{t} ? b[r{t}] : 0.f" for t in T) + ";"
264
+ sel = " : ".join([f"k < {32 * (u + 1)} ? y{u}" for u in range(ndl - 1)] + [f"y{ndl - 1}"])
265
+
266
+ def step(var, cmp):
267
+ return "\n".join(f" y{t} = r{t} == k ? {var} : ({'' if t == 0 else f'has{t} && '}r{t} {cmp} k ? y{t} - l{t} * {var} : "
268
+ f"y{t});" for t in T)
269
+ lf = ", ".join(f"l{t} = L[t{t} + min(k, r{t})]" for t in T)
270
+ lb = ", ".join(f"l{t} = L[tk + min(r{t}, k)]" for t in T)
271
+ store = "\n".join(" b[r0] = y0;" if t == 0 else f" if (has{t}) b[r{t}] = y{t};" for t in T)
272
+ return f"""__device__ __noinline__ void tri_solve_packed(const float* L, float* b, int lane) {{
273
+ static_assert(NV <= {32 * ndl}, "{ndl} entries per lane (nv128)");
274
+ {rows}
275
+ {has}
276
+ {starts}
277
+ __syncwarp();
278
+ {init}
279
+ #pragma unroll 5
280
+ for (int k = 0; k < NV; k++) {{ // forward: L y = b
281
+ const float d = L[TRI(k, k)], {lf};
282
+ const float yk = div_fast(__shfl_sync(0xffffffffu, {sel}, k & 31), d, rcp_step(d));
283
+ {step("yk", ">")}
284
+ }}
285
+ #pragma unroll 5
286
+ for (int k = NV - 1; k >= 0; k--) {{ // backward: L' x = y
287
+ const int tk = TRI(k, 0);
288
+ const float d = L[tk + k], {lb};
289
+ const float xk = div_fast(__shfl_sync(0xffffffffu, {sel}, k & 31), d, rcp_step(d));
290
+ {step("xk", "<")}
291
+ }}
292
+ __syncwarp();
293
+ {store}
294
+ __syncwarp();
295
+ }}
296
+ #endif
297
+ """
298
+
299
+
300
+ TRI_START = ('__device__ __noinline__ void tri_solve_packed(const float* L, float* b, int lane) {\n'
301
+ ' static_assert(NV <= 64, "two entries per lane");\n')
302
+ TRI_END = " if (has1) b[r1] = y1;\n __syncwarp();\n}\n#endif\n"
303
+
304
+ SUPPORT_RE = re.compile(r"__device__ __forceinline__ unsigned long long support_mask\((unsigned(?: long long)? x)\) \{"
305
+ r"[^\n]*\n#if DOF_BODY_ROOT6\n.*?\n#endif\n\}\n", re.S)
306
+
307
+ FORWARD = (
308
+ ("#ifndef NEWTON_REUSE\n#define NEWTON_REUSE (NV > 32 && NV <= 35)\n#endif\n",
309
+ "#ifndef NEWTON_REUSE\n#define NEWTON_REUSE (NV > 32 && NV <= 35)\n#endif\n"
310
+ "struct DofMask { unsigned w[NDL]; }; // (nv128) dof bits: bit i of word w is dof 32 w + i\n", 1),
311
+ (" unsigned long long con_mask[MAXCON]; // the support as dof bits (bit i: dof i; con_dof[c][k] is the k-th set "
312
+ "bit)\n",
313
+ " DofMask con_mask[MAXCON]; // the support as dof bits (nv128: NDL words; con_dof[c][k] is the k-th set bit)\n", 1),
314
+ (" unsigned long long con_mask[MAXCON];\n", " DofMask con_mask[MAXCON];" + NOTE + "\n", 1),
315
+ (" const unsigned long long* con_mask;\n", " const DofMask* con_mask;" + NOTE + "\n", 1),
316
+ (" unsigned long long* con_mask;\n", " DofMask* con_mask;" + NOTE + "\n", 1),
317
+ (" float M[NTRI], L[NTRI]; // overlap share storage (unions), the read-only ones the loop seldom reads stay in Hand\n",
318
+ " const float* M; // (nv128: in Hand; SimN within the 48 KB of dynamic shared memory k_post gets without an opt-in)\n"
319
+ " float L[NTRI]; // overlap share storage (unions), the read-only ones the loop seldom reads stay in Hand\n", 1),
320
+ (' static_assert(NV <= 64 && MAXCON <= 255, "two dofs per lane; contact counts in 8 bits");\n',
321
+ ' static_assert(NV <= 128 && MAXCON <= 255, "NDL dofs per lane (nv128); contact counts in 8 bits");\n', 1),
322
+ (" float dw[2][3], dv[2][3], dO[2][3];\n int dbody[2];\n",
323
+ " float dw[NDL][3], dv[NDL][3], dO[NDL][3];" + NOTE + "\n int dbody[NDL];\n", 1),
324
+ (" for (int h = 0; h < 2; h++) {\n int i = lane + 32 * h;\n dbody[h] = ",
325
+ " for (int h = 0; h < NDL; h++) {" + NOTE + "\n int i = lane + 32 * h;\n dbody[h] = ", 1),
326
+ (" for (int h = 0; h < 2; h++) {\n int i = lane + 32 * h, bi = dbody[h];\n",
327
+ " for (int h = 0; h < NDL; h++) {" + NOTE + "\n int i = lane + 32 * h, bi = dbody[h];\n", 1),
328
+ (" float acc[2];\n#pragma unroll\n for (int t = 0; t < 2; t++) {\n const int i = lane + 32 * t;\n",
329
+ " float acc[NDL];" + NOTE + "\n#pragma unroll\n for (int t = 0; t < NDL; t++) {\n const int i = lane + 32 * t;\n",
330
+ 1),
331
+ (" unsigned glo = 0u, ghi = 0u;\n if (c0 + lane < ncon) {\n con_force(s, f, c0 + lane, g);\n"
332
+ " const unsigned long long m = s.con_mask[c0 + lane];\n glo = (unsigned)m; ghi = (unsigned)(m >> 32);\n"
333
+ " }\n",
334
+ " unsigned glo = 0u, gw[NDL] = {}; // (nv128: the support's words; glo = word 0)\n"
335
+ " if (c0 + lane < ncon) {\n con_force(s, f, c0 + lane, g);\n"
336
+ " const DofMask m = s.con_mask[c0 + lane];\n#pragma unroll\n for (int t = 0; t < NDL; t++) gw[t] = m.w[t];\n"
337
+ " glo = gw[0];\n }\n", 1),
338
+ (" if (NV > 32)\n for (unsigned hm = __ballot_sync(0xffffffffu, ghi != 0u); hm; hm &= hm - 1u) {\n"
339
+ " const int i = __ffs(hm) - 1;\n"
340
+ " const unsigned lo = __shfl_sync(0xffffffffu, glo, i), hi = __shfl_sync(0xffffffffu, ghi, i);\n",
341
+ "#pragma unroll\n for (int t = 1; t < NDL; t++) // (nv128: the dofs 32 t .. from word t, the words below it give "
342
+ "the offset)\n for (unsigned hm = __ballot_sync(0xffffffffu, gw[t] != 0u); hm; hm &= hm - 1u) {\n"
343
+ " const int i = __ffs(hm) - 1;\n int kb = 0;\n#pragma unroll\n"
344
+ " for (int u = 0; u < t; u++) kb += __popc(__shfl_sync(0xffffffffu, gw[u], i));\n"
345
+ " const unsigned hi = __shfl_sync(0xffffffffu, gw[t], i);\n", 1),
346
+ (" const int k = __popc(lo) + __popc(hi & below);\n acc[1] += ",
347
+ " const int k = kb + __popc(hi & below);\n acc[t] += ", 1),
348
+ (" float mv[(NTRI + 31) / 32]; // L = M: all loads first (entry e by lane e mod 32)\n#pragma unroll\n"
349
+ " for (int k = 0; k < (NTRI + 31) / 32; k++) if (lane + 32 * k < NTRI) mv[k] = s.M[lane + 32 * k];\n", "", 1),
350
+ ("#pragma unroll\n for (int k = 0; k < (NTRI + 31) / 32; k++) if (lane + 32 * k < NTRI) s.L[lane + 32 * k] = mv[k];\n",
351
+ " for (int e = lane; e < NTRI; e += 32) s.L[e] = s.M[e]; // (nv128: L = M, entry e by lane e mod 32, unstaged)\n",
352
+ 1),
353
+ (" const int ndof = uniform_int(s.nefc_dof, 8);\n",
354
+ " const int ndof = uniform_int(s.nefc_dof, 9); // (nv128: up to 2 NV dof rows)\n", 1),
355
+ ("#ifndef CHOL_INLINE\n", "#if NV <= 64 // (nv128: two rows per lane; NV > 64: chol_solve_dense)\n#ifndef CHOL_INLINE\n", 1),
356
+ ("\n// Broadcast variant (same contract", "#endif // (nv128)\n" + DEVICE + "\n// Broadcast variant (same contract", 1),
357
+ ("#elif CHOL_COMPACT\n#define CHOL_SOLVE(A, L, b, lane, cb) chol_solve_compact(A, L, b, lane)\n#else\n"
358
+ "#define CHOL_SOLVE(A, L, b, lane, cb) chol_solve_reg(A, L, b, lane)\n#endif\n",
359
+ "#else\n#define CHOL_SOLVE(A, L, b, lane, cb) chol_solve_dense(A, L, b, lane) // (nv128: NV > 64)\n#endif\n", 1),
360
+ (" unsigned hd = (unsigned)ncon | (unsigned)s.nefc << 8 | (unsigned)(s.nefc_dof - NFLOSS) << 18\n"
361
+ " | (unsigned)min(it, 255) << 24;\n",
362
+ " unsigned hd = (unsigned)ncon | (unsigned)s.nefc << 8 | (unsigned)min(it, 255) << 24; // (nv128: nlim in the "
363
+ "reserved word)\n", 1),
364
+ (" __stcs(rec + OFF_RESERVED, 0.f);\n",
365
+ " __stcs(rec + OFF_RESERVED, __uint_as_float((unsigned)(s.nefc_dof - NFLOSS))); // (nv128: nlim)\n", 1),
366
+ )
367
+
368
+ ADJOINT = (
369
+ (" int hdr; // the record's header: ncon | nefc << 8 | nlim << 18 | niter << 24\n",
370
+ " int hdr; // the record's header: ncon | nefc << 8 | niter << 24 (nv128: nlim 0)\n"
371
+ " int nlimw; // (nv128) the record's active limit rows (its reserved word)\n", 1),
372
+ (" s.hdr = (int)hd;\n",
373
+ " s.hdr = (int)hd;\n s.nlimw = (int)__float_as_uint(__ldcs(rec + OFF_RESERVED)); // (nv128)\n", 1),
374
+ )
375
+ NLIM_RE = re.compile(r"\(\(unsigned\)s\.hdr >> 18\) & 63u?")
376
+
377
+ SURROGATE = (
378
+ (" chol_solve_compact(s.L, s.L, s.lam, lane);\n", " chol_solve_dense(s.L, s.L, s.lam, lane);" + NOTE + "\n", 1),
379
+ (" float h[2] = {0.f, 0.f};\n for (int t = 0; t < 2; t++) {\n const int j = lane + 32 * t;\n",
380
+ " float h[NDL] = {};" + NOTE + "\n for (int t = 0; t < NDL; t++) {\n const int j = lane + 32 * t;\n", 1),
381
+ (" for (int t = 0; t < 2; t++) {\n const int j = lane + 32 * t;\n if (j <= i) s.L[TRI(i, j)] = h[t];\n",
382
+ " for (int t = 0; t < NDL; t++) {\n const int j = lane + 32 * t;\n if (j <= i) s.L[TRI(i, j)] = h[t];\n", 1),
383
+ )
384
+
385
+
386
+
387
+ HOST = (
388
+ (" for (int i = lane; i < NTRI; i += 32) s.M[i] = g.M[i];\n",
389
+ " if (lane == 0) s.M = g.M; // (nv128: M stays in Hand)\n", 1),
390
+ )
391
+
392
+
393
+ WPSM_SPLIT = (" size_t smem_pre = sizeof(SimP), size_t smem_post = sizeof(SimN)) {\n",
394
+ " size_t smem_pre = nv128_smem(0), size_t smem_post = nv128_smem(1)) {"
395
+ " // (nv128 stage 6)\n")
396
+ WPSM_DEV = r"""// (nv128 stage 6) k_pre's / k_post's dynamic shared memory: sizeof(SimP) / sizeof(SimN), or, with a cap of
397
+ // NV128_PRE_WPSM / NV128_POST_WPSM worlds per SM (> 0; nv128.wpsm), more, so that at most that many are resident
398
+ // (the SM's shared memory / cap - the 1 KB the runtime reserves per block; at most 48 KB: no opt-in)
399
+ #ifndef NV128_PRE_WPSM
400
+ #define NV128_PRE_WPSM 0
401
+ #endif
402
+ #ifndef NV128_POST_WPSM
403
+ #define NV128_POST_WPSM 0
404
+ #endif
405
+ // (nv128) a per-world state above the 48 KB launch default (SimN at about 120 dofs with 255 contacts) needs the
406
+ // kernels' opt-in to more dynamic shared memory (cudaFuncAttributeMaxDynamicSharedMemorySize; at most the device's
407
+ // per-block limit, e.g. 96 KB on V100); set once per process and device, before the first launch
408
+ static void nv128_optin(int k, size_t bytes) {
409
+ static bool done[2][64] = {};
410
+ int dev = 0;
411
+ cudaGetDevice(&dev);
412
+ if (dev < 0 || dev >= 64 || done[k][dev]) return;
413
+ done[k][dev] = true;
414
+ if (k) {
415
+ cudaFuncSetAttribute(k_post, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)bytes);
416
+ } else {
417
+ cudaFuncSetAttribute(k_pre, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)bytes);
418
+ #if CV_DEFER
419
+ cudaFuncSetAttribute(k_pre_a, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)bytes);
420
+ #endif
421
+ }
422
+ }
423
+ static size_t nv128_smem(int k) {
424
+ const size_t base = k ? sizeof(SimN) : sizeof(SimP);
425
+ const int cap = k ? NV128_POST_WPSM : NV128_PRE_WPSM;
426
+ if (base > 48 * 1024) nv128_optin(k, base); // (a failed opt-in leaves the launch's error to report)
427
+ if (cap <= 0) return base;
428
+ int dev = 0, sm = 0;
429
+ cudaGetDevice(&dev);
430
+ cudaDeviceGetAttribute(&sm, cudaDevAttrMaxSharedMemoryPerMultiprocessor, dev);
431
+ size_t s = (size_t)sm / (size_t)cap;
432
+ s = s > 1024 ? (s - 1024) & ~(size_t)127 : 0;
433
+ if (s > 48 * 1024) s = 48 * 1024;
434
+ return s > base ? s : base;
435
+ }
436
+ """
437
+
438
+
439
+ def wpsm():
440
+ """$DK_NV128_PRE_WPSM / $DK_NV128_POST_WPSM at source generation (more than 64 dofs): caps on the resident worlds per
441
+ SM of k_pre / k_post through their dynamic shared memory (0 / unset: none, the default)."""
442
+ import os
443
+ out = []
444
+ for k in ("PRE", "POST"):
445
+ v = int(os.environ.get(f"DK_NV128_{k}_WPSM", "") or 0)
446
+ if v < 0:
447
+ raise ValueError(f"DK_NV128_{k}_WPSM={v}: >= 0")
448
+ out.append(v)
449
+ return tuple(out)
450
+
451
+
452
+ def host(src, m):
453
+ """host.KERNEL (the split forward's k_pre / k_post) with the edits for more than 64 dofs (SimN's M as a pointer into
454
+ Hand; the launches' dynamic shared memory through nv128_smem, wpsm); unchanged for at most 64."""
455
+ if not needed(m):
456
+ return src
457
+ src = _apply(src, HOST + (WPSM_SPLIT + (1,),))
458
+ pre, post = wpsm()
459
+ dev = (f"#define NV128_PRE_WPSM {pre}\n#define NV128_POST_WPSM {post}\n" if pre or post else "") + WPSM_DEV
460
+ a = "static inline cudaError_t dk_forward_split("
461
+ if src.count(a) != 1:
462
+ raise RuntimeError("nv128: dk_forward_split not found once")
463
+ return src.replace(a, dev + a)
464
+
465
+
466
+ def _apply(src, hooks):
467
+ for a, b, n in hooks:
468
+ if src.count(a) != n:
469
+ raise RuntimeError(f"nv128 hook anchor found {src.count(a)} times, expected {n}: {a[:70]!r}")
470
+ src = src.replace(a, b)
471
+ return src
472
+
473
+
474
+ def apply(src, m):
475
+ """src (adjoint.cuda_source's text after every other edit, nb64's included) with the edits for more than 64
476
+ dofs; unchanged for at most 64."""
477
+ if not needed(m):
478
+ return src
479
+ assert m.nv <= 128, "nv128: at most 128 dofs (four per lane)"
480
+ if len(SUPPORT_RE.findall(src)) != 1:
481
+ raise RuntimeError("nv128: support_mask not found once")
482
+ src = SUPPORT_RE.sub(lambda mt: (
483
+ f"__device__ __forceinline__ DofMask support_mask({mt.group(1)}) {{{NOTE}\n"
484
+ " DofMask m = {};\n for (int i = 0; i < NV; i++)\n"
485
+ " if ((x >> c_dofbody[i]) & 1u) m.w[i >> 5] |= 1u << (i & 31);\n return m;\n}\n"), src)
486
+ src = _apply(src, FORWARD)
487
+ src = _dense_swap(src, m.nv)
488
+ a = " for (int t = 0; t < 2; t++)\n if (lane + 32 * t < NV) "
489
+ want = 2 if "eq_jtf(s, f, lane + 32 * t, acc[t])" in src else 1
490
+ if src.count(a) != want:
491
+ raise RuntimeError(f"nv128: rows_jtf's per-dof loops found {src.count(a)} times, expected {want}")
492
+ src = src.replace(a, " for (int t = 0; t < NDL; t++) // (nv128)\n if (lane + 32 * t < NV) ")
493
+ if "__global__ void k_adjoint(" in src:
494
+ if src.count(TRI_START) != 1:
495
+ raise RuntimeError("nv128: tri_solve_packed (two entries per lane) not found once")
496
+ i = src.index(TRI_START)
497
+ j = src.index(TRI_END, i) + len(TRI_END)
498
+ src = src[:i] + tri_solve((m.nv + 31) // 32) + src[j:]
499
+ src = _apply(src, ADJOINT)
500
+ n = len(NLIM_RE.findall(src))
501
+ if n < 2:
502
+ raise RuntimeError(f"nv128: the adjoint's reads of the header's nlim found {n} times, expected >= 2")
503
+ src = NLIM_RE.sub("s.nlimw", src)
504
+ if "adj_sur_hessian(" in src:
505
+ src = _apply(src, SURROGATE)
506
+ if re.search(r"\bunsigned long long con_mask\b|\bglo\b.*\bghi\b|acc\[2\]|mv\[k\]", src):
507
+ raise RuntimeError("nv128: a two-dofs-per-lane site left in the text")
508
+ if not sparse(m):
509
+ return _copy_swap(src)
510
+ st = storage(m)
511
+ if st["lh"] and "adj_sur_hessian(" in src:
512
+ raise ValueError("nv128: the contact surrogate rebuilds H from a dense L_H; this model's records hold L_H on the "
513
+ "closure of P_H: build it with DK_NV128_HCHOL=dense")
514
+ src = apply_sparse(src, m, st)
515
+ done = False
516
+ if hchol() != "dense" and "adj_sur_hessian(" not in src:
517
+ info = hpattern(m)
518
+ if hsparse(m, src, info):
519
+ src, done = apply_hsparse(src, m, info, st), True
520
+ assert done or not st["lh"], "nv128: L_H on the closure without the sparse Newton factor"
521
+ return _copy_swap(src)
522
+
523
+
524
+ def _tri(i, j):
525
+ return i * (i + 1) // 2 + j
526
+
527
+
528
+ def tree(par):
529
+ """The dof tree of a parent array (MuJoCo's dof_parentid: a parent has a smaller index): dict of anc (nearest
530
+ first), depth, height, desc (sorted), the leaves-first pivot order (height, then index) and the root-first order
531
+ (depth, then index)."""
532
+ nv = len(par)
533
+ anc = []
534
+ for i in range(nv):
535
+ a, j = [], int(par[i])
536
+ while j >= 0:
537
+ assert j < i, "nv128 tree: a dof's parent must come first"
538
+ a.append(j)
539
+ j = int(par[j])
540
+ anc.append(a)
541
+ children = [[] for _ in range(nv)]
542
+ for i in range(nv):
543
+ if par[i] >= 0:
544
+ children[int(par[i])].append(i)
545
+ height = [0] * nv
546
+ for i in reversed(range(nv)):
547
+ height[i] = 1 + max((height[c] for c in children[i]), default=-1)
548
+ depth = [len(a) for a in anc]
549
+ desc = [[] for _ in range(nv)]
550
+ for j in range(nv):
551
+ for i in anc[j]:
552
+ desc[i].append(j)
553
+ return dict(nv=nv, anc=anc, depth=depth, height=height, desc=desc,
554
+ leaves_first=sorted(range(nv), key=lambda k: (height[k], k)),
555
+ root_first=sorted(range(nv), key=lambda k: (depth[k], k)))
556
+
557
+
558
+ def tree_chol(par, name="chol_solve_tree"):
559
+ """chol_solve_tree(A, L, b, lane) for the dof tree par as straight-line code: A = R' R with R lower triangular on
560
+ the tree pattern (row i: the columns of i's ancestors and i), eliminated leaves first, so there is no fill (MuJoCo's
561
+ mj_factorM order, as the tree engine's DK_TREE_CHOL); b := A^-1 b in place. Contract as CHOL_SOLVE (A, L packed
562
+ lower triangles in shared or global memory, L may alias A; b a shared NV vector) except that L receives R, and only
563
+ on the pattern: entries off the pattern are left as they are (zero when L aliases A and A is on the pattern)."""
564
+ T = tree(par)
565
+ nv, anc, depth, desc = T["nv"], T["anc"], T["depth"], T["desc"]
566
+ ndl = (nv + 31) // 32
567
+ rows = lambda t: [r for r in range(32 * t, min(32 * t + 32, nv))]
568
+ D = [max(depth[r] for r in rows(t)) for t in range(ndl)]
569
+ base = [sum(D[u] + 1 for u in range(t)) for t in range(ndl)]
570
+ ntab = base[-1] + D[-1] + 1
571
+ off = [0] * (ntab * 32)
572
+ for t in range(ndl):
573
+ for r in rows(t):
574
+ ra = list(reversed(anc[r])) + [r]
575
+ for e, c in enumerate(ra):
576
+ off[(base[t] + e) * 32 + (r & 31)] = _tri(r, c)
577
+
578
+ def mask(rs, t):
579
+ return sum(1 << (r & 31) for r in rs if r >> 5 == t)
580
+
581
+ def has(t, e):
582
+ return mask([r for r in rows(t) if depth[r] >= e], t)
583
+
584
+ F = "0xffffffffu"
585
+ o = [f"// (nv128 stage 3) {name}: see forest_engine.nv128.tree_chol",
586
+ f"__device__ const unsigned short nvt_off[{ntab * 32}] = {{{', '.join(map(str, off))}}};",
587
+ f"__device__ __noinline__ void {name}(const float* A, float* L, float* b, int lane) {{",
588
+ " const unsigned bit = 1u << lane;",
589
+ " const unsigned short* off = nvt_off + lane;",
590
+ " __syncwarp();"]
591
+ for t in range(ndl):
592
+ regs = []
593
+ for e in range(D[t] + 1):
594
+ mk = has(t, e)
595
+ regs.append(f"a{t}_{e} = (0x{mk:08x}u & bit) ? A[off[{(base[t] + e) * 32}]] : 0.f" if mk else f"a{t}_{e} = 0.f")
596
+ o.append(" float " + ", ".join(regs) + ";")
597
+ o.append(f" float y{t} = lane + {32 * t} < NV ? b[lane + {32 * t}] : 0.f, v{t} = 0.f; // v: 1 / R_rr")
598
+ for k in T["leaves_first"]:
599
+ sk, sl, dk = k >> 5, k & 31, depth[k]
600
+ a = anc[k]
601
+ o.append(f" {{ // pivot {k}")
602
+ o.append(f" const float dkk = fmaxf(__shfl_sync({F}, a{sk}_{dk}, {sl}), 1e-30f);")
603
+ o.append(" float inv;")
604
+ o.append(' asm("rsqrt.approx.ftz.f32 %0, %1;" : "=f"(inv) : "f"(dkk));')
605
+ o.append(" inv = TMUL(inv, TFMS(TMUL(TMUL(0.5f, dkk), inv), inv, 1.5f));")
606
+ for e in range(dk):
607
+ o.append(f" const float r{e} = TMUL(__shfl_sync({F}, a{sk}_{e}, {sl}), inv);")
608
+ o.append(f" const float z = TMUL(__shfl_sync({F}, y{sk}, {sl}), inv);")
609
+ st = "".join(f" a{sk}_{e} = r{e};" for e in range(dk))
610
+ o.append(f" if (lane == {sl}) {{{st} a{sk}_{dk} = TMUL(dkk, inv); y{sk} = z; v{sk} = inv; }}")
611
+ for t in range(ndl):
612
+ at = [i for i in a if i >> 5 == t]
613
+ if not at:
614
+ continue
615
+ o.append(f" if (0x{mask(at, t):08x}u & bit) {{")
616
+ o.append(" float c = 0.f;" + "".join(f" if (lane == {i & 31}) c = r{depth[i]};" for i in at))
617
+ for e in range(min(dk, D[t] + 1)):
618
+ o.append(f" a{t}_{e} = TFMS(c, r{e}, a{t}_{e});")
619
+ o.append(f" y{t} = TFMS(c, z, y{t});")
620
+ o.append(" }")
621
+ o.append(" }")
622
+ for i in T["root_first"]:
623
+ si, li = i >> 5, i & 31
624
+ o.append(f" {{ const float x = __shfl_sync({F}, TMUL(y{si}, v{si}), {li}); // x_{i}")
625
+ o.append(f" if (lane == {li}) y{si} = x;")
626
+ for t in range(ndl):
627
+ mk = mask(desc[i], t)
628
+ if mk:
629
+ o.append(f" if (0x{mk:08x}u & bit) y{t} = TFMS(a{t}_{depth[i]}, x, y{t});")
630
+ o.append(" }")
631
+ o.append(" __syncwarp(); // (every lane has read A and b)")
632
+ for t in range(ndl):
633
+ o.append(f" if (lane + {32 * t} < NV) b[lane + {32 * t}] = y{t};")
634
+ for e in range(D[t] + 1):
635
+ mk = has(t, e)
636
+ if mk:
637
+ o.append(f" if (0x{mk:08x}u & bit) L[off[{(base[t] + e) * 32}]] = a{t}_{e};")
638
+ o.append(" __syncwarp();")
639
+ o.append("}")
640
+ return ("#define TFMS(a, b, c) __fmaf_rn(-(a), (b), (c))\n#define TMUL(a, b) __fmul_rn((a), (b))\n"
641
+ + "\n".join(o) + "\n#undef TFMS\n#undef TMUL\n")
642
+
643
+
644
+ def tree_solve(par, name="tree_solve_packed"):
645
+ """tree_solve_packed(L, b, lane): b := (R' R)^-1 b for a factor R of tree_chol in the packed triangle L (shared
646
+ memory; the tape's L_Q), straight-line: lane c holds b_c, b_{c + 32}, .. in registers; R' z = b leaves first (z_k
647
+ by one shuffle and a division, the ancestors' lanes subtract R[k][c] z_k from their own entry of row k), then
648
+ R x = z root first (the descendants' lanes subtract R[r][i] x_i). Divisions as tri_solve_packed (div_fast)."""
649
+ T = tree(par)
650
+ nv, anc, desc = T["nv"], T["anc"], T["desc"]
651
+ ndl = (nv + 31) // 32
652
+
653
+ def mask(rs, t):
654
+ return sum(1 << (r & 31) for r in rs if r >> 5 == t)
655
+
656
+ F = "0xffffffffu"
657
+ o = [f"// (nv128 stage 3) {name}: see forest_engine.nv128.tree_solve",
658
+ f"__device__ __noinline__ void {name}(const float* L, float* b, int lane) {{",
659
+ " const unsigned bit = 1u << lane;",
660
+ " __syncwarp();"]
661
+ for t in range(ndl):
662
+ o.append(f" float y{t} = lane + {32 * t} < NV ? b[lane + {32 * t}] : 0.f;")
663
+ for k in T["leaves_first"]:
664
+ sk, sl = k >> 5, k & 31
665
+ o.append(f" {{ const float d = L[{_tri(k, k)}];")
666
+ o.append(f" const float z = div_fast(__shfl_sync({F}, y{sk}, {sl}), d, rcp_step(d));")
667
+ o.append(f" if (lane == {sl}) y{sk} = z;")
668
+ for t in range(ndl):
669
+ mk = mask(anc[k], t)
670
+ if mk:
671
+ o.append(f" if (0x{mk:08x}u & bit) y{t} -= L[{_tri(k, 0)} + lane + {32 * t}] * z;")
672
+ o.append(" }")
673
+ for i in T["root_first"]:
674
+ si, li = i >> 5, i & 31
675
+ o.append(f" {{ const float d = L[{_tri(i, i)}];")
676
+ o.append(f" const float x = div_fast(__shfl_sync({F}, y{si}, {li}), d, rcp_step(d));")
677
+ o.append(f" if (lane == {li}) y{si} = x;")
678
+ for t in range(ndl):
679
+ mk = mask(desc[i], t)
680
+ if mk:
681
+ o.append(f" if (0x{mk:08x}u & bit) y{t} -= L[TRI(lane + {32 * t}, {i})] * x;")
682
+ o.append(" }")
683
+ o.append(" __syncwarp();")
684
+ for t in range(ndl):
685
+ o.append(f" if (lane + {32 * t} < NV) b[lane + {32 * t}] = y{t};")
686
+ o.append(" __syncwarp();")
687
+ o.append("}")
688
+ return "\n".join(o) + "\n"
689
+
690
+
691
+ def tree_ok(m):
692
+ """Whether M (and M + h kv) of model m stays on the tree pattern, so the tree factor's tree factor applies: no noslip
693
+ (its L_M and its adjoint's solves keep the dense form), and every fixed tendon that adds to M or to M + h kv (armature,
694
+ passive damping, tendon actuators' kv) runs along one root-to-leaf chain (forest_engine.tendon's outer products
695
+ c c' then stay on the pattern), and no dof has more than 32 ancestor dofs (tree_chol_loop: one lane each; e.g.
696
+ MyoChallenge's table tennis arm, 38). Otherwise the dense factor of the dense factor (CHOL_SOLVE) stays."""
697
+ from nablaengine.forest_engine import noslip, tendon
698
+ if noslip.enabled(m):
699
+ return False
700
+ if max(tree([int(p) for p in m.dof_parentid])["depth"], default=0) > 32:
701
+ return False
702
+ if m.ntendon and tendon.applies(m):
703
+ ts = set(tendon.armature(m)) | set(tendon.passive(m)) | {t for _, t in tendon.actuators(m)}
704
+ for t in ts:
705
+ d = [x for x, _ in tendon.support_list(m, t)]
706
+ if any(not tendon._ancestor(m, j, i) for a, i in enumerate(d) for j in d[a + 1:]):
707
+ return False
708
+ return True
709
+
710
+
711
+ def mchol():
712
+ """$DK_NV128_MCHOL at source generation (more than 64 dofs only): loop (default: tree_chol_loop), straight
713
+ (tree_chol: the same factor as straight-line code, other pivot order) or dense (the dense factor's chol_solve_dense,
714
+ L_Q dense). V100, 4096 worlds, one control step: S3 (nv 65) forward 48.0 / 52.0 / 49.0-52.0 ms, forward +
715
+ backward 105.8 / 109.3 / 105.4; S1 (nv 113) forward 283 / 284 / 344, forward + backward 455 / 455 / 518
716
+ (the tree factor): the straight-line code is the fastest alone
717
+ but its size (~100 KB of SASS per copy at nv 65) slows the rest of k_post."""
718
+ import os
719
+ raw = os.environ.get("DK_NV128_MCHOL", "") or "loop"
720
+ if raw not in ("straight", "loop", "dense"):
721
+ raise ValueError(f"DK_NV128_MCHOL={raw!r}: straight, loop or dense")
722
+ return raw
723
+
724
+
725
+ def sparse(m):
726
+ """the tree factor's tree-sparse factor of M and M + h kv (CHOL_M_SOLVE = chol_solve_tree, L_Q in tree form): more than
727
+ 64 dofs, tree_ok and $DK_NV128_MCHOL not dense."""
728
+ return needed(m) and tree_ok(m) and mchol() != "dense"
729
+
730
+
731
+
732
+ M_SOLVE = ("#if CHOL_TREES\n#define CHOL_M_SOLVE(A, L, b, lane, cb) chol_solve_trees(A, L, b, lane)\n#else\n"
733
+ "#define CHOL_M_SOLVE(A, L, b, lane, cb) CHOL_SOLVE(A, L, b, lane, cb)\n#endif\n")
734
+
735
+ TRI_MUL_RTR = r"""// (nv128 stage 3) out = R' (R x) for L_Q = R (-DDK_ADJ_DEBUG's |M a*|); tmp: NV scratch; all shared
736
+ __device__ void tri_mul_rtr(const float* L, const float* x, float* tmp, float* out, int lane) {
737
+ for (int i = lane; i < NV; i += 32) { // tmp = R x, row i
738
+ float acc = 0.f;
739
+ for (int j = 0; j <= i; j++) acc += L[TRI(i, j)] * x[j];
740
+ tmp[i] = acc;
741
+ }
742
+ __syncwarp();
743
+ for (int j = lane; j < NV; j += 32) { // out = R' tmp, column j
744
+ float acc = 0.f;
745
+ for (int i = j; i < NV; i++) acc += L[TRI(i, j)] * tmp[i];
746
+ out[j] = acc;
747
+ }
748
+ __syncwarp();
749
+ }
750
+ """
751
+
752
+
753
+ def apply_sparse(src, m, st=None):
754
+ """the tree factor's edits (sparse(m)): chol_solve_tree for CHOL_M_SOLVE (k_pre's smooth acceleration, k_post's
755
+ implicitfast M + h kv: the tape's L_Q becomes R, Q = R' R, entries off the tree pattern zero), the record's flag
756
+ FLAG_LQ_TREE, and the adjoint's A1 solve with L_Q by tree_solve_packed (DK_ADJ_DEBUG: tri_mul_rtr).
757
+ the pattern storage (st["lq"], storage): k_pre's factor of M into L on M's tree pattern (chol_solve_tree_m, SimP's L of
758
+ NNZ_LQ words), the record's L_Q gathered onto it (tape_put_idx), the adjoint's copy and solve on it (tree_solve_t);
759
+ with st["lh"] k_post's factor of M + h kv on the closure of P_H (chol_solve_tree_c; apply_hsparse)."""
760
+ from nablaengine.forest_engine.tape import FLAG_LQ_TREE
761
+ st = st or storage(m)
762
+ par = [int(p) for p in m.dof_parentid]
763
+ emit = tree_chol if mchol() == "straight" else tree_chol_loop
764
+ dev = emit(par)
765
+ if st["lq"]:
766
+ dev += tree_chol_loop(par, "chol_solve_tree_m", lidx=st["tl"]["idx"], pfx="nvm")
767
+ if st["lh"]:
768
+ dev += tree_chol_loop(par, "chol_solve_tree_c", aidx=st["cl"]["idx"], lidx=st["cl"]["idx"], pfx="nvc")
769
+ src = _apply(src, ((M_SOLVE, dev + "#define CHOL_M_SOLVE(A, L, b, lane, cb) chol_solve_tree(A, L, b, "
770
+ "lane) // (nv128 stage 3: M on its tree pattern)\n", 1),
771
+ (" | (nu < TAPE_SINGULAR_NU ? TAPE_SINGULAR : 0u);\n",
772
+ " | (nu < TAPE_SINGULAR_NU ? TAPE_SINGULAR : 0u)\n"
773
+ f" | {FLAG_LQ_TREE}u; // (nv128 stage 3: L_Q in tree form, Q = R' R)\n", 1)))
774
+ if "__global__ void k_adjoint(" in src:
775
+ from nablaengine.forest_engine.tape import FLAG_H_DENSE, FLAG_H_LOWRANK, FLAG_LH_SPARSE
776
+ src = _apply(src, ((" s.flags |= (int)__float_as_uint(__ldcs(rec + OFF_FLAGS));\n",
777
+ f" s.flags |= (int)(__float_as_uint(__ldcs(rec + OFF_FLAGS)) & ~{FLAG_LQ_TREE | FLAG_LH_SPARSE | FLAG_H_LOWRANK | FLAG_H_DENSE}u);"
778
+ " // (nv128: not the factor forms)\n", 1),))
779
+ anchor = "__device__ __noinline__ void adj_solves(Adj& s, const float* rec, int lane) {\n"
780
+ solve = tree_solve_t(par) + tri_mul_rtr_t(par) if st["lq"] else tree_solve(par) + TRI_MUL_RTR
781
+ src = _apply(src, ((anchor, solve + anchor, 1),
782
+ (" tri_solve_packed(s.L, s.y, lane);\n",
783
+ " tree_solve_packed(s.L, s.y, lane); // (nv128 stage 3: L_Q = R, Q = R' R)\n", 1),
784
+ (" tri_mul_llt(s.L, s.a, s.tmp, s.did, lane);\n",
785
+ " tri_mul_rtr(s.L, s.a, s.tmp, s.did, lane); // (nv128 stage 3: L_Q = R)\n", 1)))
786
+ if st["lq"]:
787
+ src = apply_lq(src, m, st)
788
+ return src
789
+
790
+
791
+ S5_LQ = (
792
+ (" struct { float L[NTRI]; alignas(16) float cbuf[CHOL_CB]; }; // CHOL_SOLVE's scratch\n",
793
+ " struct { float L[NNZ_LQ]; alignas(16) float cbuf[CHOL_CB]; }; // CHOL_SOLVE's scratch (nv128 stage 5: L of "
794
+ "M on its tree pattern)\n", 1),
795
+ (" CHOL_M_SOLVE(s.M, s.L, s.qacc0, lane, s.cbuf);\n",
796
+ " chol_solve_tree_m(s.M, LRAW(s.L), s.qacc0, lane); // (nv128 stage 5: R into L on M's tree pattern)\n", 1),
797
+ (" tape_put(rec + OFF_LQ, s.L, NTRI, REC_WORDS - OFF_LQ, lane);\n",
798
+ " tape_put_idx(rec + OFF_LQ, LRAW(s.L), nvq_src, NNZ_LQ, REC_WORDS - OFF_LQ, lane); // (nv128 stage 5: L_Q on M's "
799
+ "tree pattern)\n", 1),
800
+ )
801
+ S5_LQ_ADJ = (
802
+ (" float L[NTRI]; // a factor from the record: L_Q (A1), then L_H (A2)\n",
803
+ " float L[NNZ_ADJ]; // a factor from the record: L_Q (A1), then L_H (A2) (nv128 stage 5: as stored there)\n", 1),
804
+ (" for (int e = lane; e < NTRI; e += 32) s.L[e] = __ldcs(rec + OFF_LQ + e);\n",
805
+ " for (int e = lane; e < NNZ_LQ; e += 32) s.L[e] = __ldcs(rec + OFF_LQ + e); // (nv128 stage 5: tlayout)\n", 1),
806
+ )
807
+ S5_LH_LOAD = " for (int e = lane; e < NTRI; e += 32) s.L[e] = __ldcs(rec + OFF_LH + e);\n"
808
+
809
+
810
+ def apply_lq(src, m, st):
811
+ """the pattern storage's edits of every lq_compact build (apply_sparse): the definitions (s5_header), SimP's L, k_pre's factor of
812
+ M into tlayout, the record's L_Q gathered into tlayout, the adjoint's copies of L_Q and L_H as long as they are."""
813
+ if src.count("struct Sim {\n") != 1:
814
+ raise RuntimeError("nv128: struct Sim not found once")
815
+ src = src.replace("struct Sim {\n", s5_header(m, st) + "struct Sim {\n")
816
+ src = _apply(src, S5_LQ)
817
+ if "__global__ void k_adjoint(" in src:
818
+ src = _apply(src, S5_LQ_ADJ)
819
+ if src.count(S5_LH_LOAD) < 1:
820
+ raise RuntimeError("nv128: the adjoint's L_H load not found")
821
+ src = src.replace(S5_LH_LOAD, " for (int e = lane; e < NNZ_LH; e += 32) s.L[e] = __ldcs(rec + OFF_LH + e);"
822
+ " // (nv128 stage 5: as stored)\n")
823
+ return src
824
+
825
+
826
+ S5_LH = (
827
+ (" float L[NTRI]; // overlap share storage (unions), the read-only ones the loop seldom reads stay in Hand\n",
828
+ " HL L; // (nv128 stage 5: on the closure of P_H) overlap share storage (unions), the read-only ones the loop seldom "
829
+ "reads stay in Hand\n", 1),
830
+ (" float M[NTRI], L[NTRI]; // mass matrix and Cholesky scratch, packed lower triangles TRI(i, j)\n",
831
+ " float M[NTRI]; // mass matrix, packed lower triangle TRI(i, j)\n"
832
+ " HL L; // Cholesky scratch (nv128 stage 5: on the closure of P_H)\n", 1),
833
+ (" for (int e = lane; e < NTRI; e += 32) s.L[e] = s.M[e]; // (nv128: L = M, entry e by lane e mod 32, unstaged)\n",
834
+ " for (int q = lane; q < NNZ_LH; q += 32) s.L.v[q] = s.M[nvc_tri[q]]; // (nv128 stage 5: L = M on the closure)\n"
835
+ " __syncwarp(); // (the dof rows below add by the lane of the packed index)\n", 1),
836
+ (" for (int e = lane; e < NTRI; e += 32) s.L[e] = s.M[e];\n __syncwarp();\n",
837
+ " for (int q = lane; q < NNZ_LH; q += 32) s.L.v[q] = s.M[nvc_tri[q]]; // (nv128 stage 5: L = M on the closure)\n"
838
+ " __syncwarp();\n", 1),
839
+ (" CHOL_M_SOLVE(s.L, s.L, s.tmp, lane, s.cbuf);\n",
840
+ " chol_solve_tree_c(s.L.v, s.L.v, s.tmp, lane); // (nv128 stage 5: M + h kv on the closure of P_H)\n", 1),
841
+ (" tape_put(rec + OFF_LH, s.L, NTRI, OFF_LQ - OFF_LH, lane);\n",
842
+ " tape_put(rec + OFF_LH, s.L.v, NNZ_LH, OFF_LQ - OFF_LH, lane); // (nv128 stage 5: L_H on the closure of P_H)\n", 1),
843
+ )
844
+
845
+
846
+ def tree_chol_loop(par, name="chol_solve_tree", aidx=None, lidx=None, pfx="nvt"):
847
+ """chol_solve_tree as loops over the pivots (compact code: the straight-line form's ~5 instructions per factor
848
+ entry come to ~100 KB of SASS per copy at nv 65, which evicts the Newton loop's code from the instruction caches).
849
+ Same contract and factor as tree_chol, other order: pivots by decreasing index (a valid leaves-first order, MuJoCo's
850
+ mj_factorM order), one loop per register slot t (rows 32 t .. 32 t + 31; their ancestors are in slots <= t), so
851
+ the pivot row's slot is a compile-time constant. Rows in registers by depth (a<t>_<e>, e < the row's depth; the
852
+ diagonal in g<t>). Pivot k (lane k & 31): its row broadcast, unrolled to the slot's deepest row without branches
853
+ (registers past a row's depth hold 0, so r_e = 0 there), every lane forms r_e = A[k][e] inv; lane e keeps r_e (w)
854
+ and stores it to L (its column from nvt_pa); the lanes of k's ancestors (nvt_anc, per slot u <= t) take
855
+ c = r_{depth row} by one shuffle of w and update A[i][e] -= c r_e for every e of the slot's depth range (entries
856
+ past the row's own depth are scratch, never read), A[i][i] -= c c, y_i -= c z_k (the R' z = b solve). Then R x = z
857
+ root first from L (the descendants' lanes, nvt_desc). Explicit roundings; the pivot formula is chol_solve_dense's.
858
+ aidx, lidx (the pattern storage): the storage of A and of L as functions (i, j) -> index for a dof i and j = i or an ancestor
859
+ of i (None: the packed triangle TRI(i, j)); with either given, the same factor through index tables (prefix pfx):
860
+ _tree_chol_loop_map."""
861
+ if aidx is not None or lidx is not None:
862
+ return _tree_chol_loop_map(par, name, aidx or _tri, lidx or _tri, pfx)
863
+ T = tree(par)
864
+ nv, anc, depth, desc = T["nv"], T["anc"], T["depth"], T["desc"]
865
+ ndl = (nv + 31) // 32
866
+ rows = lambda t: [r for r in range(32 * t, min(32 * t + 32, nv))]
867
+ D = [max(depth[r] for r in rows(t)) for t in range(ndl)]
868
+ base = [sum(D[u] for u in range(t)) for t in range(ndl)]
869
+ ntab = max(base[-1] + D[-1], 1)
870
+ off = [0] * (ntab * 32)
871
+ for t in range(ndl):
872
+ for r in rows(t):
873
+ for e, c in enumerate(reversed(anc[r])):
874
+ off[(base[t] + e) * 32 + (r & 31)] = _tri(r, c)
875
+ dep = [depth[32 * t + l] if 32 * t + l < nv else -1 for t in range(ndl) for l in range(32)]
876
+ assert max(depth) <= 32, "nv128 tree_chol_loop: at most 32 ancestors (one lane each)"
877
+ pa = [_tri(k, list(reversed(anc[k]))[l]) if l < depth[k] else 0 for k in range(nv) for l in range(32)]
878
+ ancm = [sum(1 << (i & 31) for i in anc[k] if i >> 5 == u) for k in range(nv) for u in range(ndl)]
879
+ rf = T["root_first"]
880
+ dm = [sum(1 << (j & 31) for j in desc[i] if j >> 5 == t) for i in rf for t in range(ndl)]
881
+ lst = lambda v: ", ".join(map(str, v))
882
+ F = "0xffffffffu"
883
+ o = [f"// (nv128 stage 3) {name}: see forest_engine.nv128.tree_chol_loop",
884
+ f"__device__ const unsigned short nvt_off[{ntab * 32}] = {{{lst(off)}}};",
885
+ f"__device__ const signed char nvt_dep[{ndl * 32}] = {{{lst(dep)}}};",
886
+ f"__device__ const unsigned short nvt_pa[{nv * 32}] = {{{lst(pa)}}};",
887
+ f"__constant__ unsigned char nvt_dk[{nv}] = {{{lst(depth)}}};",
888
+ f"__constant__ unsigned nvt_anc[{nv * ndl}] = {{{lst(ancm)}}};",
889
+ f"__constant__ unsigned char nvt_rf[{nv}] = {{{lst(rf)}}};",
890
+ f"__constant__ unsigned nvt_desc[{nv * ndl}] = {{{lst(dm)}}};",
891
+ f"__device__ __noinline__ void {name}(const float* A, float* L, float* b, int lane) {{",
892
+ " const unsigned bit = 1u << lane;",
893
+ " const unsigned short* off = nvt_off + lane;",
894
+ " __syncwarp();"]
895
+ for t in range(ndl):
896
+ r = f"lane + {32 * t}"
897
+ o.append(f" const int d{t} = nvt_dep[{r}], o{t} = ({r}) * ({r} + 1) / 2; // the row's depth, TRI(row, 0)")
898
+ regs = [f"a{t}_{e} = d{t} > {e} ? A[off[{(base[t] + e) * 32}]] : 0.f" for e in range(D[t])]
899
+ o.append(" float " + ", ".join(regs + [f"g{t} = d{t} >= 0 ? A[o{t} + {r}] : 0.f"]) + ";")
900
+ o.append(f" float y{t} = d{t} >= 0 ? b[{r}] : 0.f;")
901
+ o.append(" __syncwarp(); // (A and b read: L may alias A)")
902
+ for t in reversed(range(ndl)):
903
+ o.append(f" for (int k = {min(32 * t + 31, nv - 1)}; k >= {32 * t}; k--) {{ // the pivots of slot {t}")
904
+ o.append(" const int sl = k & 31;")
905
+ o.append(f" const float dkk = fmaxf(__shfl_sync({F}, g{t}, sl), 1e-30f);")
906
+ o.append(" float inv;")
907
+ o.append(' asm("rsqrt.approx.ftz.f32 %0, %1;" : "=f"(inv) : "f"(dkk));')
908
+ o.append(" inv = TMUL(inv, TFMS(TMUL(TMUL(0.5f, dkk), inv), inv, 1.5f));")
909
+ o.append(f" const float z = TMUL(__shfl_sync({F}, y{t}, sl), inv);")
910
+ o.append(" float w = 0.f; // r_lane")
911
+ for e in range(D[t]):
912
+ o.append(f" const float r{e} = TMUL(__shfl_sync({F}, a{t}_{e}, sl), inv); // (0 from depth k on)")
913
+ o.append(f" if (lane == {e}) w = r{e};")
914
+ o.append(" if (lane < nvt_dk[k]) L[nvt_pa[k * 32 + lane]] = w;")
915
+ o.append(f" if (lane == sl) {{ L[k * (k + 1) / 2 + k] = g{t} = TMUL(dkk, inv); y{t} = z; }}")
916
+ for u in range(t + 1):
917
+ o.append(f" {{ const unsigned am = nvt_anc[k * {ndl} + {u}];")
918
+ o.append(f" if (am) {{ const float c = __shfl_sync({F}, w, d{u} & 31);")
919
+ o.append(" if (am & bit) {")
920
+ for e in range(min(D[u], D[t])):
921
+ o.append(f" a{u}_{e} = TFMS(c, r{e}, a{u}_{e});")
922
+ o.append(f" g{u} = TFMS(c, c, g{u}); y{u} = TFMS(c, z, y{u});")
923
+ o.append(" } } }")
924
+ o.append(" }")
925
+ o.append(" __syncwarp();")
926
+ o.append(" const float " + ", ".join(f"rq{t} = __frcp_rn(d{t} >= 0 ? g{t} : 1.f)" for t in range(ndl))
927
+ + "; // (stage 6: the reciprocals of the diagonal before the chain)")
928
+ o.append(" for (int q = 0; q < NV; q++) { // R x = z, root first")
929
+ o.append(" const int i = nvt_rf[q], li = i & 31, si = i >> 5;")
930
+ ysel = " : ".join([f"si == {t} ? y{t}" for t in range(ndl - 1)] + [f"y{ndl - 1}"])
931
+ csel = " : ".join([f"si == {t} ? rq{t}" for t in range(ndl - 1)] + [f"rq{ndl - 1}"])
932
+ o.append(f" const float a_ = __shfl_sync({F}, {ysel}, li), r_ = __shfl_sync({F}, {csel}, li);")
933
+ o.append(f" const float x = {_mk_div('a_', 'r_', 'L[i * (i + 1) / 2 + i]')};")
934
+ for t in range(ndl):
935
+ o.append(f" if (lane == li && si == {t}) y{t} = x;")
936
+ o.append(f" if (nvt_desc[q * {ndl} + {t}] & bit) y{t} = TFMS(L[o{t} + i], x, y{t});")
937
+ o.append(" }")
938
+ o.append(" __syncwarp();")
939
+ for t in range(ndl):
940
+ o.append(f" if (d{t} >= 0) b[lane + {32 * t}] = y{t};")
941
+ o.append(" __syncwarp();")
942
+ o.append("}")
943
+ return ("#define TFMS(a, b, c) __fmaf_rn(-(a), (b), (c))\n#define TMUL(a, b) __fmul_rn((a), (b))\n"
944
+ + "\n".join(o) + "\n#undef TFMS\n#undef TMUL\n")
945
+
946
+
947
+ def _mk_div(a, r, d):
948
+ return f"__fmaf_rn({r}, __fmaf_rn(-({d}), __fmul_rn({a}, {r}), {a}), __fmul_rn({a}, {r}))"
949
+
950
+
951
+ def _ptri(i, j):
952
+ return _tri(max(i, j), min(i, j))
953
+
954
+
955
+ def ktree(kpar):
956
+ """The tree of kernel rows kpar (the sparse Newton factor: a parent has a LARGER index than its children, rows leaves first): dict of
957
+ anc (nearest first), depth, desc and root_first (depth, then index)."""
958
+ nv = len(kpar)
959
+ anc = []
960
+ for i in range(nv):
961
+ a, j = [], int(kpar[i])
962
+ while j >= 0:
963
+ assert j > i, "nv128 ktree: a row's parent must come after it"
964
+ a.append(j)
965
+ j = int(kpar[j])
966
+ anc.append(a)
967
+ depth = [len(a) for a in anc]
968
+ desc = [[] for _ in range(nv)]
969
+ for j in range(nv):
970
+ for i in anc[j]:
971
+ desc[i].append(j)
972
+ return dict(nv=nv, anc=anc, depth=depth, desc=desc, root_first=sorted(range(nv), key=lambda k: (depth[k], k)))
973
+
974
+
975
+ def hpattern(m, extra=()):
976
+ """The static Hessian pattern of model m for the sparse Newton factor (forest_engine.sparse_pattern.Pattern with the model's
977
+ explicit contact pairs, the engine's pair table: tree(M), the constraint cliques, the world / chain / object pairs
978
+ and the cheap self-pair groups; the other self pairs are dynamic), its symbolic factor's elimination tree and the
979
+ kernel layout of chol_solve_hp. Returns a dict:"""
980
+ if not extra:
981
+ key = _fingerprint(m)
982
+ if key not in _HP_CACHE:
983
+ _HP_CACHE[key] = _hpattern(m, ())
984
+ return _HP_CACHE[key]
985
+ return _hpattern(m, extra)
986
+
987
+
988
+ _HP_CACHE = {}
989
+
990
+
991
+ def _fingerprint(m):
992
+ import hashlib
993
+ import numpy as np
994
+ h = hashlib.sha256()
995
+ for f in ("dof_parentid", "dof_bodyid", "body_parentid", "body_dofnum", "body_dofadr", "jnt_dofadr", "jnt_type",
996
+ "geom_bodyid", "site_bodyid", "pair_geom1", "pair_geom2", "eq_type", "eq_objtype", "eq_obj1id",
997
+ "eq_obj2id", "tendon_adr", "tendon_num", "wrap_type", "wrap_objid"):
998
+ a = np.ascontiguousarray(getattr(m, f, np.zeros(0)))
999
+ h.update(f.encode() + str(a.shape).encode() + a.tobytes())
1000
+ return h.hexdigest()
1001
+
1002
+
1003
+ def _hpattern(m, extra):
1004
+ from nablaengine.forest_engine import sparse_pattern as sp
1005
+ P = sp.Pattern(m, pairs=[(int(a), int(b)) for a, b in zip(m.pair_geom1, m.pair_geom2)])
1006
+ F = P.factor
1007
+ if extra:
1008
+ adj = list(P.adj)
1009
+ for k in extra:
1010
+ P._add(adj, P.pairs[k].support)
1011
+ F = sp.symbolic(F.n, adj, P.order)
1012
+ for p in P.pairs:
1013
+ p.in_pattern = F.is_clique(p.support)
1014
+ n = F.n
1015
+ dep = [0] * n
1016
+ for k in reversed(range(n)):
1017
+ dep[k] = dep[F.etree[k]] + 1 if F.etree[k] >= 0 else 0
1018
+ ndl = (n + 31) // 32
1019
+
1020
+ def slots(order):
1021
+ return [max(dep[order[i]] for i in range(32 * t, min(32 * t + 32, n))) for t in range(ndl)]
1022
+
1023
+ cands = [list(range(n)), sorted(range(n), key=lambda k: (-dep[k], k))]
1024
+ order = min(cands, key=lambda o: (sum(slots(o)), cands.index(o)))
1025
+ kidx = {p: i for i, p in enumerate(order)}
1026
+ kpar = [kidx[F.etree[p]] if F.etree[p] >= 0 else -1 for p in order]
1027
+ assert all(kpar[i] < 0 or kpar[i] > i for i in range(n)), "nv128 hpattern: kernel order not children first"
1028
+ return dict(perm=[int(F.perm[p]) for p in order], kpar=kpar, pdyn=[not p.in_pattern for p in P.pairs],
1029
+ nnz_ph=F.nnz, nnz_closure=sum(d + 1 for d in dep), depth=max(dep), slots=slots(order),
1030
+ dense=n * (n + 1) // 2, npair_dyn=sum(not p.in_pattern for p in P.pairs))
1031
+
1032
+
1033
+ HREG_BUDGET = 96
1034
+ HW_COLS = 12
1035
+
1036
+
1037
+ def hchol():
1038
+ """$DK_NV128_HCHOL at source generation (more than 64 dofs only): auto (default: the Newton Hessian factored on its
1039
+ static pattern P_H by chol_solve_hp when every contact pair of the model is on P_H, else dense), sparse (P_H with
1040
+ hp_lowrank's correction in the worlds with contacts off the pattern, the dense factor beyond HW_COLS columns) or
1041
+ dense (chol_solve_dense for every world). V100, S3 (929 of 1544 pairs off P_H; 36 % of world-substeps of random-
1042
+ control rollouts with such a contact in H): dense 48.4-51.8 ms forward / 105.5-107.0 forward + backward, sparse
1043
+ 54.1-56.9 / 115.1-115.4 (a per-world choice between two factor codes costs more than either alone: measured with
1044
+ forced forms in the same code); every world on P_H (s3noself: S3 without its off-pattern
1045
+ pairs) auto 40.5-41.2 / 94.5-95.5 against dense 45.4-48.4 / 102.5-103.0."""
1046
+ import os
1047
+ raw = os.environ.get("DK_NV128_HCHOL", "") or "auto"
1048
+ if raw not in ("auto", "sparse", "dense"):
1049
+ raise ValueError(f"DK_NV128_HCHOL={raw!r}: auto, sparse or dense")
1050
+ return raw
1051
+
1052
+
1053
+ def hsparse(m, src=None, info=None):
1054
+ """the sparse Newton factor's sparse Newton factor applies: the tree factor on (sparse(m)), $DK_NV128_HCHOL sparse, or auto and no contact
1055
+ pair off P_H, the pyramidal cone (the elliptic cone's Hessian blocks are not hp_lowrank's C), no contact surrogate
1056
+ in the text (its H_mu rebuilds H = L L' from a dense L_H), the elimination tree at most 64 deep and its rows within
1057
+ HREG_BUDGET registers (S1 / S2: P_H is 70-77 % of dense, the tree 72-81 deep: the dense factor stays)."""
1058
+ import mujoco
1059
+ if not sparse(m) or hchol() == "dense" or int(m.opt.cone) != int(mujoco.mjtCone.mjCONE_PYRAMIDAL):
1060
+ return False
1061
+ if src is not None and "adj_sur_hessian(" in src:
1062
+ return False
1063
+ info = info or hpattern(m)
1064
+ if hchol() == "auto" and info["npair_dyn"]:
1065
+ return False
1066
+ return info["depth"] <= 64 and sum(info["slots"]) <= HREG_BUDGET
1067
+
1068
+
1069
+ def perm_chol_loop(kpar, perm, name="chol_solve_hp", pfx="nvh", cl=False):
1070
+ """chol_solve_hp(A, L, b, lane): A = R' R on the dof tree kpar of kernel rows (leaves first: kpar[r] > r) whose dofs
1071
+ are perm[r], b := A^-1 b in place (A, L the packed triangles of the original dof order, L may alias A: entry
1072
+ (r, c) at TRI(max(perm r, perm c), min(..)); b in dof order). For P_H's elimination tree (hpattern): R on the
1073
+ tree's ancestor closure, no fill. As tree_chol_loop (the tree factor) with the slot order mirrored: lane l holds the rows
1074
+ l, l + 32, .. (slot t = row >> 5), each row's entries by depth in registers (a<t>_<e>: the ancestor at depth e,
1075
+ the diagonal in g<t>), one loop per slot over its pivots by increasing index (ancestors are in slots >= t), the
1076
+ entries of the slot's depth range unrolled without branches (entries past a row's depth are scratch, never read
1077
+ as R), the pivot's entries r_e kept by lane e (w; e >= 32: lane e - 32, w1) for the ancestors' c = r_{depth}. The
1078
+ pivot's lane keeps its finished row in its registers; R goes to L in one pass after the loop (through the table of
1079
+ the loads), R x = z (root first) computes its addresses. Entries of L outside the closure are left as they are
1080
+ (zero for a Hessian on P_H). Explicit roundings; the pivot formula is chol_solve_dense's. cl (the pattern storage): A and L
1081
+ are stored on the closure itself (clayout: kernel row r's entries by depth from <pfx>_cb[r], the diagonal last)
1082
+ instead of the packed triangle: the same factor, addresses c<t> + e."""
1083
+ T = ktree(kpar)
1084
+ nv, anc, depth, desc = T["nv"], T["anc"], T["depth"], T["desc"]
1085
+ ndl = (nv + 31) // 32
1086
+ assert max(depth) <= 64, "nv128 perm_chol_loop: at most 64 ancestors (two registers on 32 lanes)"
1087
+ rows = lambda t: [r for r in range(32 * t, min(32 * t + 32, nv))]
1088
+ D = [max(depth[r] for r in rows(t)) for t in range(ndl)]
1089
+ base = [sum(D[u] for u in range(t)) for t in range(ndl)]
1090
+ ntab = max(base[-1] + D[-1], 1)
1091
+ off = [0] * (ntab * 32)
1092
+ for t in range(ndl):
1093
+ for r in rows(t):
1094
+ for e, c in enumerate(reversed(anc[r])):
1095
+ off[(base[t] + e) * 32 + (r & 31)] = _ptri(perm[r], perm[c])
1096
+ lane_of = lambda t, l: 32 * t + l
1097
+ dep = [depth[lane_of(t, l)] if lane_of(t, l) < nv else -1 for t in range(ndl) for l in range(32)]
1098
+ pv = [perm[lane_of(t, l)] if lane_of(t, l) < nv else 0 for t in range(ndl) for l in range(32)]
1099
+ ancm = [sum(1 << (i & 31) for i in anc[k] if i >> 5 == u) for k in range(nv) for u in range(ndl)]
1100
+ rf = T["root_first"]
1101
+ dm = [sum(1 << (j & 31) for j in desc[i] if j >> 5 == t) for i in rf for t in range(ndl)]
1102
+ lst = lambda v: ", ".join(map(str, v))
1103
+ F = "0xffffffffu"
1104
+ cb = _cbase(depth)
1105
+ o = [f"// (nv128 stage 4) {name}: see forest_engine.nv128.perm_chol_loop"]
1106
+ if cl:
1107
+ o += [f"__device__ const unsigned short {pfx}_cb[{ndl * 32}] = "
1108
+ f"{{{lst([cb[lane_of(t, l)] if lane_of(t, l) < nv else 0 for t in range(ndl) for l in range(32)])}}};",
1109
+ f"__constant__ unsigned short {pfx}_cbk[{nv}] = {{{lst(cb[:nv])}}};",
1110
+ f"__constant__ unsigned char {pfx}_kd[{nv}] = {{{lst(depth)}}};"]
1111
+ else:
1112
+ o.append(f"__device__ const unsigned short {pfx}_off[{ntab * 32}] = {{{lst(off)}}};")
1113
+ o += [f"__device__ const signed char {pfx}_dep[{ndl * 32}] = {{{lst(dep)}}};",
1114
+ f"__device__ const unsigned char {pfx}_pv[{ndl * 32}] = {{{lst(pv)}}};",
1115
+ f"__constant__ unsigned {pfx}_anc[{nv * ndl}] = {{{lst(ancm)}}};",
1116
+ f"__constant__ unsigned char {pfx}_rf[{nv}] = {{{lst(rf)}}};",
1117
+ f"__constant__ unsigned char {pfx}_pk[{nv}] = {{{lst(perm)}}};",
1118
+ f"__constant__ unsigned {pfx}_desc[{nv * ndl}] = {{{lst(dm)}}};",
1119
+ f"__device__ __noinline__ void {name}(const float* A, float* L, float* b, int lane, bool back = true) {{",
1120
+ " const unsigned bit = 1u << lane;"]
1121
+ if not cl:
1122
+ o.append(f" const unsigned short* off = {pfx}_off + lane;")
1123
+ o.append(" __syncwarp();")
1124
+ for t in range(ndl):
1125
+ r = f"lane + {32 * t}"
1126
+ if cl:
1127
+ o.append(f" const int d{t} = {pfx}_dep[{r}], p{t} = {pfx}_pv[{r}], c{t} = {pfx}_cb[{r}];"
1128
+ " // depth, dof, the row's start on the closure")
1129
+ regs = [f"a{t}_{e} = d{t} > {e} ? A[c{t} + {e}] : 0.f" for e in range(D[t])]
1130
+ o.append(" float " + ", ".join(regs + [f"g{t} = d{t} >= 0 ? A[c{t} + d{t}] : 0.f"]) + ";")
1131
+ else:
1132
+ o.append(f" const int d{t} = {pfx}_dep[{r}], p{t} = {pfx}_pv[{r}], o{t} = p{t} * (p{t} + 1) / 2;"
1133
+ " // depth, dof, TRI(dof, 0)")
1134
+ regs = [f"a{t}_{e} = d{t} > {e} ? A[off[{(base[t] + e) * 32}]] : 0.f" for e in range(D[t])]
1135
+ o.append(" float " + ", ".join(regs + [f"g{t} = d{t} >= 0 ? A[o{t} + p{t}] : 0.f"]) + ";")
1136
+ o.append(f" float y{t} = d{t} >= 0 ? b[p{t}] : 0.f;")
1137
+ o.append(" __syncwarp(); // (A and b read: L may alias A)")
1138
+ for t in range(ndl):
1139
+ wide = D[t] > 32
1140
+ o.append(f" for (int k = {32 * t}; k <= {min(32 * t + 31, nv - 1)}; k++) {{ // the pivots of slot {t}")
1141
+ o.append(" const int sl = k & 31;")
1142
+ o.append(f" const float dkk = fmaxf(__shfl_sync({F}, g{t}, sl), 1e-30f);")
1143
+ o.append(" float inv;")
1144
+ o.append(' asm("rsqrt.approx.ftz.f32 %0, %1;" : "=f"(inv) : "f"(dkk));')
1145
+ o.append(" inv = TMUL(inv, TFMS(TMUL(TMUL(0.5f, dkk), inv), inv, 1.5f));")
1146
+ o.append(f" const float z = TMUL(__shfl_sync({F}, y{t}, sl), inv);")
1147
+ if D[t]:
1148
+ o.append(" float w = 0.f" + (", w1 = 0.f;" if wide else ";") + " // r_lane (, r_lane+32)")
1149
+ for e in range(D[t]):
1150
+ o.append(f" const float r{e} = TMUL(__shfl_sync({F}, a{t}_{e}, sl), inv); // (0 from depth k on)")
1151
+ o.append(f" if (lane == {e}) w = r{e};" if e < 32 else f" if (lane == {e - 32}) w1 = r{e};")
1152
+ keep = " ".join(f"a{t}_{e} = r{e};" for e in range(D[t]))
1153
+ o.append(f" if (lane == sl) {{ {keep} g{t} = TMUL(dkk, inv); y{t} = z; }} // (the finished row of R)")
1154
+ for u in range(t, ndl):
1155
+ if not D[t]:
1156
+ break
1157
+ o.append(f" {{ const unsigned am = {pfx}_anc[k * {ndl} + {u}];")
1158
+ if wide and D[u] > 32:
1159
+ o.append(f" if (am) {{ const float c0 = __shfl_sync({F}, w, d{u} & 31), "
1160
+ f"c1 = __shfl_sync({F}, w1, d{u} & 31), c = d{u} >= 32 ? c1 : c0;")
1161
+ else:
1162
+ o.append(f" if (am) {{ const float c = __shfl_sync({F}, w, d{u} & 31);")
1163
+ o.append(" if (am & bit) {")
1164
+ for e in range(min(D[u], D[t])):
1165
+ o.append(f" a{u}_{e} = TFMS(c, r{e}, a{u}_{e});")
1166
+ o.append(f" g{u} = TFMS(c, c, g{u}); y{u} = TFMS(c, z, y{u});")
1167
+ o.append(" } } }")
1168
+ o.append(" }")
1169
+ for t in range(ndl):
1170
+ o.append(f" if (d{t} >= 0) L[c{t} + d{t}] = g{t};" if cl else f" if (d{t} >= 0) L[o{t} + p{t}] = g{t};")
1171
+ for e in range(D[t]):
1172
+ o.append(f" if (d{t} > {e}) L[c{t} + {e}] = a{t}_{e};" if cl else
1173
+ f" if (d{t} > {e}) L[off[{(base[t] + e) * 32}]] = a{t}_{e};")
1174
+ o.append(" __syncwarp();")
1175
+ o.append(" const float " + ", ".join(f"rq{t} = __frcp_rn(d{t} >= 0 ? g{t} : 1.f)" for t in range(ndl))
1176
+ + "; // (stage 6: the reciprocals of the diagonal before the chain)")
1177
+ o.append(" if (back) // (false: z = R'^-1 b to b, for hp_lowrank)")
1178
+ o.append(" for (int q = 0; q < NV; q++) { // R x = z, root first")
1179
+ ysel = " : ".join([f"si == {t} ? y{t}" for t in range(ndl - 1)] + [f"y{ndl - 1}"])
1180
+ csel = " : ".join([f"si == {t} ? rq{t}" for t in range(ndl - 1)] + [f"rq{ndl - 1}"])
1181
+ if cl:
1182
+ o.append(f" const int i = {pfx}_rf[q], li = i & 31, si = i >> 5, ki = {pfx}_kd[i];")
1183
+ o.append(f" const float a_ = __shfl_sync({F}, {ysel}, li), r_ = __shfl_sync({F}, {csel}, li);")
1184
+ o.append(f" const float x = {_mk_div('a_', 'r_', f'L[{pfx}_cbk[i] + ki]')};")
1185
+ else:
1186
+ o.append(f" const int i = {pfx}_rf[q], li = i & 31, si = i >> 5, pi = {pfx}_pk[i], ti = pi * (pi + 1) / 2;")
1187
+ o.append(f" const float a_ = __shfl_sync({F}, {ysel}, li), r_ = __shfl_sync({F}, {csel}, li);")
1188
+ o.append(f" const float x = {_mk_div('a_', 'r_', 'L[ti + pi]')};")
1189
+ for t in range(ndl):
1190
+ o.append(f" if (lane == li && si == {t}) y{t} = x;")
1191
+ ent = f"L[c{t} + ki]" if cl else f"L[p{t} > pi ? o{t} + pi : ti + p{t}]"
1192
+ o.append(f" if ({pfx}_desc[q * {ndl} + {t}] & bit) y{t} = TFMS({ent}, x, y{t});")
1193
+ o.append(" }")
1194
+ o.append(" __syncwarp();")
1195
+ for t in range(ndl):
1196
+ o.append(f" if (d{t} >= 0) b[p{t}] = y{t};")
1197
+ o.append(" __syncwarp();")
1198
+ o.append("}")
1199
+ return ("#define TFMS(a, b, c) __fmaf_rn(-(a), (b), (c))\n#define TMUL(a, b) __fmul_rn((a), (b))\n"
1200
+ + "\n".join(o) + "\n#undef TFMS\n#undef TMUL\n")
1201
+
1202
+
1203
+ def perm_solve_loop(kpar, perm, name, div="div_fast(y_, d, rcp_step(d))", pfx=None, multi=False, cl=False):
1204
+ """name(L, b, lane): b := (R' R)^-1 b for a factor R of perm_chol_loop(kpar, perm) in the packed triangle L
1205
+ (shared memory; the tape's L_H), as loops (a straight-line form made the adjoint ~2 ms slower on S3): the vector in
1206
+ registers, lane l holding the kernel rows l, l + 32, .. (dofs perm[row]); R' z = b over the pivots by increasing
1207
+ index, one loop per slot (z_k from lane k & 31, the lanes of k's ancestors subtract R[k][their row] z_k), then
1208
+ R x = z root first (the descendants' lanes). Addresses computed (TRI of the two dofs), masks and dofs from constant
1209
+ tables. Also <pfx>_vsolve(L, y, lane): the same on a vector already in that register layout (y[NDL]: lane l's
1210
+ rows). div: the division (y_ / d; the adjoint's div_fast, the forward's __fdiv_rn). cl (the pattern storage): L stored on the
1211
+ closure (clayout) instead of the packed triangle (as perm_chol_loop's cl)."""
1212
+ T = ktree(kpar)
1213
+ nv, anc, desc = T["nv"], T["anc"], T["desc"]
1214
+ assert not (cl and multi), "nv128 perm_solve_loop: the closure storage has no low-rank form"
1215
+ cb = _cbase(T["depth"])
1216
+ ndl = (nv + 31) // 32
1217
+ pfx = pfx or name
1218
+ pv = [perm[32 * t + l] if 32 * t + l < nv else 0 for t in range(ndl) for l in range(32)]
1219
+ ancm = [sum(1 << (i & 31) for i in anc[k] if i >> 5 == u) for k in range(nv) for u in range(ndl)]
1220
+ rf = T["root_first"]
1221
+ dm = [sum(1 << (j & 31) for j in desc[i] if j >> 5 == t) for i in rf for t in range(ndl)]
1222
+ lst = lambda v: ", ".join(map(str, v))
1223
+ F = "0xffffffffu"
1224
+ o = [f"// (nv128 stage 4) {name}: see forest_engine.nv128.perm_solve_loop",
1225
+ f"__device__ const unsigned char {pfx}_pv[{ndl * 32}] = {{{lst(pv)}}};",
1226
+ f"__constant__ unsigned {pfx}_anc[{nv * ndl}] = {{{lst(ancm)}}};",
1227
+ f"__constant__ unsigned char {pfx}_rf[{nv}] = {{{lst(rf)}}};",
1228
+ f"__constant__ unsigned char {pfx}_pk[{nv}] = {{{lst(perm)}}};",
1229
+ f"__constant__ unsigned {pfx}_desc[{nv * ndl}] = {{{lst(dm)}}};"]
1230
+ if cl:
1231
+ o += [f"__device__ const unsigned short {pfx}_cb[{ndl * 32}] = "
1232
+ f"{{{lst([cb[32 * t + l] if 32 * t + l < nv else 0 for t in range(ndl) for l in range(32)])}}};",
1233
+ f"__device__ const unsigned char {pfx}_kdl[{ndl * 32}] = "
1234
+ f"{{{lst([T['depth'][32 * t + l] if 32 * t + l < nv else 0 for t in range(ndl) for l in range(32)])}}};",
1235
+ f"__constant__ unsigned short {pfx}_cbk[{nv}] = {{{lst(cb[:nv])}}};",
1236
+ f"__constant__ unsigned char {pfx}_kd[{nv}] = {{{lst(T['depth'])}}};"]
1237
+ o += [f"__device__ __forceinline__ void {pfx}_vsolve(const float* L, float (&y)[{ndl}], int lane) {{",
1238
+ " const unsigned bit = 1u << lane;"]
1239
+ for t in range(ndl):
1240
+ if cl:
1241
+ o.append(f" const int c{t} = {pfx}_cb[lane + {32 * t}], q{t} = {pfx}_kdl[lane + {32 * t}];"
1242
+ " // the row's start on the closure, its depth")
1243
+ else:
1244
+ o.append(f" const int p{t} = {pfx}_pv[lane + {32 * t}], o{t} = p{t} * (p{t} + 1) / 2; // the row's dof, TRI(dof, 0)")
1245
+ for t in range(ndl):
1246
+ o.append(f" for (int k = {32 * t}; k <= {min(32 * t + 31, nv - 1)}; k++) {{ // R' z = b: the pivots of slot {t}")
1247
+ if cl:
1248
+ o.append(f" const int ck = {pfx}_cbk[k];")
1249
+ o.append(f" const float d = L[ck + {pfx}_kd[k]], y_ = __shfl_sync({F}, y[{t}], k & 31);")
1250
+ else:
1251
+ o.append(f" const int pk = {pfx}_pk[k], tk = pk * (pk + 1) / 2;")
1252
+ o.append(f" const float d = L[tk + pk], y_ = __shfl_sync({F}, y[{t}], k & 31);")
1253
+ o.append(f" const float z = {div};")
1254
+ o.append(f" if (lane == (k & 31)) y[{t}] = z;")
1255
+ for u in range(t, ndl):
1256
+ ent = f"L[ck + q{u}]" if cl else f"L[pk > p{u} ? tk + p{u} : o{u} + pk]"
1257
+ o.append(f" if ({pfx}_anc[k * {ndl} + {u}] & bit) y[{u}] -= {ent} * z;")
1258
+ o.append(" }")
1259
+ o.append(" for (int q = 0; q < NV; q++) { // R x = z, root first")
1260
+ ysel = " : ".join([f"si == {t} ? y[{t}]" for t in range(ndl - 1)] + [f"y[{ndl - 1}]"])
1261
+ if cl:
1262
+ o.append(f" const int i = {pfx}_rf[q], li = i & 31, si = i >> 5, ki = {pfx}_kd[i];")
1263
+ o.append(f" const float d = L[{pfx}_cbk[i] + ki], y_ = __shfl_sync({F}, {ysel}, li);")
1264
+ else:
1265
+ o.append(f" const int i = {pfx}_rf[q], li = i & 31, si = i >> 5, pi = {pfx}_pk[i], ti = pi * (pi + 1) / 2;")
1266
+ o.append(f" const float d = L[ti + pi], y_ = __shfl_sync({F}, {ysel}, li);")
1267
+ o.append(f" const float x = {div};")
1268
+ for t in range(ndl):
1269
+ o.append(f" if (lane == li && si == {t}) y[{t}] = x;")
1270
+ ent = f"L[c{t} + ki]" if cl else f"L[p{t} > pi ? o{t} + pi : ti + p{t}]"
1271
+ o.append(f" if ({pfx}_desc[q * {ndl} + {t}] & bit) y[{t}] -= {ent} * x;")
1272
+ o.append(" }")
1273
+ o.append("}")
1274
+ if multi:
1275
+ o += _fsolve_back(nv, ndl, pfx, div, F, ysel)
1276
+ if name == "chol_resolve_hp":
1277
+ o += ["#if NV128_REUSE", f"__device__ __forceinline__ void {name}(const float* L, float* b, int lane) {{", "#else"]
1278
+ o.append(f"__device__ __noinline__ void {name}(const float* L, float* b, int lane) {{")
1279
+ if name == "chol_resolve_hp":
1280
+ o.append("#endif")
1281
+ o.append(f" float y[{ndl}];")
1282
+ o.append(" __syncwarp();")
1283
+ for t in range(ndl):
1284
+ o.append(f" y[{t}] = lane + {32 * t} < NV ? b[{pfx}_pv[lane + {32 * t}]] : 0.f;")
1285
+ o.append(f" {pfx}_vsolve(L, y, lane);")
1286
+ o.append(" __syncwarp();")
1287
+ for t in range(ndl):
1288
+ o.append(f" if (lane + {32 * t} < NV) b[{pfx}_pv[lane + {32 * t}]] = y[{t}];")
1289
+ o.append(" __syncwarp();")
1290
+ o.append("}")
1291
+ return "\n".join(o) + "\n"
1292
+
1293
+
1294
+ def _fsolve_back(nv, ndl, pfx, div, F, ysel):
1295
+ o = []
1296
+ o.append(f"__device__ __forceinline__ void {pfx}_fsolve_m(const float* L, float (&V)[HW_COLS][{ndl}], int nc, int lane) {{")
1297
+ o.append(" const unsigned bit = 1u << lane;")
1298
+ for t in range(ndl):
1299
+ o.append(f" const int p{t} = {pfx}_pv[lane + {32 * t}], o{t} = p{t} * (p{t} + 1) / 2;")
1300
+ for t in range(ndl):
1301
+ o.append(f" for (int k = {32 * t}; k <= {min(32 * t + 31, nv - 1)}; k++) {{ // the pivots of slot {t}")
1302
+ o.append(f" const int pk = {pfx}_pk[k], tk = pk * (pk + 1) / 2;")
1303
+ o.append(" const float inv = __frcp_rn(L[tk + pk]);")
1304
+ o.append(" float zz[HW_COLS];")
1305
+ o.append("#pragma unroll")
1306
+ o.append(" for (int a = 0; a < HW_COLS; a++) {")
1307
+ o.append(f" zz[a] = a < nc ? __shfl_sync({F}, V[a][{t}], k & 31) * inv : 0.f;")
1308
+ o.append(f" if (lane == (k & 31)) V[a][{t}] = zz[a];")
1309
+ o.append(" }")
1310
+ for u in range(t, ndl):
1311
+ o.append(f" if ({pfx}_anc[k * {ndl} + {u}] & bit) {{")
1312
+ o.append(f" const float l = L[pk > p{u} ? tk + p{u} : o{u} + pk];")
1313
+ o.append("#pragma unroll")
1314
+ o.append(f" for (int a = 0; a < HW_COLS; a++) if (a < nc) V[a][{u}] -= l * zz[a];")
1315
+ o.append(" }")
1316
+ o.append(" }")
1317
+ o.append("}")
1318
+ o.append(f"__device__ __noinline__ void {pfx}_back(const float* L, float* b, int lane) {{")
1319
+ o.append(" const unsigned bit = 1u << lane;")
1320
+ o.append(f" float y[{ndl}];")
1321
+ o.append(" __syncwarp();")
1322
+ for t in range(ndl):
1323
+ o.append(f" const int p{t} = {pfx}_pv[lane + {32 * t}], o{t} = p{t} * (p{t} + 1) / 2;")
1324
+ o.append(f" y[{t}] = lane + {32 * t} < NV ? b[p{t}] : 0.f;")
1325
+ o.append(" for (int q = 0; q < NV; q++) {")
1326
+ o.append(f" const int i = {pfx}_rf[q], li = i & 31, si = i >> 5, pi = {pfx}_pk[i], ti = pi * (pi + 1) / 2;")
1327
+ o.append(f" const float d = L[ti + pi], y_ = __shfl_sync({F}, {ysel}, li);")
1328
+ o.append(f" const float x = {div};")
1329
+ for t in range(ndl):
1330
+ o.append(f" if (lane == li && si == {t}) y[{t}] = x;")
1331
+ o.append(f" if ({pfx}_desc[q * {ndl} + {t}] & bit) y[{t}] -= L[p{t} > pi ? o{t} + pi : ti + p{t}] * x;")
1332
+ o.append(" }")
1333
+ o.append(" __syncwarp();")
1334
+ for t in range(ndl):
1335
+ o.append(f" if (lane + {32 * t} < NV) b[p{t}] = y[{t}];")
1336
+ o.append(" __syncwarp();")
1337
+ o.append("}")
1338
+ return o
1339
+
1340
+
1341
+ CHOL_RESOLVE_DENSE = r"""// (nv128 stage 4) chol_resolve_dense(L, b, lane): b := (L L')^-1 b with chol_solve_dense's factor in L (its two
1342
+ // triangular solves, the same text: NEWTON_REUSE's analog for the dense worlds)
1343
+ // NV128_REUSE: chol_resolve_dense and chol_resolve_hp inlined. k_post calls them from its SimN and its Hand::big path;
1344
+ // as calls, the pattern ptxas miscompiled in chol_resolve (docs/perf/chol_wide.md) could not be ruled out for every
1345
+ // target (forest_engine.chol_blk: chol_resolve_blk)
1346
+ #define DFMS(a, b, c) __fmaf_rn(-(a), (b), (c))
1347
+ #if NV128_REUSE
1348
+ __device__ __forceinline__ void chol_resolve_dense(const float* L, float* b, int lane) {
1349
+ #else
1350
+ __device__ __noinline__ void chol_resolve_dense(const float* L, float* b, int lane) {
1351
+ #endif
1352
+ __syncwarp();
1353
+ """ + DEVICE[DEVICE.index(" float y[NDL];\n"):DEVICE.index("#undef DFMS")] + "#undef DFMS\n"
1354
+
1355
+ WOODBURY = r"""
1356
+ // (nv128 stage 4) the Newton Hessian of a world with contacts of dynamic pairs (pairs whose support is not a clique of
1357
+ // P_H, nvh_pdyn): H = R' R + sum_c U_c C_c U_c', R' R = H_P assembled without them (hessian(.., hskip)) and factored by
1358
+ // chol_solve_hp, U_c = the contact's frame rows (normal, tangents[, spin]) as dof vectors, C_c its CD x CD block of
1359
+ // con_C (positive semidefinite). hp_lowrank (between chol_solve_hp's two triangular solves): H = R' (I + V C V') R,
1360
+ // V = R'^-1 U, so H^-1 g = R^-1 (w - V (I + C W)^-1 C V' w) with w = R'^-1 g, W = V' V (the Sherman-Morrison-Woodbury
1361
+ // identity; I + C W is nonsingular). At most HW_COLS columns (hp_count * CD); beyond, the dense factor of the full H.
1362
+ template <class S>
1363
+ __device__ __forceinline__ bool hp_dyn_on(const S& s, int c) { // a contact of a dynamic pair with a quadratic row
1364
+ const int pr = s.con_pair[c];
1365
+ if (pr >= NPAIR || !((nvh_pdyn[pr >> 5] >> (pr & 31)) & 1u)) return false;
1366
+ const int r0 = s.con_row[c], nr = s.con_nrow[c];
1367
+ bool on = false;
1368
+ for (int k = 0; k < nr; k++) on |= s.efc_jar[r0 + k] < 0.f && s.efc_D[r0 + k] != 0.f;
1369
+ return on;
1370
+ }
1371
+ template <class S>
1372
+ __device__ __forceinline__ int hp_count(const S& s, int ncon, int lane) { // (uniform)
1373
+ int n = 0;
1374
+ for (int c0 = 0; c0 < ncon; c0 += 32) n += __popc(__ballot_sync(0xffffffffu, c0 + lane < ncon && hp_dyn_on(s, c0 + lane)));
1375
+ return n;
1376
+ }
1377
+ template <class S>
1378
+ __device__ __forceinline__ void hp_ucol(const S& s, int c, int j, float (&u)[NDL], int lane) {
1379
+ // column j of contact c's frame rows in the vsolve layout (lane l: the dofs of kernel rows l, l + 32, ..)
1380
+ const DofMask mk = s.con_mask[c];
1381
+ #pragma unroll
1382
+ for (int t = 0; t < NDL; t++) {
1383
+ const int d = chol_resolve_hp_pv[lane + 32 * t];
1384
+ u[t] = 0.f;
1385
+ if (lane + 32 * t < NV && ((mk.w[d >> 5] >> (d & 31)) & 1u)) {
1386
+ int k = __popc(mk.w[d >> 5] & ((1u << (d & 31)) - 1u));
1387
+ #pragma unroll
1388
+ for (int w = 0; w < NDL; w++) if (w < (d >> 5)) k += __popc(mk.w[w]);
1389
+ u[t] = s.con_J[c][j][k];
1390
+ }
1391
+ }
1392
+ }
1393
+ template <class S>
1394
+ __device__ __noinline__ void hp_lowrank(S& s, int ncon, int lane) {
1395
+ // H = R' R + U C U' = R' (I + V C V') R with V = R'^-1 U: on entry s.p = w = R'^-1 g (chol_solve_hp without its back
1396
+ // solve); y = (I + V C V')^-1 w = w - V (I + C W)^-1 C V' w with W = V' V (Woodbury), to s.p; the caller's R x = y
1397
+ // finishes p = H^-1 g. One forward pass for all columns (fsolve_m), W symmetric by construction
1398
+ constexpr int NW = HW_COLS / CD; // contacts
1399
+ int cid[NW];
1400
+ int n = 0;
1401
+ for (int c0 = 0; c0 < ncon; c0 += 32)
1402
+ for (unsigned b = __ballot_sync(0xffffffffu, c0 + lane < ncon && hp_dyn_on(s, c0 + lane)); b; b &= b - 1u)
1403
+ if (n < NW) cid[n++] = c0 + __ffs(b) - 1;
1404
+ const int nc = n * CD;
1405
+ float V[HW_COLS][NDL], w[NDL];
1406
+ #pragma unroll
1407
+ for (int a = 0; a < HW_COLS; a++) {
1408
+ if (a < nc) hp_ucol(s, cid[a / CD], a % CD, V[a], lane);
1409
+ else {
1410
+ #pragma unroll
1411
+ for (int t = 0; t < NDL; t++) V[a][t] = 0.f;
1412
+ }
1413
+ }
1414
+ chol_resolve_hp_fsolve_m(s.L, V, nc, lane);
1415
+ __syncwarp();
1416
+ #pragma unroll
1417
+ for (int t = 0; t < NDL; t++) w[t] = lane + 32 * t < NV ? s.p[chol_resolve_hp_pv[lane + 32 * t]] : 0.f;
1418
+ // this lane's row r of (I + C W | C V' w) (lanes < nc; C = the row's contact block: [C0 C1 C3 (C5); C1 C2 0 (0);
1419
+ // C3 0 C4 (0); (C5 0 0 C6)]), accumulated as the entries of W and V' w arrive (warp sums)
1420
+ float cr[CD];
1421
+ {
1422
+ const int q = lane % CD;
1423
+ const float* C = s.con_C[nc ? cid[min(lane, nc - 1) / CD] : 0];
1424
+ cr[0] = q == 0 ? C[0] : q == 1 ? C[1] : q == 2 ? C[3] : C[CC - 2];
1425
+ cr[1] = q == 0 ? C[1] : q == 1 ? C[2] : 0.f;
1426
+ cr[2] = q == 0 ? C[3] : q == 2 ? C[4] : 0.f;
1427
+ #if HAS_CONDIM4
1428
+ cr[3] = q == 0 ? C[5] : q == 3 ? C[6] : 0.f;
1429
+ #endif
1430
+ }
1431
+ const int blk = lane / CD;
1432
+ float Ar[HW_COLS + 1];
1433
+ #pragma unroll
1434
+ for (int b = 0; b <= HW_COLS; b++) Ar[b] = b == lane ? 1.f : 0.f;
1435
+ #pragma unroll
1436
+ for (int a = 0; a < HW_COLS; a++) {
1437
+ if (a >= nc) break;
1438
+ float acc = 0.f;
1439
+ #pragma unroll
1440
+ for (int t = 0; t < NDL; t++) acc += V[a][t] * w[t];
1441
+ acc = warp_sum(acc);
1442
+ if (blk == a / CD) Ar[HW_COLS] += cr[a % CD] * acc; // (C V' w)_r
1443
+ #pragma unroll
1444
+ for (int b = 0; b <= a; b++) { // W_ab = W_ba
1445
+ float wab = 0.f;
1446
+ #pragma unroll
1447
+ for (int t = 0; t < NDL; t++) wab += V[a][t] * V[b][t];
1448
+ wab = warp_sum(wab);
1449
+ if (blk == a / CD) Ar[b] += cr[a % CD] * wab;
1450
+ if (b != a && blk == b / CD) Ar[a] += cr[b % CD] * wab;
1451
+ }
1452
+ }
1453
+ #pragma unroll
1454
+ for (int b = 0; b <= HW_COLS; b++) Ar[b] = lane < nc ? Ar[b] : 0.f;
1455
+ // Gaussian elimination with partial pivoting, row r on lane r
1456
+ #pragma unroll
1457
+ for (int k = 0; k < HW_COLS; k++) {
1458
+ if (k >= nc) break;
1459
+ float v = lane >= k && lane < nc ? fabsf(Ar[k]) : -1.f;
1460
+ int piv = lane;
1461
+ #pragma unroll
1462
+ for (int o = 16; o > 0; o >>= 1) { // argmax (the smaller lane on ties: the same on every lane)
1463
+ const float v2 = __shfl_xor_sync(0xffffffffu, v, o);
1464
+ const int p2 = __shfl_xor_sync(0xffffffffu, piv, o);
1465
+ if (v2 > v || (v2 == v && p2 < piv)) { v = v2; piv = p2; }
1466
+ }
1467
+ const int src = lane == k ? piv : lane == piv ? k : lane;
1468
+ #pragma unroll
1469
+ for (int j = k; j <= HW_COLS; j++) Ar[j] = __shfl_sync(0xffffffffu, Ar[j], src);
1470
+ const float pv = __shfl_sync(0xffffffffu, Ar[k], k); // (every lane: a shuffle inside the select hung the warp)
1471
+ const float f = lane > k && lane < nc ? Ar[k] / pv : 0.f;
1472
+ #pragma unroll
1473
+ for (int j = k; j <= HW_COLS; j++) Ar[j] -= f * __shfl_sync(0xffffffffu, Ar[j], k);
1474
+ }
1475
+ float x[HW_COLS];
1476
+ #pragma unroll
1477
+ for (int k = HW_COLS - 1; k >= 0; k--) {
1478
+ x[k] = 0.f;
1479
+ if (k >= nc) continue;
1480
+ float acc = __shfl_sync(0xffffffffu, Ar[HW_COLS], k);
1481
+ #pragma unroll
1482
+ for (int j = k + 1; j < HW_COLS; j++) acc -= __shfl_sync(0xffffffffu, Ar[j], k) * x[j];
1483
+ x[k] = acc / __shfl_sync(0xffffffffu, Ar[k], k);
1484
+ }
1485
+ #pragma unroll
1486
+ for (int t = 0; t < NDL; t++) {
1487
+ float v = w[t];
1488
+ #pragma unroll
1489
+ for (int a = 0; a < HW_COLS; a++) v -= V[a][t] * x[a];
1490
+ if (lane + 32 * t < NV) s.p[chol_resolve_hp_pv[lane + 32 * t]] = v;
1491
+ }
1492
+ __syncwarp();
1493
+ }
1494
+ // the per-world state of the Newton loop in one int (k_post sits at its register cap: no further live values there):
1495
+ // bits 0-1 the form of the last factor (0 P_H, 1 P_H + the low-rank correction, 2 dense), bit 2 a low-rank iteration
1496
+ // with columns happened, bit 3 a dense one (outside the tape's re-factorization), bit 4 the last factor has correction
1497
+ // columns (then the tape's final factor is re-assembled: the full H, dense). The form: dense for the tape's
1498
+ // re-factorization of a world with contacts of dynamic pairs (refact) and beyond HW_COLS correction columns
1499
+ template <class S>
1500
+ __device__ __noinline__ int hp_mode(const S& s, int ncon, bool refact, int hst, int lane) {
1501
+ const int nd = hp_count(s, ncon, lane);
1502
+ int md = nd == 0 ? 0 : (nd * CD <= HW_COLS && !refact && NV128_HFORCE != 1) ? 1 : 2;
1503
+ if (NV128_HFORCE == 2) md = 0; // (diagnosis: every world on P_H, H wrong where contacts are off it)
1504
+ if (NV128_HFORCE == 3) md = 2; // (diagnosis: every world dense)
1505
+ if (NV128_HFORCE == 4 && md == 0) md = 1; // (every world through hp_lowrank, no columns where none is needed)
1506
+ if (NV128_HFORCE == 5 && nd > 0 && !refact) md = 3; // (H_P's direction, the contacts off P_H left out: a
1507
+ // preconditioned step; the tape's factor stays the full H's)
1508
+ const bool cols = (md == 1 && nd > 0) || md == 3; // (this factor is not the full H's: the tape needs it)
1509
+ return (hst & 12) | md | (cols ? 4 | 16 : 0) | (md == 2 && !refact ? 8 : 0);
1510
+ }
1511
+ // the Newton direction p = -H^-1 grad in the form md (one call site in the loop, as CHOL_H_SOLVE)
1512
+ template <class S>
1513
+ __device__ __noinline__ void hp_newton_dir(S& s, int ncon, int md, int lane) {
1514
+ md = uniform_int(md, 2); // (a vote: the branches below are uniform; md 0 .. 3)
1515
+ for (int i = lane; i < NV; i += 32) s.p[i] = -s.grad[i];
1516
+ __syncwarp();
1517
+ if (md == 2) chol_solve_dense(s.L, s.L, s.p, lane);
1518
+ else if (md != 1) chol_solve_hp(s.L, s.L, s.p, lane); // (H (form 0) or H_P (3) = R' R on P_H's elimination tree)
1519
+ else { // H = R' R + U C U': R'^-1 g, the low-rank step, R^-1
1520
+ chol_solve_hp(s.L, s.L, s.p, lane, false);
1521
+ hp_lowrank(s, ncon, lane);
1522
+ chol_resolve_hp_back(s.L, s.p, lane);
1523
+ }
1524
+ }
1525
+ """
1526
+
1527
+ H_CALL = (" hessian(s, ncon, world, grp, lane);\n PROF(7);\n"
1528
+ " for (int i = lane; i < NV; i += 32) s.p[i] = -s.grad[i];\n __syncwarp();\n"
1529
+ " CHOL_H_SOLVE(s.L, s.L, s.p, lane, s.cbuf);\n")
1530
+ H_CALL_NEW = (" hst = hp_mode(s, ncon, refact, hst, lane); // (nv128 stage 4: the factor's form, hp_mode)\n"
1531
+ " hessian(s, ncon, world, grp, lane, (hst & 1) != 0); // (forms 1, 3: H_P)\n PROF(7);\n"
1532
+ " hp_newton_dir(s, ncon, hst & 3, lane);\n")
1533
+ H_REUSE = ("#if NEWTON_REUSE || NEWTON_REUSE_WIDE\n"
1534
+ " if (zsame && !refact) { // no row changed its zone in the last step: H and its factor in s.L are the same\n"
1535
+ " for (int i = lane; i < NV; i += 32) s.p[i] = -s.grad[i];\n __syncwarp();\n"
1536
+ " chol_resolve(s.L, s.p, lane, s.cbuf);\n } else\n#endif\n")
1537
+ H_REUSE_NEW = ("#if NV128_REUSE\n"
1538
+ " if (zsame && !refact && UNIFORM((hst & 3) != 1)) { // (nv128 stage 4) no row changed its zone: the same H, its\n"
1539
+ " for (int i = lane; i < NV; i += 32) s.p[i] = -s.grad[i]; // factor in s.L (not with the low-rank\n"
1540
+ " __syncwarp(); // correction: con_C is gone)\n"
1541
+ " if (UNIFORM((hst & 3) == 2)) chol_resolve_dense(s.L, s.p, lane);\n else chol_resolve_hp(s.L, s.p, lane);\n"
1542
+ " } else\n#endif\n")
1543
+ H_LOOP = " bool conv = false, zchanged = rec && iterations <= 0, refact = zchanged, zsame = false;\n"
1544
+ H_LOOP_NEW = H_LOOP + " int hst = 2; // (nv128 stage 4) the factor's form and the forms used (hp_mode)\n"
1545
+ H_REFACT = " refact = zchanged;\n"
1546
+ H_REFACT_NEW = (" refact = zchanged || UNIFORM((hst & 16) != 0); // (nv128 stage 4: L_H of the full H for the tape: the low-rank\n"
1547
+ " // correction's world is re-assembled and factored densely)\n")
1548
+ H_SIG = ("__device__ __forceinline__ void hessian(S& s, int ncon, const unsigned (&world)[CPL], const unsigned (&grp)[CPL],\n"
1549
+ " int lane) {\n")
1550
+ H_SIG_NEW = ("__device__ __forceinline__ void hessian(S& s, int ncon, const unsigned (&world)[CPL], const unsigned (&grp)[CPL],\n"
1551
+ " int lane, bool hskip = false) { // (nv128 stage 4: hskip, the\n"
1552
+ " // contacts of dynamic pairs left out: H_P for hp_lowrank)\n")
1553
+ H_ON = " on = s.con_C[c][0] != 0.f; // C_nn is the sum of the curvatures\n"
1554
+ H_ON_NEW = (" on = s.con_C[c][0] != 0.f && !(hskip && s.con_pair[c] < NPAIR\n"
1555
+ " && ((nvh_pdyn[s.con_pair[c] >> 5] >> (s.con_pair[c] & 31)) & 1u));\n")
1556
+
1557
+
1558
+ def hreuse():
1559
+ """$DK_NV128_REUSE at source generation (the sparse Newton factor builds): 1 re-uses the last Newton factor when no row changed its
1560
+ zone in the last step (NEWTON_REUSE's analog: chol_resolve_hp / chol_resolve_dense; not after the low-rank
1561
+ correction), 0 (default) refactors."""
1562
+ import os
1563
+ raw = os.environ.get("DK_NV128_REUSE", "") or "0"
1564
+ if raw not in ("0", "1"):
1565
+ raise ValueError(f"DK_NV128_REUSE={raw!r}: 0 or 1")
1566
+ return int(raw)
1567
+
1568
+
1569
+ def hw_cols():
1570
+ """hp_lowrank's column capacity: HW_COLS, or $DK_NV128_HWCOLS (a multiple of CD; diagnosis)."""
1571
+ import os
1572
+ return int(os.environ.get("DK_NV128_HWCOLS", "") or HW_COLS)
1573
+
1574
+
1575
+ HFORCE = {"": 0, "dense": 1, "sparse_all": 2, "dense_all": 3, "lowrank_all": 4, "hp_only": 5}
1576
+
1577
+
1578
+ def hforce():
1579
+ """$DK_NV128_HFORCE (timing diagnosis of DK_NV128_HCHOL=sparse builds only; the sparse Newton factor):
1580
+ dense (a world with a contact of a dynamic pair takes the dense factor instead of the low-rank correction),
1581
+ sparse_all (every world on P_H: H wrong where contacts are off it), dense_all (every world dense), lowrank_all
1582
+ (every world through hp_lowrank), hp_only (H_P's direction without the correction: inexact); unset: hp_mode's
1583
+ choice."""
1584
+ import os
1585
+ return HFORCE[os.environ.get("DK_NV128_HFORCE", "")]
1586
+
1587
+
1588
+ def pdyn_table(pdyn, npair):
1589
+ words = [sum(1 << (b & 31) for b in range(32 * w, min(32 * w + 32, npair)) if pdyn[b]) for w in range((npair + 31) // 32)]
1590
+ return (f"// (nv128 stage 4) the pairs whose support is not a clique of P_H (forest_engine.nv128.hpattern)\n"
1591
+ f"__constant__ unsigned nvh_pdyn[{max(len(words), 1)}] = {{{', '.join(map(str, words or [0]))}}};\n"
1592
+ "#ifndef NV128_REUSE // (nv128 stage 4) re-use the last Newton factor when no row changed its zone\n"
1593
+ f"#define NV128_REUSE {hreuse()}\n#endif\n"
1594
+ f"#define NV128_HFORCE {hforce()} // (diagnosis: 1 the dense factor instead of the low-rank correction)\n"
1595
+ f"#define HW_COLS {hw_cols()} // hp_lowrank's columns at most (nv128.hw_cols)\n")
1596
+
1597
+
1598
+ def apply_hsparse(src, m, info, st=None):
1599
+ """the sparse Newton factor's edits (hsparse(m)): the Newton Hessian factored by chol_solve_hp (perm_chol_loop on P_H's elimination
1600
+ tree); a world with contacts of dynamic pairs in H gets H_P (hessian's hskip) and hp_lowrank's low-rank correction
1601
+ (up to HW_COLS columns; beyond, chol_solve_dense of the full H); the tape's final factor is on P_H or (such a world)
1602
+ dense, its form in the record (tape.FLAG_LH_SPARSE), the forms the iterations used in FLAG_H_LOWRANK / FLAG_H_DENSE;
1603
+ the adjoint's lam solve by the record's form (hp_solve_packed or tri_solve_packed); NV128_REUSE (NEWTON_REUSE's
1604
+ analog, $DK_NV128_REUSE). the pattern storage (st["lh"]: no dynamic pair): the factor stored on the closure (clayout) in
1605
+ SimN / Sim (struct HL), k_post's factor of M + h kv there too (chol_solve_tree_c), the record's L_H and the adjoint's
1606
+ copy as stored (S5_LH)."""
1607
+ from nablaengine.forest_engine.tape import FLAG_H_DENSE, FLAG_H_LOWRANK, FLAG_LH_SPARSE, FLAG_LQ_TREE
1608
+ st = st or storage(m)
1609
+ cl = st["lh"]
1610
+ v = ".v" if cl else ""
1611
+ perm, kpar = info["perm"], info["kpar"]
1612
+ anchor = "#define CHOL_M_SOLVE(A, L, b, lane, cb) chol_solve_tree(A, L, b, lane)"
1613
+ if src.count(anchor) != 1:
1614
+ raise RuntimeError("nv128: CHOL_M_SOLVE's tree-factor definition not found once")
1615
+ if not info["npair_dyn"]:
1616
+ flag = f" | {FLAG_LQ_TREE}u; // (nv128 stage 3: L_Q in tree form, Q = R' R)\n"
1617
+ dev = (f"#ifndef NV128_REUSE // (nv128 stage 4) re-use the last Newton factor when no row changed its zone\n"
1618
+ f"#define NV128_REUSE {hreuse()}\n#endif\n" + perm_chol_loop(kpar, perm, cl=cl)
1619
+ + perm_solve_loop(kpar, perm, "chol_resolve_hp", "__fdiv_rn(y_, d)", cl=cl))
1620
+ reuse = ("#if NV128_REUSE\n"
1621
+ " if (zsame && !refact) { // (nv128 stage 4) no row changed its zone: the same H, its factor in s.L\n"
1622
+ " for (int i = lane; i < NV; i += 32) s.p[i] = -s.grad[i];\n __syncwarp();\n"
1623
+ f" chol_resolve_hp(s.L{v}, s.p, lane);\n }} else\n#endif\n")
1624
+ src = _apply(src, ((anchor, dev + anchor, 1), (H_REUSE, reuse, 1),
1625
+ (" CHOL_H_SOLVE(s.L, s.L, s.p, lane, s.cbuf);\n",
1626
+ f" chol_solve_hp(s.L{v}, s.L{v}, s.p, lane); // (nv128 stage 4: H = R' R on P_H's elimination tree)\n",
1627
+ 1),
1628
+ (flag, f" | {FLAG_LQ_TREE}u | {FLAG_LH_SPARSE}u; // (nv128 stages 3, 4: L_Q, L_H "
1629
+ "in tree form)\n", 1)))
1630
+ if "__global__ void k_adjoint(" in src:
1631
+ anchor = "__device__ __noinline__ void adj_solves(Adj& s, const float* rec, int lane) {\n"
1632
+ src = _apply(src, ((anchor, perm_solve_loop(kpar, perm, "hp_solve_packed", cl=cl) + anchor, 1),
1633
+ (" tri_solve_packed(s.L, s.lam, lane);\n}\n",
1634
+ " hp_solve_packed(s.L, s.lam, lane); // (nv128 stage 4: L_H = R, H = R' R)\n}\n", 1)))
1635
+ if cl:
1636
+ src = _apply(src, S5_LH)
1637
+ ten = "__device__ __forceinline__ void ten_outer(float* A, "
1638
+ if ten in src:
1639
+ src = _apply(src, ((ten, "template <class LA> // (nv128 stage 5: float* or HL&)\n"
1640
+ "__device__ __forceinline__ void ten_outer(LA&& A, ", 1),))
1641
+ return src
1642
+ dev = (pdyn_table(info["pdyn"], int(m.npair)) + perm_chol_loop(kpar, perm)
1643
+ + perm_solve_loop(kpar, perm, "chol_resolve_hp", "__fdiv_rn(y_, d)", multi=True) + CHOL_RESOLVE_DENSE
1644
+ + WOODBURY)
1645
+ hanchor = "// the Newton Hessian into s.L (see below); world, grp:"
1646
+ flag = f" | {FLAG_LQ_TREE}u; // (nv128 stage 3: L_Q in tree form, Q = R' R)\n"
1647
+ src = _apply(src, ((hanchor, dev + hanchor, 1), (H_SIG, H_SIG_NEW, 1), (H_ON, H_ON_NEW, 1),
1648
+ (H_CALL, H_CALL_NEW, 1),
1649
+ (H_REUSE, H_REUSE_NEW, 1), (H_LOOP, H_LOOP_NEW, 1), (H_REFACT, H_REFACT_NEW, 1),
1650
+ (flag, f" | {FLAG_LQ_TREE}u // (nv128 stage 3: L_Q in tree form, Q = R' R)\n"
1651
+ f" | ((hst & 3) == 2 ? 0u : {FLAG_LH_SPARSE}u) | ((hst & 4) ? {FLAG_H_LOWRANK}u : 0u)\n"
1652
+ f" | ((hst & 8) ? {FLAG_H_DENSE}u : 0u); // (nv128 stage 4: L_H's form, the forms used)\n",
1653
+ 1)))
1654
+ if "__global__ void k_adjoint(" in src:
1655
+ anchor = "__device__ __noinline__ void adj_solves(Adj& s, const float* rec, int lane) {\n"
1656
+ call = " tri_solve_packed(s.L, s.lam, lane);\n}\n"
1657
+ src = _apply(src, ((anchor, perm_solve_loop(kpar, perm, "hp_solve_packed") + anchor, 1),
1658
+ (call, f" if (__any_sync(0xffffffffu, (__float_as_uint(__ldcs(rec + OFF_FLAGS)) & {FLAG_LH_SPARSE}u) "
1659
+ "!= 0u)) // (nv128 stage 4: the record's form of L_H)\n"
1660
+ " hp_solve_packed(s.L, s.lam, lane);\n else\n tri_solve_packed(s.L, s.lam, lane);\n}\n",
1661
+ 1)))
1662
+ return src
1663
+
1664
+
1665
+ def _cbase(depth):
1666
+ out, k = [], 0
1667
+ for d in depth:
1668
+ out.append(k)
1669
+ k += d + 1
1670
+ return out + [k]
1671
+
1672
+
1673
+ def tlayout(par):
1674
+ """M's tree pattern stored row by row (the pattern storage; the tape's L_Q, k_pre's factor of M): dof i's row holds its
1675
+ ancestors root first, then the diagonal, from tbase[i]. Returns dict(nnz, tbase, depth, idx(i, j) for j = i or an
1676
+ ancestor of i, tri: the packed-triangle index TRI(i, j) of every stored entry in storage order)."""
1677
+ T = tree(par)
1678
+ depth, anc = T["depth"], T["anc"]
1679
+ tb = _cbase(depth)
1680
+ tri = [_tri(i, a) for i in range(T["nv"]) for a in list(reversed(anc[i])) + [i]]
1681
+ return dict(nnz=tb[-1], tbase=tb[:-1], depth=depth, idx=lambda i, j: tb[i] + depth[j], tri=tri)
1682
+
1683
+
1684
+ def clayout(info):
1685
+ """The closure of P_H's elimination tree stored row by row (the pattern storage; the Newton factor in k_post's / k_substep's
1686
+ shared memory, the adjoint's, the tape's L_H for models whose every pair is on P_H): kernel row r (dof perm[r],
1687
+ hpattern) holds its elimination-tree ancestors root first, then the diagonal, from cbase[r]. Returns dict(nnz,
1688
+ cbase, depth, idx(i, j) for two dofs one of which is the other's elimination-tree ancestor, tri: TRI of every
1689
+ stored entry in storage order, slot: per packed-triangle index the storage index, nnz (a spare slot that is
1690
+ never read) for the entries outside the closure)."""
1691
+ perm, kpar = info["perm"], info["kpar"]
1692
+ T = ktree(kpar)
1693
+ depth, anc = T["depth"], T["anc"]
1694
+ cb = _cbase(depth)
1695
+ kidx = {d: r for r, d in enumerate(perm)}
1696
+ ancs = [set(a) for a in anc]
1697
+
1698
+ def idx(i, j):
1699
+ ri, rj = kidx[i], kidx[j]
1700
+ if ri > rj:
1701
+ ri, rj = rj, ri
1702
+ assert ri == rj or rj in ancs[ri], f"nv128 clayout: dofs {i}, {j} not on the closure"
1703
+ return cb[ri] + depth[rj]
1704
+
1705
+ tri = [_ptri(perm[r], perm[a]) for r in range(T["nv"]) for a in list(reversed(anc[r])) + [r]]
1706
+ nv = len(perm)
1707
+ slot = [cb[-1]] * (nv * (nv + 1) // 2)
1708
+ for q, e in enumerate(tri):
1709
+ slot[e] = q
1710
+ return dict(nnz=cb[-1], cbase=cb[:-1], depth=depth, idx=idx, tri=tri, slot=slot)
1711
+
1712
+
1713
+ def lq_compact(m):
1714
+ """the pattern storage: L_Q (the record's, k_pre's factor of M, the adjoint's copy) stored on M's tree pattern (tlayout):
1715
+ the tree factor's loop factor (sparse(m), $DK_NV128_MCHOL loop). The straight-line form (diagnosis) keeps the triangle."""
1716
+ return sparse(m) and mchol() == "loop"
1717
+
1718
+
1719
+ def lh_compact(m):
1720
+ """the pattern storage: the Newton factor stored on the closure of P_H (clayout) in SimN / Sim / Adj and the record's L_H sized
1721
+ to it, for the builds where no world can leave P_H: the sparse Newton factor's P_H factor (hsparse) on a model whose every contact
1722
+ pair is on P_H (no dynamic pair: one factor code for every world, $DK_NV128_HCHOL auto or sparse). Builds with a
1723
+ dense fallback ($DK_NV128_HCHOL=sparse with dynamic pairs) or the dense factor keep the packed triangle: their
1724
+ records hold a world's dense L_H. (The contact surrogate's builds refuse such models: apply.)"""
1725
+ if not lq_compact(m) or hchol() == "dense":
1726
+ return False
1727
+ return hsparse(m) and not hpattern(m)["npair_dyn"]
1728
+
1729
+
1730
+ def storage(m):
1731
+ """The pattern storage of model m (more than 64 dofs): dict(lq, lh: the forms above, nnz_lq, nnz_lh: the record's
1732
+ L_Q / L_H words, ntri, tl / cl: tlayout / clayout or None)."""
1733
+ ntri = m.nv * (m.nv + 1) // 2
1734
+ lq, lh = lq_compact(m), lh_compact(m)
1735
+ tl = tlayout([int(p) for p in m.dof_parentid]) if lq else None
1736
+ cl = clayout(hpattern(m)) if lh else None
1737
+ return dict(lq=lq, lh=lh, ntri=ntri, nnz_lq=tl["nnz"] if lq else ntri, nnz_lh=cl["nnz"] if lh else ntri,
1738
+ tl=tl, cl=cl)
1739
+
1740
+
1741
+ def _tree_chol_loop_map(par, name, aidx, lidx, pfx):
1742
+ T = tree(par)
1743
+ nv, anc, depth, desc = T["nv"], T["anc"], T["depth"], T["desc"]
1744
+ ndl = (nv + 31) // 32
1745
+ rows = lambda t: [r for r in range(32 * t, min(32 * t + 32, nv))]
1746
+ D = [max(depth[r] for r in rows(t)) for t in range(ndl)]
1747
+ base = [sum(D[u] for u in range(t)) for t in range(ndl)]
1748
+ ntab = max(base[-1] + D[-1], 1)
1749
+ aoff, loff = [0] * (ntab * 32), [0] * (ntab * 32)
1750
+ for t in range(ndl):
1751
+ for r in rows(t):
1752
+ for e, c in enumerate(reversed(anc[r])):
1753
+ aoff[(base[t] + e) * 32 + (r & 31)] = aidx(r, c)
1754
+ loff[(base[t] + e) * 32 + (r & 31)] = lidx(r, c)
1755
+ same = aoff == loff
1756
+ assert max(depth) <= 32, "nv128 tree_chol_loop: at most 32 ancestors (one lane each)"
1757
+ dep = [depth[32 * t + l] if 32 * t + l < nv else -1 for t in range(ndl) for l in range(32)]
1758
+ ad = [aidx(32 * t + l, 32 * t + l) if 32 * t + l < nv else 0 for t in range(ndl) for l in range(32)]
1759
+ ld = [lidx(k, k) for k in range(nv)]
1760
+ ancm = [sum(1 << (i & 31) for i in anc[k] if i >> 5 == u) for k in range(nv) for u in range(ndl)]
1761
+ rf = T["root_first"]
1762
+ dm = [sum(1 << (j & 31) for j in desc[i] if j >> 5 == t) for i in rf for t in range(ndl)]
1763
+ lst = lambda v: ", ".join(map(str, v))
1764
+ F = "0xffffffffu"
1765
+ lo = f"{pfx}_aoff" if same else f"{pfx}_loff"
1766
+ o = [f"// (nv128 stage 5) {name}: forest_engine.nv128.tree_chol_loop with A and L stored on patterns",
1767
+ f"__device__ const unsigned short {pfx}_aoff[{ntab * 32}] = {{{lst(aoff)}}};"]
1768
+ if not same:
1769
+ o.append(f"__device__ const unsigned short {pfx}_loff[{ntab * 32}] = {{{lst(loff)}}};")
1770
+ o += [f"__device__ const signed char {pfx}_dep[{ndl * 32}] = {{{lst(dep)}}};",
1771
+ f"__device__ const unsigned short {pfx}_ad[{ndl * 32}] = {{{lst(ad)}}};",
1772
+ f"__constant__ unsigned short {pfx}_ld[{nv}] = {{{lst(ld)}}};",
1773
+ f"__constant__ unsigned char {pfx}_dk[{nv}] = {{{lst(depth)}}};",
1774
+ f"__constant__ unsigned {pfx}_anc[{nv * ndl}] = {{{lst(ancm)}}};",
1775
+ f"__constant__ unsigned char {pfx}_rf[{nv}] = {{{lst(rf)}}};",
1776
+ f"__constant__ unsigned {pfx}_desc[{nv * ndl}] = {{{lst(dm)}}};",
1777
+ f"__device__ __noinline__ void {name}(const float* A, float* L, float* b, int lane) {{",
1778
+ " const unsigned bit = 1u << lane;",
1779
+ f" const unsigned short* off = {pfx}_aoff + lane;",
1780
+ " __syncwarp();"]
1781
+ for t in range(ndl):
1782
+ r = f"lane + {32 * t}"
1783
+ o.append(f" const int d{t} = {pfx}_dep[{r}]; // the row's depth")
1784
+ regs = [f"a{t}_{e} = d{t} > {e} ? A[off[{(base[t] + e) * 32}]] : 0.f" for e in range(D[t])]
1785
+ o.append(" float " + ", ".join(regs + [f"g{t} = d{t} >= 0 ? A[{pfx}_ad[{r}]] : 0.f"]) + ";")
1786
+ o.append(f" float y{t} = d{t} >= 0 ? b[{r}] : 0.f;")
1787
+ o.append(" __syncwarp(); // (A and b read: L may alias A)")
1788
+ for t in reversed(range(ndl)):
1789
+ o.append(f" for (int k = {min(32 * t + 31, nv - 1)}; k >= {32 * t}; k--) {{ // the pivots of slot {t}")
1790
+ o.append(" const int sl = k & 31;")
1791
+ o.append(f" const float dkk = fmaxf(__shfl_sync({F}, g{t}, sl), 1e-30f);")
1792
+ o.append(" float inv;")
1793
+ o.append(' asm("rsqrt.approx.ftz.f32 %0, %1;" : "=f"(inv) : "f"(dkk));')
1794
+ o.append(" inv = TMUL(inv, TFMS(TMUL(TMUL(0.5f, dkk), inv), inv, 1.5f));")
1795
+ o.append(f" const float z = TMUL(__shfl_sync({F}, y{t}, sl), inv);")
1796
+ o.append(" float w = 0.f; // r_lane")
1797
+ for e in range(D[t]):
1798
+ o.append(f" const float r{e} = TMUL(__shfl_sync({F}, a{t}_{e}, sl), inv); // (0 from depth k on)")
1799
+ o.append(f" if (lane == {e}) w = r{e};")
1800
+ o.append(f" if (lane < {pfx}_dk[k]) L[{lo}[({base[t]} + lane) * 32 + sl]] = w;")
1801
+ o.append(f" if (lane == sl) {{ L[{pfx}_ld[k]] = g{t} = TMUL(dkk, inv); y{t} = z; }}")
1802
+ for u in range(t + 1):
1803
+ o.append(f" {{ const unsigned am = {pfx}_anc[k * {ndl} + {u}];")
1804
+ o.append(f" if (am) {{ const float c = __shfl_sync({F}, w, d{u} & 31);")
1805
+ o.append(" if (am & bit) {")
1806
+ for e in range(min(D[u], D[t])):
1807
+ o.append(f" a{u}_{e} = TFMS(c, r{e}, a{u}_{e});")
1808
+ o.append(f" g{u} = TFMS(c, c, g{u}); y{u} = TFMS(c, z, y{u});")
1809
+ o.append(" } } }")
1810
+ o.append(" }")
1811
+ o.append(" __syncwarp();")
1812
+ o.append(" const float " + ", ".join(f"rq{t} = __frcp_rn(d{t} >= 0 ? g{t} : 1.f)" for t in range(ndl))
1813
+ + "; // (stage 6: the reciprocals of the diagonal before the chain)")
1814
+ o.append(" for (int q = 0; q < NV; q++) { // R x = z, root first")
1815
+ o.append(f" const int i = {pfx}_rf[q], li = i & 31, si = i >> 5, di = {pfx}_dk[i];")
1816
+ ysel = " : ".join([f"si == {t} ? y{t}" for t in range(ndl - 1)] + [f"y{ndl - 1}"])
1817
+ csel = " : ".join([f"si == {t} ? rq{t}" for t in range(ndl - 1)] + [f"rq{ndl - 1}"])
1818
+ o.append(f" const float a_ = __shfl_sync({F}, {ysel}, li), r_ = __shfl_sync({F}, {csel}, li);")
1819
+ o.append(f" const float x = {_mk_div('a_', 'r_', f'L[{pfx}_ld[i]]')};")
1820
+ for t in range(ndl):
1821
+ o.append(f" if (lane == li && si == {t}) y{t} = x;")
1822
+ o.append(f" if ({pfx}_desc[q * {ndl} + {t}] & bit) y{t} = TFMS(L[{lo}[({base[t]} + di) * 32 + lane]], x, y{t});")
1823
+ o.append(" }")
1824
+ o.append(" __syncwarp();")
1825
+ for t in range(ndl):
1826
+ o.append(f" if (d{t} >= 0) b[lane + {32 * t}] = y{t};")
1827
+ o.append(" __syncwarp();")
1828
+ o.append("}")
1829
+ return ("#define TFMS(a, b, c) __fmaf_rn(-(a), (b), (c))\n#define TMUL(a, b) __fmul_rn((a), (b))\n"
1830
+ + "\n".join(o) + "\n#undef TFMS\n#undef TMUL\n")
1831
+
1832
+
1833
+ def tree_solve_t(par, name="tree_solve_packed"):
1834
+ """tree_solve with L stored on M's tree pattern (the pattern storage: the record's L_Q in tlayout): the same straight-line
1835
+ solve, the same operations; the entry (k, the lane's row c) of R' z = b at tbase[k] + depth[c] (dl<t>: the lane's
1836
+ row's depth), the entry (the lane's row r, i) of R x = z at tbase[r] + depth[i] (tb<t>: the lane's row start)."""
1837
+ T = tree(par)
1838
+ nv, anc, desc, depth = T["nv"], T["anc"], T["desc"], T["depth"]
1839
+ L = tlayout(par)
1840
+ tb = L["tbase"]
1841
+ ndl = (nv + 31) // 32
1842
+
1843
+ def mask(rs, t):
1844
+ return sum(1 << (r & 31) for r in rs if r >> 5 == t)
1845
+
1846
+ lst = lambda v: ", ".join(map(str, v))
1847
+ F = "0xffffffffu"
1848
+ o = [f"// (nv128 stages 3, 5) {name}: see forest_engine.nv128.tree_solve_t",
1849
+ f"__device__ const unsigned short nvqa_tb[{ndl * 32}] = "
1850
+ f"{{{lst([tb[32 * t + l] if 32 * t + l < nv else 0 for t in range(ndl) for l in range(32)])}}};",
1851
+ f"__device__ const unsigned char nvqa_dl[{ndl * 32}] = "
1852
+ f"{{{lst([depth[32 * t + l] if 32 * t + l < nv else 0 for t in range(ndl) for l in range(32)])}}};",
1853
+ f"__device__ __noinline__ void {name}(const float* L, float* b, int lane) {{",
1854
+ " const unsigned bit = 1u << lane;",
1855
+ " __syncwarp();"]
1856
+ for t in range(ndl):
1857
+ o.append(f" float y{t} = lane + {32 * t} < NV ? b[lane + {32 * t}] : 0.f;")
1858
+ o.append(f" const int tb{t} = nvqa_tb[lane + {32 * t}], dl{t} = nvqa_dl[lane + {32 * t}];")
1859
+ for k in T["leaves_first"]:
1860
+ sk, sl = k >> 5, k & 31
1861
+ o.append(f" {{ const float d = L[{L['idx'](k, k)}];")
1862
+ o.append(f" const float z = div_fast(__shfl_sync({F}, y{sk}, {sl}), d, rcp_step(d));")
1863
+ o.append(f" if (lane == {sl}) y{sk} = z;")
1864
+ for t in range(ndl):
1865
+ mk = mask(anc[k], t)
1866
+ if mk:
1867
+ o.append(f" if (0x{mk:08x}u & bit) y{t} -= L[{tb[k]} + dl{t}] * z;")
1868
+ o.append(" }")
1869
+ for i in T["root_first"]:
1870
+ si, li = i >> 5, i & 31
1871
+ o.append(f" {{ const float d = L[{L['idx'](i, i)}];")
1872
+ o.append(f" const float x = div_fast(__shfl_sync({F}, y{si}, {li}), d, rcp_step(d));")
1873
+ o.append(f" if (lane == {li}) y{si} = x;")
1874
+ for t in range(ndl):
1875
+ mk = mask(desc[i], t)
1876
+ if mk:
1877
+ o.append(f" if (0x{mk:08x}u & bit) y{t} -= L[tb{t} + {depth[i]}] * x;")
1878
+ o.append(" }")
1879
+ o.append(" __syncwarp();")
1880
+ for t in range(ndl):
1881
+ o.append(f" if (lane + {32 * t} < NV) b[lane + {32 * t}] = y{t};")
1882
+ o.append(" __syncwarp();")
1883
+ o.append("}")
1884
+ return "\n".join(o) + "\n"
1885
+
1886
+
1887
+ def tri_mul_rtr_t(par):
1888
+ """tri_mul_rtr (-DDK_ADJ_DEBUG's |M a*|) for L_Q = R stored on M's tree pattern (tlayout): lane 0 alone."""
1889
+ L = tlayout(par)
1890
+ T = tree(par)
1891
+ rows = [i for i in range(T["nv"]) for _ in range(T["depth"][i] + 1)]
1892
+ cols = [a for i in range(T["nv"]) for a in list(reversed(T["anc"][i])) + [i]]
1893
+ lst = lambda v: ", ".join(map(str, v))
1894
+ return (f"// (nv128 stage 5) out = R' (R x) for L_Q = R on M's tree pattern (-DDK_ADJ_DEBUG's |M a*|); tmp: NV scratch\n"
1895
+ f"__device__ const unsigned char nvqd_r[{L['nnz']}] = {{{lst(rows)}}};\n"
1896
+ f"__device__ const unsigned char nvqd_c[{L['nnz']}] = {{{lst(cols)}}};\n"
1897
+ "__device__ void tri_mul_rtr(const float* L, const float* x, float* tmp, float* out, int lane) {\n"
1898
+ " __syncwarp();\n"
1899
+ " if (lane == 0) {\n"
1900
+ " for (int i = 0; i < NV; i++) tmp[i] = out[i] = 0.f;\n"
1901
+ f" for (int q = 0; q < {L['nnz']}; q++) tmp[nvqd_r[q]] += L[q] * x[nvqd_c[q]];\n"
1902
+ f" for (int q = 0; q < {L['nnz']}; q++) out[nvqd_c[q]] += L[q] * tmp[nvqd_r[q]];\n"
1903
+ " }\n"
1904
+ " __syncwarp();\n"
1905
+ "}\n")
1906
+
1907
+
1908
+ def s5_header(m, st):
1909
+ """The pattern-storage definitions ahead of struct Sim: the words of the stored factors (NNZ_LQ, NNZ_LH, NNZ_ADJ), the
1910
+ table of L_Q's entries in k_post's storage of L (nvq_src: the tape's L_Q is gathered from it), tape_put_idx, LRAW,
1911
+ and with the Newton factor on the closure struct HL (its storage, entries addressed by the packed triangle's
1912
+ index through nvs_slot, so the Hessian assembly's code stays the same)."""
1913
+ tl, cl = st["tl"], st["cl"]
1914
+ lidx = cl["idx"] if st["lh"] else _tri
1915
+ par = [int(p) for p in m.dof_parentid]
1916
+ T = tree(par)
1917
+ src = [lidx(i, a) for i in range(m.nv) for a in list(reversed(T["anc"][i])) + [i]]
1918
+ lst = lambda v: ", ".join(map(str, v))
1919
+ o = ["// (nv128 stage 5) the factors on their patterns (forest_engine.nv128.storage): words of L_Q (M's tree pattern),",
1920
+ "// of the Newton factor (the closure of P_H, or the packed triangle) and of the adjoint's copy of either",
1921
+ f"#define NNZ_LQ {st['nnz_lq']}",
1922
+ f"#define NNZ_LH {st['nnz_lh']}",
1923
+ f"#define NNZ_ADJ {max(st['nnz_lq'], st['nnz_lh'])}",
1924
+ "// the stored entries of L_Q in substep_post's storage of L, in the record's order (tlayout)",
1925
+ f"__device__ const unsigned short nvq_src[{tl['nnz']}] = {{{lst(src)}}};",
1926
+ "__device__ __noinline__ void tape_put_idx(float* dst, const float* src, const unsigned short* idx, int n, int end,",
1927
+ " int lane) {",
1928
+ " for (int i = lane; i < end; i += 32) __stcs(dst + i, i < n ? src[idx[i]] : 0.f);",
1929
+ "}",
1930
+ "__device__ __forceinline__ float* LRAW(float* p) { return p; }"]
1931
+ if st["lh"]:
1932
+ o += ["// (nv128 stage 5) the Newton factor's storage on the closure of P_H (clayout): v[nvs_slot[e]] is the entry of",
1933
+ "// packed-triangle index e (the assembly's addressing; entries outside the closure go to the spare slot",
1934
+ "// NNZ_LH, never read); the factor's own code (chol_solve_hp, chol_solve_tree_c) addresses v directly",
1935
+ f"__device__ const unsigned short nvs_slot[NTRI] = {{{lst(cl['slot'])}}};",
1936
+ "// the packed-triangle index of every stored entry (the copies L = M)",
1937
+ f"__device__ const unsigned short nvc_tri[NNZ_LH] = {{{lst(cl['tri'])}}};",
1938
+ "struct HL {",
1939
+ " float v[NNZ_LH + 1];",
1940
+ " __device__ __forceinline__ float& operator[](int e) { return v[nvs_slot[e]]; }",
1941
+ " __device__ __forceinline__ const float& operator[](int e) const { return v[nvs_slot[e]]; }",
1942
+ "};",
1943
+ "__device__ __forceinline__ float* LRAW(HL& h) { return h.v; }"]
1944
+ return "\n".join(o) + "\n"