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,530 @@
1
+ """Host-side glue of the G1 engine shared by the check binaries (scripts/engine_step_check.py, the adjoint check binary
2
+ of nablaengine.checks, ...) and the JAX FFI library (nablaengine.jax_ffi): KERNEL, the forward kernel k_substep (one
3
+ launch per control step of nsub substeps, one block of 32 threads per world, optionally writing the tape), the split
4
+ forward (k_pre / k_post, two launches per substep, dk_forward_split: the production forward when DK_SPLIT is 1, the
5
+ default; bitwise the same results), and loader(), the host code that copies the packed model constants into the
6
+ kernels' DKC arrays (scripts/engine_step_check.py re-exports both)."""
7
+
8
+
9
+ KERNEL = r"""
10
+ #ifndef DK_SPLIT
11
+ #define DK_SPLIT 1 // engine_step_check.py's and the FFI's forward: 1 the split kernels (dk_forward_split), 0 k_substep
12
+ #endif
13
+ #ifdef DK_PROFILE
14
+ static_assert(NPROF <= 32, "one profile counter per lane (step.PROF_PHASES: at most 32 phases)");
15
+ __device__ unsigned long long g_prof[NPROF];
16
+ #endif
17
+ // tape: null, or nw * nsub records of REC_WORDS (tape.py), record w * nsub + k for world w and substep k
18
+ __global__ void k_substep(int nw, const float* qpos, const float* qvel, const float* warm, const float* ctrl,
19
+ const float* fric, const float* com, int iterations, int nsub, float* oqpos, float* oqvel,
20
+ float* owarm, int* info, float* ocon, float* tape) {
21
+ extern __shared__ __align__(16) unsigned char dk_smem[]; // dynamic: struct Sim can exceed the 48 KB static limit
22
+ Sim& s = *reinterpret_cast<Sim*>(dk_smem);
23
+ // lane = threadIdx.x & 31, not threadIdx.x (also in k_pre, k_post, k_adjoint): the block is one warp, but the
24
+ // compiler bounds threadIdx.x only by 1024 (even under __launch_bounds__(32, ...)), so every lane-strided loop of the
25
+ // inlined code (for i = lane; i < n; i += 32) has an unknown trip count and is unrolled by 4 with a remainder loop;
26
+ // with the mask it has at most ceil(n / 32) trips and stays a short loop (a __noinline__ callee's lane parameter has
27
+ // no bound: adjoint.py LANE_BOUND). Results bitwise the same. SASS (sm_86): k_substep 10949 -> 9672 instructions,
28
+ // k_pre 6375 -> 5771, k_post 11983 -> 9303, k_adjoint 2882 -> 1810; k_post's spills on sm_120 / sm_90a (16 / 20 B,
29
+ // ptxas 12.9 on nvcc 12.4's PTX) gone. RTX 3090 (a 4096-state corpus, 10 iterations): the forward 2.5% / 2.2%
30
+ // faster at 1787 / 4096 worlds, k_adjoint 3.0% / 3.1% (the mask alone)
31
+ int lane = threadIdx.x & 31, w = blockIdx.x;
32
+ if (w >= nw) return;
33
+ for (int i = lane; i < NQ; i += 32) s.qpos[i] = qpos[(size_t)w * NQ + i];
34
+ for (int i = lane; i < NV; i += 32) { s.qvel[i] = qvel[(size_t)w * NV + i]; s.qacc[i] = warm[(size_t)w * NV + i]; }
35
+ if (lane < 3) s.com[lane] = com[(size_t)w * COM_WORDS + lane];
36
+ load_fixtures(s, com, w, lane);
37
+ if (lane == 0) { s.fric = fric[w]; s.unsupported = 0; }
38
+ #ifdef DK_PROFILE
39
+ if (lane < NPROF) s.prof[lane] = 0;
40
+ #endif
41
+ __syncwarp();
42
+ int nit = 0;
43
+ for (int k = 0; k < nsub; k++) {
44
+ if (lane == 0) s.oforce = k == nsub - 1 ? s.con_fo : nullptr; // the contact forces of the last substep
45
+ __syncwarp();
46
+ substep(s, ctrl + (size_t)w * NU, iterations, lane, &nit,
47
+ tape ? tape + ((size_t)w * nsub + k) * REC_WORDS : nullptr);
48
+ }
49
+ for (int i = lane; i < NQ; i += 32) oqpos[(size_t)w * NQ + i] = s.qpos[i];
50
+ for (int i = lane; i < NV; i += 32) { oqvel[(size_t)w * NV + i] = s.qvel[i]; owarm[(size_t)w * NV + i] = s.qacc[i]; }
51
+ #ifdef DK_PROFILE
52
+ __syncwarp();
53
+ if (lane < NPROF) atomicAdd(&g_prof[lane], (unsigned long long)s.prof[lane]);
54
+ #endif
55
+ if (lane == 0) { info[w * 4] = nit; info[w * 4 + 1] = s.ncon; info[w * 4 + 2] = s.nefc; info[w * 4 + 3] = s.unsupported; }
56
+ for (int c = lane; c < MAXCON; c += 32) { // contacts of the last substep: pair, dist, pos, normal, force, normal force
57
+ float* o = ocon + ((size_t)w * MAXCON + c) * CON_WORDS;
58
+ bool v = c < min(s.ncon, MAXCON);
59
+ o[0] = v ? (float)s.con_pair[c] : -1.f; o[1] = v ? s.con_dist[c] : 0.f;
60
+ for (int k = 0; k < 3; k++) { o[2 + k] = v ? s.con_pos[c][k] : 0.f; o[5 + k] = v ? s.con_frame[c][k] : 0.f; }
61
+ for (int k = 0; k < 3; k++)
62
+ o[8 + k] = v ? s.con_fo[c][0] * s.con_frame[c][k] + s.con_fo[c][1] * s.con_frame[c][3 + k]
63
+ + s.con_fo[c][2] * s.con_frame[c][6 + k] : 0.f;
64
+ o[11] = v ? s.con_fo[c][0] : 0.f;
65
+ }
66
+ }
67
+
68
+ // The split forward: every substep as two halves, substep_pre on struct SimP and substep_post on struct SimN (step.py),
69
+ // what crosses between them in struct Hand (global memory, work[w] for world w). The pre half reads the substep's input
70
+ // state (the inputs for substep 0, then the outputs), the post half the warm start (warm, then owarm) and writes the
71
+ // state after the substep to the outputs, so no other buffer is needed. Each half writes its part of the substep's tape
72
+ // record (substep_pre / substep_post, as in k_substep). Results, tape and contacts are bitwise those of k_substep.
73
+ // Two kernels per substep, k_pre and k_post (2 nsub launches, dk_forward_split). Every launch ends on a tail: per world
74
+ // 3.67 / 3.57 / 3.51 us at 1280 / 4096 / 8192 worlds on V100, 1.55 / 1.21 us at 1804 / 4096 on RTX 3090 (2 and 4.5
75
+ // waves; 4096 worlds on the target GPUs are about 2 waves). A persistent single-launch variant (blocks taking (half,
76
+ // world) tasks from a counter, per-world release / acquire waits) was 20% slower on V100 and was dropped.
77
+ // DK_SPLIT_ORDER 1 (default): k_post runs the worlds with the most constraint rows first (SPLIT_NBUCKET buckets of
78
+ // 2^SPLIT_ROW_SHIFT rows, counted by k_pre), so the launch does not end on a late expensive world (rows correlate 0.6
79
+ // with the Newton iterations); the results do not depend on the order (nor on the two bucket parameters). At about 2
80
+ // waves (4096 worlds on the target GPUs, 1787 on the RTX 3090) k_post's makespan is then the duration of its slowest
81
+ // world, which starts in the first wave. RTX 3090 (a 4096-state corpus, 10 iterations, alternating runs): 64 buckets
82
+ // of 2 rows with the warp-parallel lookup (dk_order_world) against 16 buckets of 8 rows with a serial lookup on
83
+ // lane 0: forward -4.1% at 1787 worlds (a second corpus -2.1%), -2.3% at 4096 (cycles -3.0%); the faster lookup alone
84
+ // -0.5%;
85
+ // 32 buckets of 4 rows -3.3%, 128 of 1 row -3.8%. Measured-cost keys lose: the world's k_post(k - 1) cycles +5..6%
86
+ // (Spearman 0.79 with k_post(k)'s cycles, the rows 0.89: a world's cycles depend on its SM's load), its k_post(k - 1)
87
+ // Newton iterations x rows +3.2%; ordering k_pre(k) by the world's k_pre(k - 1) cycles -0.4 / 0.0% (not kept).
88
+ // Worlds per SM: the register file is split over the SM's 4 schedulers (16K registers each), so 1-warp blocks fit
89
+ // 8 / 12 / 16 per SM at <= 255 / 168 / 128 registers; SPLIT_PRE_MINB / SPLIT_POST_MINB (__launch_bounds__ minimum
90
+ // blocks per SM, 0: none) make ptxas fit a kernel's registers to that many blocks. Default 12 (RTX 3090: k_pre 12,
91
+ // k_post 11 worlds per SM, 5.61 ms against 6.32 ms uncapped at 8 / 8). V100 (uncapped: k_pre 151, k_post 190
92
+ // registers, 12 / 8 per SM; capped: 159 / 168, 12 / 12 per SM): 6.05 against 6.35 ms (a 4096-state corpus, 10
93
+ // iterations; 1787 worlds 2.55 / 2.65, a second corpus 6.18 / 6.55, with the tape 6.26 / 6.54), the same results. In
94
+ // the current code k_post has no spills at 168 registers (20 / 52 bytes in an earlier version) and the cap is worth
95
+ // 5.0% on V100 (5.89 against 6.20 ms);
96
+ // SPLIT_POST_MINB 10 / 11 or a runtime cap of 11 / 10 per SM: +0.5% / +0.7% / 0% / +16%. On the RTX 3090 SimN's
97
+ // shared memory allows 11 k_post blocks; SPLIT_POST_MINB 11 compiles to the same 168 registers.
98
+ // SPLIT_POST_MAXNREG (defined and > 0): k_post's register cap as __maxnreg__(N) (nvcc 12.4+) in place of
99
+ // __launch_bounds__(32, SPLIT_POST_MINB). On sm_90 / sm_90a the build gives the forward unit -DSPLIT_PRE_MINB=16
100
+ // -DSPLIT_POST_MAXNREG=128 (nablaengine.cuda.unit_defines, $DK_SM90_REG_CAPS; decided by the build target in Python,
101
+ // not by __CUDA_ARCH__, which is 900 in sm_120's compute_90 forward unit too): H100 SXM5 (nvcc 12.8) k_pre 158 ->
102
+ // 128 registers without spills, k_post 168 -> 128 with spills (76 / 176 B stored / loaded; an earlier version of the
103
+ // code with nvcc 12.4: 32 / 88 B), 12 -> 16 worlds per SM each, forward -10.8% at 4096 worlds
104
+ // (k_pre's cap alone -3.6%, k_post's -7.1%), bitwise unchanged; on the RTX PRO 6000 the same two settings +0.6%
105
+ // (shared memory allows fewer worlds per SM there).
106
+ #ifndef DK_SPLIT_ORDER
107
+ #define DK_SPLIT_ORDER 1
108
+ #endif
109
+ #ifndef SPLIT_NBUCKET
110
+ #define SPLIT_NBUCKET 64
111
+ #endif
112
+ #ifndef SPLIT_ROW_SHIFT
113
+ #define SPLIT_ROW_SHIFT 1 // the bucket width: 2 rows (bucket 0, the first, also takes the worlds above the range)
114
+ #endif
115
+ #define SPLIT_MAXSUB 32 // substeps per call with DK_SPLIT_ORDER (the bucket counters)
116
+ #define SPLIT_MINB_DEFAULT 12
117
+ #ifndef SPLIT_PRE_MINB
118
+ #define SPLIT_PRE_MINB SPLIT_MINB_DEFAULT
119
+ #endif
120
+ #ifndef SPLIT_POST_MINB
121
+ #define SPLIT_POST_MINB SPLIT_MINB_DEFAULT
122
+ #endif
123
+ #ifndef DK_PRE2W
124
+ #define DK_PRE2W 0 // the latency mode's k_pre: two warps per world (step.py substep_pre)
125
+ #endif
126
+ #define PRE_THREADS (DK_PRE2W ? 64 : 32)
127
+ #if DK_PRE2W // (a few worlds per SM: no occupancy target, the registers the code wants)
128
+ #define SPLIT_PRE_BOUNDS __launch_bounds__(64)
129
+ #elif SPLIT_PRE_MINB > 0
130
+ #define SPLIT_PRE_BOUNDS __launch_bounds__(32, SPLIT_PRE_MINB)
131
+ #else
132
+ #define SPLIT_PRE_BOUNDS
133
+ #endif
134
+ #if defined(SPLIT_POST_MAXNREG) && SPLIT_POST_MAXNREG > 0
135
+ #if __CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__ < 1204
136
+ #error "SPLIT_POST_MAXNREG: __maxnreg__ needs nvcc 12.4 or newer"
137
+ #endif
138
+ #define SPLIT_POST_BOUNDS __maxnreg__(SPLIT_POST_MAXNREG)
139
+ #elif SPLIT_POST_MINB > 0
140
+ #define SPLIT_POST_BOUNDS __launch_bounds__(32, SPLIT_POST_MINB)
141
+ #else
142
+ #define SPLIT_POST_BOUNDS
143
+ #endif
144
+
145
+ #if HAS_DEFER
146
+ // The split forward with deferred pairs (CV_DEFER, default 1; box-box, capsule-box, mesh pairs: step.has_defer): per
147
+ // substep k_pre_a (kinematics, collision; those pairs queued past their OBB test), k_ccd (one thread per queued pair:
148
+ // box_pair, convex_pair or plane_mesh, its contacts appended to the world's Hand), k_pre (substep_pre PHASE 2: the
149
+ // contacts in canonical order, step.sort_contacts), k_post. A warp of k_ccd takes 32 pairs of different worlds instead
150
+ // of a world's few on as many lanes of its warp.
151
+ #ifndef CV_DEFER
152
+ #define CV_DEFER 1
153
+ #endif
154
+ #ifndef CVQ_PER_WORLD
155
+ #define CVQ_PER_WORLD 64 // the queue's capacity per world (beyond: the pairs dropped, unsupported bit 4)
156
+ #endif
157
+ __device__ __forceinline__ bool cv_defer(SimP& s, int pair) {
158
+ if (!s.cvq) return false;
159
+ const int i = atomicAdd(s.cvn, 1);
160
+ if (i < s.cvcap) s.cvq[i] = make_int2(s.world, pair);
161
+ else atomicOr(&s.unsupported, 4);
162
+ return true;
163
+ }
164
+ #else
165
+ #define CV_DEFER 0
166
+ #endif
167
+
168
+ #if DK_PRE2W && CV_DEFER
169
+ #error "DK_PRE2W: not with the deferred pairs (k_pre_a / k_ccd)"
170
+ #endif
171
+ // the pre half of substep k for world w
172
+ __device__ __forceinline__ void pre_world(SimP& s, Hand& g, int w, int lane, const float* qpos, const float* qvel,
173
+ const float* ctrl, const float* fric, const float* com, int k, int nsub,
174
+ float* ocon, float* tape) {
175
+ if (threadIdx.x < 32) { // (DK_PRE2W: warp 0 loads; both warps run substep_pre; warp 0 stores)
176
+ for (int i = lane; i < NQ; i += 32) s.qpos[i] = qpos[(size_t)w * NQ + i];
177
+ for (int i = lane; i < NV; i += 32) s.qvel[i] = qvel[(size_t)w * NV + i];
178
+ if (lane < 3) s.com[lane] = com[(size_t)w * COM_WORDS + lane];
179
+ load_fixtures(s, com, w, lane);
180
+ if (lane == 0) {
181
+ s.fric = fric[w];
182
+ s.unsupported = k ? g.unsupported : 0; // accumulated over the substeps (the post half does not change it)
183
+ s.M = g.M; s.con_dist = g.con_dist; s.con_pos = g.con_pos; s.con_frame = g.con_frame;
184
+ s.con_J = g.con_J; s.con_dof = g.con_dof; s.con_mask = g.con_mask; s.kvoff = g.kvoff;
185
+ #if DK_CLAMP_IMPLICIT == 2
186
+ s.kvw = g.kvw;
187
+ #endif
188
+ s.efc_kind = g.efc_kind; s.efc_a = g.efc_a; s.efc_b = g.efc_b; s.efc_D = g.efc_D; s.efc_aref = g.efc_aref;
189
+ #if HAS_DEFER
190
+ s.cvq = nullptr;
191
+ #endif
192
+ }
193
+ #ifdef DK_PROFILE
194
+ if (lane < NPROF) s.prof[lane] = 0;
195
+ #endif
196
+ }
197
+ if (DK_PRE2W) __syncthreads(); else __syncwarp();
198
+ #if CV_DEFER
199
+ { // the contacts of k_pre_a and k_ccd
200
+ const int n = min(g.ncon, MAXCON);
201
+ for (int c = lane; c < n; c += 32) {
202
+ s.con_pair[c] = g.con_pair[c]; s.con_slot[c] = g.con_slot[c]; s.con_dim[c] = g.con_dim[c];
203
+ s.con_mu[c] = g.con_mu[c];
204
+ }
205
+ if (lane == 0) { s.ncon = g.ncon; s.min_nu_bits = g.min_nu_bits; s.unsupported = g.unsupported; }
206
+ __syncwarp();
207
+ }
208
+ substep_pre<2>(s, ctrl + (size_t)w * NU, lane, tape ? tape + ((size_t)w * nsub + k) * REC_WORDS : nullptr);
209
+ #else
210
+ substep_pre(s, ctrl + (size_t)w * NU, lane, tape ? tape + ((size_t)w * nsub + k) * REC_WORDS : nullptr);
211
+ #endif
212
+ if (threadIdx.x >= 32) return;
213
+ int ncon = min(s.ncon, MAXCON);
214
+ for (int i = lane; i < NV; i += 32) { g.qsm[i] = s.qsm[i]; g.qacc0[i] = s.qacc0[i]; }
215
+ for (int c = lane; c < ncon; c += 32) {
216
+ g.con_pair[c] = s.con_pair[c]; g.con_dim[c] = s.con_dim[c]; g.con_row[c] = s.con_row[c];
217
+ g.con_nrow[c] = s.con_nrow[c]; g.con_nd[c] = s.con_nd[c]; g.con_mu[c] = s.con_mu[c];
218
+ }
219
+ if (lane == 0) {
220
+ g.ncon = s.ncon; g.nefc = s.nefc; g.nefc_dof = s.nefc_dof; g.unsupported = s.unsupported;
221
+ g.min_nu_bits = s.min_nu_bits;
222
+ }
223
+ if (k == nsub - 1) // contacts of the last substep's collision: pair, dist, pos, normal
224
+ for (int c = lane; c < MAXCON; c += 32) {
225
+ float* o = ocon + ((size_t)w * MAXCON + c) * CON_WORDS; // (words 8 .. 11: the forces, k_post)
226
+ bool v = c < ncon;
227
+ o[0] = v ? (float)s.con_pair[c] : -1.f; o[1] = v ? s.con_dist[c] : 0.f;
228
+ for (int t = 0; t < 3; t++) { o[2 + t] = v ? s.con_pos[c][t] : 0.f; o[5 + t] = v ? s.con_frame[c][t] : 0.f; }
229
+ if (!v) for (int t = 8; t < 12; t++) o[t] = 0.f; // (past the world's contacts: k_post writes none)
230
+ }
231
+ #ifdef DK_PROFILE
232
+ __syncwarp();
233
+ if (lane < NPROF) atomicAdd(&g_prof[lane], (unsigned long long)s.prof[lane]);
234
+ #endif
235
+ __syncwarp();
236
+ }
237
+
238
+ template <class S> // the post half of substep k for world w on its state s (SimN in shared memory, or Hand::big)
239
+ __device__ __forceinline__ void post_world_on(S& s, const Hand& g, int w, int lane, const float* qpos,
240
+ const float* qvel, const float* warm, int iterations, int k, int nsub,
241
+ float* oqpos, float* oqvel, float* owarm, int* info, float* tape,
242
+ float* ocon, float (*fo)[3]) {
243
+ const int ncon = min(g.ncon, MAXCON), nefc = g.nefc;
244
+ float *q = oqpos + (size_t)w * NQ, *v = oqvel + (size_t)w * NV; // implicitfast updates the outputs in place
245
+ if (k == 0) { // (from substep 1 on, the inputs are the outputs)
246
+ for (int i = lane; i < NQ; i += 32) q[i] = qpos[(size_t)w * NQ + i];
247
+ for (int i = lane; i < NV; i += 32) v[i] = qvel[(size_t)w * NV + i];
248
+ }
249
+ for (int i = lane; i < NV; i += 32) s.qacc[i] = warm[(size_t)w * NV + i];
250
+ for (int i = lane; i < NTRI; i += 32) s.M[i] = g.M[i];
251
+ for (int r = lane; r < nefc; r += 32) {
252
+ s.efc_kind[r] = g.efc_kind[r]; s.efc_a[r] = g.efc_a[r]; s.efc_b[r] = g.efc_b[r]; s.efc_D[r] = g.efc_D[r];
253
+ }
254
+ for (int c = lane; c < ncon; c += 32) {
255
+ s.con_dim[c] = g.con_dim[c]; s.con_row[c] = g.con_row[c]; s.con_nrow[c] = g.con_nrow[c]; s.con_nd[c] = g.con_nd[c];
256
+ }
257
+ if (lane == 0) {
258
+ s.ncon = g.ncon; s.nefc = nefc; s.nefc_dof = g.nefc_dof; s.unsupported = g.unsupported;
259
+ s.min_nu_bits = g.min_nu_bits;
260
+ s.qpos = q; s.qvel = v; s.qsm = g.qsm; s.qacc0 = g.qacc0; s.con_mu = g.con_mu; s.efc_aref = g.efc_aref;
261
+ s.con_pair = g.con_pair; s.con_J = g.con_J; s.con_dof = g.con_dof; s.con_mask = g.con_mask;
262
+ s.kvoff = g.kvoff;
263
+ #if DK_CLAMP_IMPLICIT == 2
264
+ s.kvw = g.kvw;
265
+ #endif
266
+ s.oforce = k == nsub - 1 ? fo : nullptr; // the contact forces of the last substep (Hand::con_force)
267
+ }
268
+ #ifdef DK_PROFILE
269
+ if (lane < NPROF) s.prof[lane] = 0;
270
+ #endif
271
+ __syncwarp();
272
+ int nit = 0;
273
+ substep_post(s, iterations, lane, &nit, tape ? tape + ((size_t)w * nsub + k) * REC_WORDS : nullptr);
274
+ if (k == nsub - 1 && ocon) // the contact table's forces (k_pre wrote the rest): world force, normal force
275
+ for (int c = lane; c < ncon; c += 32) {
276
+ float* o = ocon + ((size_t)w * MAXCON + c) * CON_WORDS;
277
+ for (int j = 0; j < 3; j++)
278
+ o[8 + j] = fo[c][0] * g.con_frame[c][j] + fo[c][1] * g.con_frame[c][3 + j] + fo[c][2] * g.con_frame[c][6 + j];
279
+ o[11] = fo[c][0];
280
+ }
281
+ for (int i = lane; i < NV; i += 32) owarm[(size_t)w * NV + i] = s.qacc[i];
282
+ if (k == nsub - 1 && lane == 0) {
283
+ info[w * 4] = nit; info[w * 4 + 1] = s.ncon; info[w * 4 + 2] = s.nefc; info[w * 4 + 3] = s.unsupported;
284
+ }
285
+ #ifdef DK_PROFILE
286
+ __syncwarp();
287
+ if (lane < NPROF) atomicAdd(&g_prof[lane], (unsigned long long)s.prof[lane]);
288
+ #endif
289
+ __syncwarp();
290
+ }
291
+
292
+ // the post half: on SimN in shared memory (smem) when the world's contacts and rows fit, else on Hand::big
293
+ __device__ __forceinline__ void post_world(unsigned char* smem, Hand& g, int w, int lane, const float* qpos,
294
+ const float* qvel, const float* warm, int iterations, int k, int nsub,
295
+ float* oqpos, float* oqvel, float* owarm, int* info, float* tape,
296
+ float* ocon) {
297
+ #ifndef DK_SPLIT_ALL_BIG // (debug: every world on the full-capacity state in global memory)
298
+ if (min(g.ncon, MAXCON) <= SPLIT_NCON && g.nefc <= SPLIT_NEFC)
299
+ post_world_on(*reinterpret_cast<SimN*>(smem), g, w, lane, qpos, qvel, warm, iterations, k, nsub, oqpos, oqvel,
300
+ owarm, info, tape, ocon, g.con_force);
301
+ else
302
+ #endif
303
+ post_world_on(g.big, g, w, lane, qpos, qvel, warm, iterations, k, nsub, oqpos, oqvel, owarm, info, tape, ocon,
304
+ g.con_force);
305
+ }
306
+
307
+ // DK_SPLIT_ORDER's ordering memory (after the Hand records): counters cnt[SPLIT_MAXSUB][SPLIT_NBUCKET] (zero at the
308
+ // call), then order[2][SPLIT_NBUCKET][nw]: substep k's worlds of bucket b (most rows first) at order[k & 1][b]
309
+ #if DK_SPLIT_ORDER
310
+ // block i's world in bucket order (cnt: one substep's counters, order: its lists; all of k_pre(k) has run), on the
311
+ // whole warp: lane l sums the counters of buckets l * PER .. l * PER + PER - 1, a shuffle scan gives the lane whose
312
+ // range holds i and that lane the bucket (a serial walk over 64 buckets on lane 0 would cost each block up to 64
313
+ // dependent loads)
314
+ __device__ __forceinline__ int dk_order_world(const int* cnt, const int* order, int nw, int i, int lane) {
315
+ constexpr int PER = (SPLIT_NBUCKET + 31) / 32;
316
+ int c[PER], s = 0;
317
+ #pragma unroll
318
+ for (int j = 0; j < PER; j++) {
319
+ const int b = lane * PER + j;
320
+ c[j] = b < SPLIT_NBUCKET ? cnt[b] : 0;
321
+ s += c[j];
322
+ }
323
+ int incl = s;
324
+ #pragma unroll
325
+ for (int o = 1; o < 32; o <<= 1) {
326
+ const int t = __shfl_up_sync(0xffffffffu, incl, o);
327
+ if (lane >= o) incl += t;
328
+ }
329
+ const int excl = incl - s;
330
+ const unsigned m = __ballot_sync(0xffffffffu, i >= excl && i < incl); // one lane (the counters sum to nw > i)
331
+ const int src = __ffs(m) - 1;
332
+ int b = lane * PER + PER - 1, r = i - excl;
333
+ bool found = false;
334
+ #pragma unroll
335
+ for (int j = 0; j < PER; j++) { // the lane's first bucket j with r < c[0] + ... + c[j]
336
+ if (!found && r < c[j]) { b = lane * PER + j; found = true; }
337
+ else if (!found) r -= c[j];
338
+ }
339
+ b = __shfl_sync(0xffffffffu, b, src);
340
+ r = __shfl_sync(0xffffffffu, r, src);
341
+ return order[(size_t)b * nw + r];
342
+ }
343
+ #endif
344
+ #if CV_DEFER
345
+ // k_pre_a: substep_pre PHASE 1 (kinematics, collision with the deferred pairs queued), its contacts and geom poses
346
+ // into Hand for k_ccd and k_pre
347
+ __global__ void SPLIT_PRE_BOUNDS k_pre_a(int nw, const float* qpos, const float* qvel, const float* ctrl,
348
+ const float* fric, const float* com, int k, int nsub, Hand* work, int2* cvq,
349
+ int* cvn, float* tape) {
350
+ extern __shared__ __align__(16) unsigned char dk_smem[];
351
+ SimP& s = *reinterpret_cast<SimP*>(dk_smem);
352
+ const int lane = threadIdx.x & 31, w = blockIdx.x;
353
+ if (w >= nw) return;
354
+ Hand& g = work[w];
355
+ for (int i = lane; i < NQ; i += 32) s.qpos[i] = qpos[(size_t)w * NQ + i];
356
+ for (int i = lane; i < NV; i += 32) s.qvel[i] = qvel[(size_t)w * NV + i];
357
+ if (lane < 3) s.com[lane] = com[(size_t)w * COM_WORDS + lane];
358
+ load_fixtures(s, com, w, lane);
359
+ if (lane == 0) {
360
+ s.fric = fric[w];
361
+ s.unsupported = k ? g.unsupported : 0;
362
+ s.M = g.M; s.con_dist = g.con_dist; s.con_pos = g.con_pos; s.con_frame = g.con_frame; s.kvoff = g.kvoff;
363
+ #if DK_CLAMP_IMPLICIT == 2
364
+ s.kvw = g.kvw;
365
+ #endif
366
+ s.cvq = cvq; s.cvn = cvn; s.cvcap = nw * CVQ_PER_WORLD; s.world = w;
367
+ }
368
+ __syncwarp();
369
+ substep_pre<1>(s, ctrl + (size_t)w * NU, lane, nullptr); // (no tape: k_pre writes it)
370
+ const int n = min(s.ncon, MAXCON);
371
+ for (int c = lane; c < n; c += 32) {
372
+ g.con_pair[c] = s.con_pair[c]; g.con_slot[c] = s.con_slot[c]; g.con_dim[c] = s.con_dim[c];
373
+ g.con_mu[c] = s.con_mu[c];
374
+ }
375
+ for (int i = lane; i < NGEOMC; i += 32) {
376
+ for (int t = 0; t < 3; t++) g.gx[i][t] = s.gx[i][t];
377
+ for (int t = 0; t < 4; t++) g.gq[i][t] = s.gq[i][t];
378
+ }
379
+ if (lane == 0) { g.ncon = s.ncon; g.min_nu_bits = s.min_nu_bits; g.unsupported = s.unsupported; }
380
+ }
381
+
382
+ // k_ccd: one thread per queued pair: its contacts appended to the world's
383
+ __global__ void k_ccd(const int2* cvq, const int* cvn, int cap, Hand* work, const float* fric) {
384
+ const int i = blockIdx.x * blockDim.x + threadIdx.x;
385
+ if (i >= min(*cvn, cap)) return;
386
+ const int w = cvq[i].x, pair = cvq[i].y;
387
+ Hand& g = work[w];
388
+ const int g1 = PG1(pair), g2 = PG2(pair), t1 = c_gtype[g1], t2 = c_gtype[g2];
389
+ CSink o;
390
+ o.n = 0; o.unsupported = 0;
391
+ #if HAS_MESH
392
+ if (t2 == 4) {
393
+ if (t1 == 0) {
394
+ float n[3];
395
+ zaxis_rn(g.gq[g1], n);
396
+ CV_PLANE(g.gx[g1], n, g2, g.gx[g2], g.gq[g2], o);
397
+ } else {
398
+ CV_PAIR(g1, t1, g.gx[g1], g.gq[g1], g2, t2, g.gx[g2], g.gq[g2], o);
399
+ }
400
+ }
401
+ #endif
402
+ #if HAS_BOX
403
+ if (t2 == 3) box_pair(g1, t1, g.gx[g1], g.gq[g1], g2, g.gx[g2], g.gq[g2], o);
404
+ #endif
405
+ if (o.unsupported) atomicOr(&g.unsupported, o.unsupported);
406
+ if (!o.n) return;
407
+ const int c0 = atomicAdd(&g.ncon, o.n);
408
+ for (int j = 0; j < o.n; j++) {
409
+ const int c = c0 + j;
410
+ if (c >= MAXCON) { atomicOr(&g.unsupported, 4); continue; }
411
+ g.con_pair[c] = pair; g.con_slot[c] = (unsigned char)o.slot[j]; g.con_dim[c] = PDIM(pair);
412
+ g.con_mu[c] = PFOOT(pair) ? fric[w] : PMU(pair);
413
+ g.con_dist[c] = o.dist[j];
414
+ for (int t = 0; t < 3; t++) g.con_pos[c][t] = o.pos[j][t];
415
+ for (int t = 0; t < 9; t++) g.con_frame[c][t] = o.fr[j][t];
416
+ }
417
+ }
418
+ #endif
419
+
420
+ __global__ void SPLIT_PRE_BOUNDS k_pre(int nw, const float* qpos, const float* qvel, const float* ctrl,
421
+ const float* fric, const float* com, int k, int nsub, Hand* work, float* ocon,
422
+ float* tape) {
423
+ extern __shared__ __align__(16) unsigned char dk_smem[];
424
+ const int lane = threadIdx.x & 31, w = blockIdx.x; // (& 31: see k_substep)
425
+ if (w >= nw) return;
426
+ pre_world(*reinterpret_cast<SimP*>(dk_smem), work[w], w, lane, qpos, qvel, ctrl, fric, com, k, nsub, ocon, tape);
427
+ if (threadIdx.x >= 32) return;
428
+ #if DK_SPLIT_ORDER
429
+ if (lane == 0) {
430
+ int* cnt = reinterpret_cast<int*>(work + nw);
431
+ int* order = cnt + SPLIT_MAXSUB * SPLIT_NBUCKET + (size_t)(k & 1) * SPLIT_NBUCKET * nw;
432
+ int b = SPLIT_NBUCKET - 1 - min(work[w].nefc >> SPLIT_ROW_SHIFT, SPLIT_NBUCKET - 1);
433
+ order[(size_t)b * nw + atomicAdd(cnt + k * SPLIT_NBUCKET + b, 1)] = w;
434
+ }
435
+ #endif
436
+ }
437
+
438
+ __global__ void SPLIT_POST_BOUNDS k_post(int nw, const float* qpos, const float* qvel, const float* warm,
439
+ int iterations, int k, int nsub, Hand* work, float* oqpos, float* oqvel,
440
+ float* owarm, int* info, float* tape, float* ocon) {
441
+ extern __shared__ __align__(16) unsigned char dk_smem[];
442
+ const int lane = threadIdx.x & 31; // (& 31: see k_substep)
443
+ int w = blockIdx.x;
444
+ if (w >= nw) return;
445
+ #if DK_SPLIT_ORDER
446
+ { // block w takes the w-th world in bucket order
447
+ const int* cnt = reinterpret_cast<const int*>(work + nw);
448
+ w = dk_order_world(cnt + k * SPLIT_NBUCKET,
449
+ cnt + SPLIT_MAXSUB * SPLIT_NBUCKET + (size_t)(k & 1) * SPLIT_NBUCKET * nw, nw, w, lane);
450
+ }
451
+ #endif
452
+ post_world(dk_smem, work[w], w, lane, qpos, qvel, warm, iterations, k, nsub, oqpos, oqvel, owarm, info, tape, ocon);
453
+ }
454
+
455
+ // work memory of dk_forward_split for nw worlds: nw records of struct Hand (and DK_SPLIT_ORDER's ordering memory)
456
+ static inline size_t dk_order_bytes(int nw) {
457
+ return DK_SPLIT_ORDER ? (SPLIT_MAXSUB + (size_t)2 * nw) * SPLIT_NBUCKET * sizeof(int) : 0;
458
+ }
459
+ static inline size_t dk_work_bytes(int nw) {
460
+ #if CV_DEFER
461
+ return (size_t)nw * sizeof(Hand) + dk_order_bytes(nw) + 16 + (size_t)nw * CVQ_PER_WORLD * sizeof(int2); // (counter,
462
+ // queue)
463
+ #else
464
+ return (size_t)nw * sizeof(Hand) + dk_order_bytes(nw);
465
+ #endif
466
+ }
467
+ static int dk_split_only = 0; // timing experiments (engine_step_check.py): 1 / 2 launches only k_pre / k_post, on the
468
+ // state the previous launches left (the results are not a forward then)
469
+ // one control step (k_substep's arguments) on stream st; work: dk_work_bytes(nw) bytes (16-byte aligned); smem_pre /
470
+ // smem_post: the kernels' dynamic shared memory (at least sizeof(SimP) / sizeof(SimN); more caps the worlds per SM,
471
+ // and above 48 KB needs the cudaFuncAttributeMaxDynamicSharedMemorySize opt-in)
472
+ static inline cudaError_t dk_forward_split(cudaStream_t st, int nw, const float* qpos, const float* qvel,
473
+ const float* warm, const float* ctrl, const float* fric, const float* com,
474
+ int iterations, int nsub, float* oqpos, float* oqvel, float* owarm,
475
+ int* info, float* ocon, float* tape, void* work,
476
+ size_t smem_pre = sizeof(SimP), size_t smem_post = sizeof(SimN)) {
477
+ Hand* hand = reinterpret_cast<Hand*>(work);
478
+ #if DK_SPLIT_ORDER
479
+ if (nsub > SPLIT_MAXSUB) return cudaErrorInvalidValue;
480
+ if (dk_split_only != 2) // (k_post alone reuses the previous launches' order)
481
+ cudaMemsetAsync(hand + nw, 0, SPLIT_MAXSUB * SPLIT_NBUCKET * sizeof(int), st);
482
+ #endif
483
+ #if CV_DEFER
484
+ int* cvn = reinterpret_cast<int*>(reinterpret_cast<char*>(work) + (size_t)nw * sizeof(Hand) + dk_order_bytes(nw));
485
+ int2* cvq = reinterpret_cast<int2*>(reinterpret_cast<char*>(cvn) + 16);
486
+ const int cvcap = nw * CVQ_PER_WORLD;
487
+ #endif
488
+ for (int k = 0; k < nsub; k++) {
489
+ #if CV_DEFER
490
+ if (dk_split_only != 2) {
491
+ cudaMemsetAsync(cvn, 0, sizeof(int), st);
492
+ k_pre_a<<<nw, 32, smem_pre, st>>>(nw, k ? oqpos : qpos, k ? oqvel : qvel, ctrl, fric, com, k, nsub, hand, cvq,
493
+ cvn, tape);
494
+ #ifndef CV_NO_CCD // (timing experiments)
495
+ k_ccd<<<(cvcap + 63) / 64, 64, 0, st>>>(cvq, cvn, cvcap, hand, fric);
496
+ #endif
497
+ }
498
+ #endif
499
+ if (dk_split_only != 2)
500
+ k_pre<<<nw, PRE_THREADS, smem_pre, st>>>(nw, k ? oqpos : qpos, k ? oqvel : qvel, ctrl, fric, com, k, nsub, hand, ocon,
501
+ tape);
502
+ if (dk_split_only != 1)
503
+ k_post<<<nw, 32, smem_post, st>>>(nw, k ? oqpos : qpos, k ? oqvel : qvel, k ? owarm : warm, iterations, k, nsub,
504
+ hand, oqpos, oqvel, owarm, info, tape, ocon);
505
+ }
506
+ return cudaGetLastError();
507
+ }
508
+ """
509
+
510
+
511
+ def loader(layouts, sizes):
512
+ """C++ statements copying the packed constants (float32 array at the host pointer p, advanced as they are read)
513
+ into the DKC symbols of layouts [(symbol, kind, count, width)] with sizes {unit: n}: kind "i" int, "u" unsigned 32-bit
514
+ as two 16-bit halves, else float."""
515
+ lines, tmp = [], 0
516
+ for sym, kind, cnt, width in layouts:
517
+ size = (sizes[cnt] if isinstance(cnt, str) else cnt) * width
518
+ if kind == "i":
519
+ lines.append(f" {{ static int t{tmp}[{size}]; for (int i = 0; i < {size}; i++) t{tmp}[i] = (int)p[i]; "
520
+ f"cudaMemcpyToSymbol({sym}, t{tmp}, {size * 4}); p += {size}; }}")
521
+ tmp += 1
522
+ elif kind == "u":
523
+ n = size
524
+ lines.append(f" {{ static unsigned int t{tmp}[{n}]; for (int i = 0; i < {n}; i++) "
525
+ f"t{tmp}[i] = (unsigned int)p[2 * i] | ((unsigned int)p[2 * i + 1] << 16); "
526
+ f"cudaMemcpyToSymbol({sym}, t{tmp}, {n * 4}); p += {2 * n}; }}")
527
+ tmp += 1
528
+ else:
529
+ lines.append(f" cudaMemcpyToSymbol({sym}, p, {size * 4}); p += {size};")
530
+ return "\n".join(lines)
@@ -0,0 +1,127 @@
1
+ """Contact supports of more than 32 dofs in the forest engine (capability T11: at most MAX_KDOF)."""
2
+ import math
3
+
4
+ MAX_KDOF = 64
5
+ NOTE = " // (kdof64: KDOF > 32)"
6
+
7
+
8
+ def needed(m):
9
+ from nablaengine.forest_engine import step
10
+ return step.max_support(m) > 32
11
+
12
+
13
+ def _sets_of_block(lo, hi, passes):
14
+ out, cols, used = [], [], 0
15
+ widths = [math.ceil((hi - max(lo, b)) / passes) for b in range(hi)]
16
+ assert max(widths) <= 32
17
+ chunks = []
18
+ for b in range(hi):
19
+ if used + widths[b] > 32:
20
+ chunks.append(cols)
21
+ cols, used = [], 0
22
+ cols.append(b)
23
+ used += widths[b]
24
+ chunks.append(cols)
25
+ for cols in chunks:
26
+ tab = [[(0, 0, 255)] * 32 for _ in range(passes)]
27
+ lane = 0
28
+ for b in cols:
29
+ rows = widths[b]
30
+ for j in range(rows):
31
+ for t in range(passes):
32
+ a = max(lo, b) + j + rows * t
33
+ tab[t][lane] = (a, b, a) if a < hi else (b, b, 255)
34
+ lane += 1
35
+ out.append((lo, hi, tab))
36
+ return out
37
+
38
+
39
+ def hess_columns_wide(kdof, lo, passes=3):
40
+ """step.hess_columns' sets from row lo on, where a row block has more than 32 columns: per block the row count
41
+ (1 .. 3 passes' worth) with the most valid pairs per set (ties: the longer block)."""
42
+ sets = []
43
+ while lo < kdof:
44
+ best = None
45
+ for r in range(1, min(kdof - lo, 4 * passes) + 1):
46
+ s = _sets_of_block(lo, lo + r, passes)
47
+ pairs = sum(1 for _, _, tab in s for row in tab for _, _, thr in row if thr != 255)
48
+ key = (pairs / len(s), r)
49
+ if best is None or key > best[0]:
50
+ best = (key, s, r)
51
+ sets += best[1]
52
+ lo += best[2]
53
+ return sets
54
+
55
+
56
+ def check_sets(sets, kdof):
57
+ """Every pair (a, b), b <= a < kdof, on exactly one (set, pass, lane); HSET_LO nondecreasing; rows of a set within
58
+ [lo, hi); per set and lane one column."""
59
+ seen = {}
60
+ los = [lo for lo, _, _ in sets]
61
+ assert los == sorted(los)
62
+ for k, (lo, hi, tab) in enumerate(sets):
63
+ for lane in range(32):
64
+ bs = {tab[t][lane][1] for t in range(len(tab)) if tab[t][lane][2] != 255}
65
+ assert len(bs) <= 1
66
+ for t in range(len(tab)):
67
+ a, b, thr = tab[t][lane]
68
+ if thr == 255:
69
+ continue
70
+ assert thr == a and lo <= a < hi and b <= a
71
+ assert (a, b) not in seen, (a, b)
72
+ seen[(a, b)] = (k, t, lane)
73
+ assert set(seen) == {(a, b) for a in range(kdof) for b in range(a + 1)}
74
+ return True
75
+
76
+
77
+ ENGINE = (
78
+ (' static_assert(KDOF <= 32, "hess_columns fits 32 lanes");\n',
79
+ ' static_assert(KDOF <= 255, "hess_columns: 8-bit support positions");' + NOTE + '\n', 1),
80
+ (" for (int c = 0; c < ncon; c++) { // scatter each contact over its support (one dof per lane)\n"
81
+ " if (lane < s.con_nd[c])\n"
82
+ " out[s.con_dof[c][lane]] += s.con_f[c][0] * s.con_J[c][0][lane] + s.con_f[c][1] * s.con_J[c][1][lane]\n"
83
+ " + s.con_f[c][2] * s.con_J[c][2][lane]\n"
84
+ "#if HAS_CONDIM4\n"
85
+ " + s.con_f[c][3] * s.con_J[c][3][lane]\n"
86
+ "#endif\n"
87
+ " ;\n",
88
+ " for (int c = 0; c < ncon; c++) { // scatter each contact over its support (lane l: entries l, "
89
+ "l + 32, ..)" + NOTE + "\n"
90
+ " for (int k = lane; k < s.con_nd[c]; k += 32)\n"
91
+ " out[s.con_dof[c][k]] += s.con_f[c][0] * s.con_J[c][0][k] + s.con_f[c][1] * s.con_J[c][1][k]\n"
92
+ " + s.con_f[c][2] * s.con_J[c][2][k]\n"
93
+ "#if HAS_CONDIM4\n"
94
+ " + s.con_f[c][3] * s.con_J[c][3][k]\n"
95
+ "#endif\n"
96
+ " ;\n", 1),
97
+ )
98
+
99
+
100
+ PREFETCH = (" int ha[HSETS][3], hb[HSETS], hthr[HSETS][3]; // this lane's support pairs (ha, hb) of one column hb "
101
+ "per set, the\n"
102
+ "#pragma unroll // same for every contact, valid when nd > hthr "
103
+ "(step.hess_columns)\n"
104
+ " for (int k = 0; k < HSETS; k++)\n#pragma unroll\n for (int t = 0; t < 3; t++) {\n"
105
+ " unsigned e = c_hcol[(3 * k + t) * 32 + lane];\n"
106
+ " ha[k][t] = e & 255; hb[k] = (e >> 8) & 255; hthr[k][t] = e >> 16;\n }\n")
107
+ SET_AT = " if (nd <= hlo[k]) break; // no rows of this set in the support\n"
108
+ SET_LOAD = (" int ha_k[3], hb_k = 0, hthr_k[3]; // this lane's pairs of set k (kdof64: loaded per set, not "
109
+ "HSETS x 7 registers)\n#pragma unroll\n for (int t = 0; t < 3; t++) {\n"
110
+ " const unsigned e = c_hcol[(3 * k + t) * 32 + lane];\n"
111
+ " ha_k[t] = e & 255; hb_k = (e >> 8) & 255; hthr_k[t] = e >> 16;\n }\n")
112
+ HSET_EDITS = ((PREFETCH, " // (kdof64: the support pairs (ha, hb, valid when nd > hthr) are loaded per set in the "
113
+ "assembly below)\n", 1),
114
+ (SET_AT, SET_AT + SET_LOAD, 1), ("hb[k]", "hb_k", 2), ("ha[k][t]", "ha_k[t]", 2),
115
+ ("hthr[k][t]", "hthr_k[t]", 2))
116
+
117
+
118
+ def apply(src, m):
119
+ """src (adjoint.cuda_source's text) with the edits for a contact support of more than 32 dofs; unchanged
120
+ otherwise."""
121
+ if not needed(m):
122
+ return src
123
+ for a, b, n in ENGINE + HSET_EDITS:
124
+ if src.count(a) != n:
125
+ raise RuntimeError(f"kdof64 anchor found {src.count(a)} times, expected {n}: {a[:70]!r}")
126
+ src = src.replace(a, b)
127
+ return src