diffneusim 1.0.0__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 (682) hide show
  1. diffneusim/__init__.py +1 -0
  2. diffneusim/_cache.py +42 -0
  3. diffneusim/_paths.py +5 -0
  4. diffneusim/bindings/rew14_ext.cu +115 -0
  5. diffneusim/bindings/soft14_capi.cpp +443 -0
  6. diffneusim/bindings/soft14_engine_ext.cu +596 -0
  7. diffneusim/bindings/soft_capi.cpp +782 -0
  8. diffneusim/bindings/soft_engine_ext.cu +495 -0
  9. diffneusim/core/cpu_engine/build.sh +40 -0
  10. diffneusim/core/cpu_engine/fiber/cuda_runtime.h +445 -0
  11. diffneusim/core/cpu_engine/x14_cpu.cpp +283 -0
  12. diffneusim/core/diff/dual.h +126 -0
  13. diffneusim/core/include/diffneusim/macros.h +35 -0
  14. diffneusim/core/kin/kinematic_tree.h +273 -0
  15. diffneusim/core/math/so3.h +182 -0
  16. diffneusim/core/soft/adj/out_adj.h +102 -0
  17. diffneusim/core/soft/adj/rnea_adj.h +425 -0
  18. diffneusim/core/soft/adj/rows_adj.h +439 -0
  19. diffneusim/core/soft/adj/rows_functor.h +89 -0
  20. diffneusim/core/soft/adj/rows_lanes.h +443 -0
  21. diffneusim/core/soft/adj/shell_adj.h +243 -0
  22. diffneusim/core/soft/adj/tree_adj.h +356 -0
  23. diffneusim/core/soft/collide.h +183 -0
  24. diffneusim/core/soft/gpu/adj14.cuh +233 -0
  25. diffneusim/core/soft/gpu/adj14_mus.cuh +98 -0
  26. diffneusim/core/soft/gpu/adj_shell.cuh +50 -0
  27. diffneusim/core/soft/gpu/adj_tab.cuh +49 -0
  28. diffneusim/core/soft/gpu/body14.cuh +47 -0
  29. diffneusim/core/soft/gpu/chol_rn.cuh +458 -0
  30. diffneusim/core/soft/gpu/chol_small.cuh +123 -0
  31. diffneusim/core/soft/gpu/chol_split.cuh +193 -0
  32. diffneusim/core/soft/gpu/engine_launch.cuh +263 -0
  33. diffneusim/core/soft/gpu/fk_rn.cuh +109 -0
  34. diffneusim/core/soft/gpu/generated/body_019e20820f86_mmfloor.cuh +28 -0
  35. diffneusim/core/soft/gpu/generated/body_62f77a4bb16b_mmfloor.cuh +52 -0
  36. diffneusim/core/soft/gpu/generated/body_77dbb7213f26_mmfloor_rampsb3l_n6t12.cuh +28 -0
  37. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rampsb3l_n6t12.cuh +28 -0
  38. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsd05_n6t12.cuh +28 -0
  39. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsdef_n6t12.cuh +28 -0
  40. diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsmjd_n6t12.cuh +28 -0
  41. diffneusim/core/soft/gpu/generated/body_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +52 -0
  42. diffneusim/core/soft/gpu/generated/body_a944653edd64_mmfloor.cuh +25 -0
  43. diffneusim/core/soft/gpu/generated/body_a944653edd64_mmfloor_rampsb3l_n6t12.cuh +25 -0
  44. diffneusim/core/soft/gpu/generated/g1_soft_5db44fd45286.cuh +74 -0
  45. diffneusim/core/soft/gpu/generated/split_62f77a4bb16b_mmfloor.cuh +18 -0
  46. diffneusim/core/soft/gpu/generated/split_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +18 -0
  47. diffneusim/core/soft/gpu/generated/x14_soft_019e20820f86_mmfloor.cuh +123 -0
  48. diffneusim/core/soft/gpu/generated/x14_soft_62f77a4bb16b_mmfloor.cuh +129 -0
  49. diffneusim/core/soft/gpu/generated/x14_soft_77dbb7213f26_mmfloor_rampsb3l_n6t12.cuh +123 -0
  50. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rampsb3l_n6t12.cuh +123 -0
  51. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsd05_n6t12.cuh +123 -0
  52. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsdef_n6t12.cuh +123 -0
  53. diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsmjd_n6t12.cuh +123 -0
  54. diffneusim/core/soft/gpu/generated/x14_soft_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +129 -0
  55. diffneusim/core/soft/gpu/generated/x14_soft_a944653edd64_mmfloor.cuh +123 -0
  56. diffneusim/core/soft/gpu/generated/x14_soft_a944653edd64_mmfloor_rampsb3l_n6t12.cuh +123 -0
  57. diffneusim/core/soft/gpu/k_mus.cuh +1038 -0
  58. diffneusim/core/soft/gpu/k_mus_host.cuh +377 -0
  59. diffneusim/core/soft/gpu/k_pre.cuh +52 -0
  60. diffneusim/core/soft/gpu/kernel_p.cuh +490 -0
  61. diffneusim/core/soft/gpu/kp14.cuh +465 -0
  62. diffneusim/core/soft/gpu/l2v2.cuh +367 -0
  63. diffneusim/core/soft/gpu/l2x14.cuh +319 -0
  64. diffneusim/core/soft/gpu/l3.cuh +1483 -0
  65. diffneusim/core/soft/gpu/model_view.cuh +48 -0
  66. diffneusim/core/soft/gpu/mus_case_fits.h +15 -0
  67. diffneusim/core/soft/gpu/mus_classes.h +182 -0
  68. diffneusim/core/soft/gpu/mus_row_cf.h +44 -0
  69. diffneusim/core/soft/gpu/rew14.cuh +177 -0
  70. diffneusim/core/soft/gpu/rows_ctab.cuh +44 -0
  71. diffneusim/core/soft/gpu/tree_m.cuh +247 -0
  72. diffneusim/core/soft/gpu/x14_engine_kernels.cuh +260 -0
  73. diffneusim/core/soft/gpu/x14_rowcf.h +14 -0
  74. diffneusim/core/soft/hand.h +124 -0
  75. diffneusim/core/soft/impedance.h +115 -0
  76. diffneusim/core/soft/jvp.h +202 -0
  77. diffneusim/core/soft/kin.h +250 -0
  78. diffneusim/core/soft/muscle.h +1208 -0
  79. diffneusim/core/soft/newton.h +371 -0
  80. diffneusim/core/soft/rows.h +176 -0
  81. diffneusim/core/soft/step.h +188 -0
  82. diffneusim/core/soft/tape.h +313 -0
  83. diffneusim/core/soft/x14/collide14.h +69 -0
  84. diffneusim/core/soft/x14/jvp14.h +182 -0
  85. diffneusim/core/soft/x14/law14.h +453 -0
  86. diffneusim/core/soft/x14adj/collide14_adj.h +134 -0
  87. diffneusim/core/soft/x14adj/passive14_adj.h +162 -0
  88. diffneusim/core/soft/x14adj/reward14.h +484 -0
  89. diffneusim/core/soft/x14adj/rows14_adj.h +400 -0
  90. diffneusim/core/soft/x14adj/scan14.h +349 -0
  91. diffneusim/core/soft/x14adj/shell14_adj.h +122 -0
  92. diffneusim/core/soft/x14adj/sweep14.h +255 -0
  93. diffneusim/core/soft/x14adj/tree14_adj.h +500 -0
  94. diffneusim/core/soft/x14adj/x14adj_common.h +96 -0
  95. diffneusim/data/mirror/H1622v2k_geyer_hfdeq.npz +0 -0
  96. diffneusim/data/mirror/H1622v2k_hfd.npz +0 -0
  97. diffneusim/data/mirror/H1622v2k_millard_hfdeq.npz +0 -0
  98. diffneusim/data/mirror/fullbody_contact.npz +0 -0
  99. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard.npz +0 -0
  100. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_p2str.npz +0 -0
  101. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_p2str_rigid.npz +0 -0
  102. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.npz +0 -0
  103. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.npz +0 -0
  104. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq.npz +0 -0
  105. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin.npz +0 -0
  106. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_calf2_pe.npz +0 -0
  107. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
  108. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfix.npz +0 -0
  109. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfixlegs01.npz +0 -0
  110. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01.npz +0 -0
  111. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01legs.npz +0 -0
  112. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01lumbar.npz +0 -0
  113. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_lumbfix.npz +0 -0
  114. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_lumbfixlegs01.npz +0 -0
  115. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.npz +0 -0
  116. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1a.npz +0 -0
  117. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n2.npz +0 -0
  118. diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_rom23.npz +0 -0
  119. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair.npz +0 -0
  120. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
  121. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_hinge.npz +0 -0
  122. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.npz +0 -0
  123. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1a.npz +0 -0
  124. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n2.npz +0 -0
  125. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_rom23.npz +0 -0
  126. diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_lspine_girdle_osimeq.npz +0 -0
  127. diffneusim/data/mirror/fullbody_contact_spinecoupled_lspine_girdle_millard.npz +0 -0
  128. diffneusim/data/mirror/fullbody_contact_spinecoupled_lspine_girdle_osimeq.npz +0 -0
  129. diffneusim/data/mirror/myoleg26_3d_compound_g14eq.npz +0 -0
  130. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq.npz +0 -0
  131. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose.npz +0 -0
  132. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin.npz +0 -0
  133. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30.npz +0 -0
  134. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30.npz +0 -0
  135. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30_luispe.npz +0 -0
  136. diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30_trunk0701.npz +0 -0
  137. diffneusim/data/muscle_fit/wang_mass_volume_14t.json +91 -0
  138. diffneusim/data/muscle_fit/wang_mass_volume_14t_axfix.json +91 -0
  139. diffneusim/data/muscle_fit/wang_mass_volume_14t_axfixlegs01.json +91 -0
  140. diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01.json +91 -0
  141. diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01legs.json +91 -0
  142. diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01lumbar.json +91 -0
  143. diffneusim/data/muscle_fit/wang_mass_volume_14t_lumbfix.json +91 -0
  144. diffneusim/data/muscle_fit/wang_mass_volume_14t_lumbfixlegs01.json +91 -0
  145. diffneusim/data/muscle_fit/wang_mass_volume_14t_n1.json +91 -0
  146. diffneusim/data/muscle_fit/wang_mass_volume_14t_n1a.json +91 -0
  147. diffneusim/data/muscle_fit/wang_mass_volume_14t_n2.json +91 -0
  148. diffneusim/data/muscle_fit/wang_mass_volume_14t_rom23.json +91 -0
  149. diffneusim/data/reference/musclemimic/myofullbody_mimic_sites.json +261 -0
  150. diffneusim/data/reference/pose3/pose3_scone.json +305 -0
  151. diffneusim/data/reference/pose3/pose3_scone.txt +3 -0
  152. diffneusim/data/reference/pose3/pose3_scone_gait.npz +0 -0
  153. diffneusim/data/reference/pose3/pose3_scone_mirror.npz +0 -0
  154. diffneusim/data/reference/pose3/pose3_scone_stand.npz +0 -0
  155. diffneusim/data/reference/x016run/MD5SUMS +241 -0
  156. diffneusim/data/reference/x016run/x016run_states.txt +240 -0
  157. diffneusim/data/reference/x016run/x016run_v3p00_s0_l0.npz +0 -0
  158. diffneusim/data/reference/x016run/x016run_v3p00_s0_l1.npz +0 -0
  159. diffneusim/data/reference/x016run/x016run_v3p00_s0_l2.npz +0 -0
  160. diffneusim/data/reference/x016run/x016run_v3p00_s0_l3.npz +0 -0
  161. diffneusim/data/reference/x016run/x016run_v3p00_s0_r0.npz +0 -0
  162. diffneusim/data/reference/x016run/x016run_v3p00_s0_r1.npz +0 -0
  163. diffneusim/data/reference/x016run/x016run_v3p00_s0_r2.npz +0 -0
  164. diffneusim/data/reference/x016run/x016run_v3p00_s0_r3.npz +0 -0
  165. diffneusim/data/reference/x016run/x016run_v3p00_s1_l0.npz +0 -0
  166. diffneusim/data/reference/x016run/x016run_v3p00_s1_l1.npz +0 -0
  167. diffneusim/data/reference/x016run/x016run_v3p00_s1_l2.npz +0 -0
  168. diffneusim/data/reference/x016run/x016run_v3p00_s1_l3.npz +0 -0
  169. diffneusim/data/reference/x016run/x016run_v3p00_s1_r0.npz +0 -0
  170. diffneusim/data/reference/x016run/x016run_v3p00_s1_r1.npz +0 -0
  171. diffneusim/data/reference/x016run/x016run_v3p00_s1_r2.npz +0 -0
  172. diffneusim/data/reference/x016run/x016run_v3p00_s1_r3.npz +0 -0
  173. diffneusim/data/reference/x016run/x016run_v3p00_s2_l0.npz +0 -0
  174. diffneusim/data/reference/x016run/x016run_v3p00_s2_l1.npz +0 -0
  175. diffneusim/data/reference/x016run/x016run_v3p00_s2_l2.npz +0 -0
  176. diffneusim/data/reference/x016run/x016run_v3p00_s2_l3.npz +0 -0
  177. diffneusim/data/reference/x016run/x016run_v3p00_s2_r0.npz +0 -0
  178. diffneusim/data/reference/x016run/x016run_v3p00_s2_r1.npz +0 -0
  179. diffneusim/data/reference/x016run/x016run_v3p00_s2_r2.npz +0 -0
  180. diffneusim/data/reference/x016run/x016run_v3p00_s2_r3.npz +0 -0
  181. diffneusim/data/reference/x016run/x016run_v3p00_s3_l0.npz +0 -0
  182. diffneusim/data/reference/x016run/x016run_v3p00_s3_l1.npz +0 -0
  183. diffneusim/data/reference/x016run/x016run_v3p00_s3_l2.npz +0 -0
  184. diffneusim/data/reference/x016run/x016run_v3p00_s3_l3.npz +0 -0
  185. diffneusim/data/reference/x016run/x016run_v3p00_s3_r0.npz +0 -0
  186. diffneusim/data/reference/x016run/x016run_v3p00_s3_r1.npz +0 -0
  187. diffneusim/data/reference/x016run/x016run_v3p00_s3_r2.npz +0 -0
  188. diffneusim/data/reference/x016run/x016run_v3p00_s3_r3.npz +0 -0
  189. diffneusim/data/reference/x016run/x016run_v3p00_s4_l0.npz +0 -0
  190. diffneusim/data/reference/x016run/x016run_v3p00_s4_l1.npz +0 -0
  191. diffneusim/data/reference/x016run/x016run_v3p00_s4_l2.npz +0 -0
  192. diffneusim/data/reference/x016run/x016run_v3p00_s4_l3.npz +0 -0
  193. diffneusim/data/reference/x016run/x016run_v3p00_s4_r0.npz +0 -0
  194. diffneusim/data/reference/x016run/x016run_v3p00_s4_r1.npz +0 -0
  195. diffneusim/data/reference/x016run/x016run_v3p00_s4_r2.npz +0 -0
  196. diffneusim/data/reference/x016run/x016run_v3p00_s4_r3.npz +0 -0
  197. diffneusim/data/reference/x016run/x016run_v3p00_s5_l0.npz +0 -0
  198. diffneusim/data/reference/x016run/x016run_v3p00_s5_l1.npz +0 -0
  199. diffneusim/data/reference/x016run/x016run_v3p00_s5_l2.npz +0 -0
  200. diffneusim/data/reference/x016run/x016run_v3p00_s5_l3.npz +0 -0
  201. diffneusim/data/reference/x016run/x016run_v3p00_s5_r0.npz +0 -0
  202. diffneusim/data/reference/x016run/x016run_v3p00_s5_r1.npz +0 -0
  203. diffneusim/data/reference/x016run/x016run_v3p00_s5_r2.npz +0 -0
  204. diffneusim/data/reference/x016run/x016run_v3p00_s5_r3.npz +0 -0
  205. diffneusim/data/reference/x016run/x016run_v3p00_s6_l0.npz +0 -0
  206. diffneusim/data/reference/x016run/x016run_v3p00_s6_l1.npz +0 -0
  207. diffneusim/data/reference/x016run/x016run_v3p00_s6_l2.npz +0 -0
  208. diffneusim/data/reference/x016run/x016run_v3p00_s6_l3.npz +0 -0
  209. diffneusim/data/reference/x016run/x016run_v3p00_s6_r0.npz +0 -0
  210. diffneusim/data/reference/x016run/x016run_v3p00_s6_r1.npz +0 -0
  211. diffneusim/data/reference/x016run/x016run_v3p00_s6_r2.npz +0 -0
  212. diffneusim/data/reference/x016run/x016run_v3p00_s6_r3.npz +0 -0
  213. diffneusim/data/reference/x016run/x016run_v3p00_s7_l0.npz +0 -0
  214. diffneusim/data/reference/x016run/x016run_v3p00_s7_l1.npz +0 -0
  215. diffneusim/data/reference/x016run/x016run_v3p00_s7_l2.npz +0 -0
  216. diffneusim/data/reference/x016run/x016run_v3p00_s7_l3.npz +0 -0
  217. diffneusim/data/reference/x016run/x016run_v3p00_s7_r0.npz +0 -0
  218. diffneusim/data/reference/x016run/x016run_v3p00_s7_r1.npz +0 -0
  219. diffneusim/data/reference/x016run/x016run_v3p00_s7_r2.npz +0 -0
  220. diffneusim/data/reference/x016run/x016run_v3p00_s7_r3.npz +0 -0
  221. diffneusim/data/reference/x016run/x016run_v3p25_s0_l0.npz +0 -0
  222. diffneusim/data/reference/x016run/x016run_v3p25_s0_l1.npz +0 -0
  223. diffneusim/data/reference/x016run/x016run_v3p25_s0_l2.npz +0 -0
  224. diffneusim/data/reference/x016run/x016run_v3p25_s0_l3.npz +0 -0
  225. diffneusim/data/reference/x016run/x016run_v3p25_s0_r0.npz +0 -0
  226. diffneusim/data/reference/x016run/x016run_v3p25_s0_r1.npz +0 -0
  227. diffneusim/data/reference/x016run/x016run_v3p25_s0_r2.npz +0 -0
  228. diffneusim/data/reference/x016run/x016run_v3p25_s0_r3.npz +0 -0
  229. diffneusim/data/reference/x016run/x016run_v3p25_s1_l0.npz +0 -0
  230. diffneusim/data/reference/x016run/x016run_v3p25_s1_l1.npz +0 -0
  231. diffneusim/data/reference/x016run/x016run_v3p25_s1_l2.npz +0 -0
  232. diffneusim/data/reference/x016run/x016run_v3p25_s1_l3.npz +0 -0
  233. diffneusim/data/reference/x016run/x016run_v3p25_s1_r0.npz +0 -0
  234. diffneusim/data/reference/x016run/x016run_v3p25_s1_r1.npz +0 -0
  235. diffneusim/data/reference/x016run/x016run_v3p25_s1_r2.npz +0 -0
  236. diffneusim/data/reference/x016run/x016run_v3p25_s1_r3.npz +0 -0
  237. diffneusim/data/reference/x016run/x016run_v3p25_s2_l0.npz +0 -0
  238. diffneusim/data/reference/x016run/x016run_v3p25_s2_l1.npz +0 -0
  239. diffneusim/data/reference/x016run/x016run_v3p25_s2_l2.npz +0 -0
  240. diffneusim/data/reference/x016run/x016run_v3p25_s2_l3.npz +0 -0
  241. diffneusim/data/reference/x016run/x016run_v3p25_s2_r0.npz +0 -0
  242. diffneusim/data/reference/x016run/x016run_v3p25_s2_r1.npz +0 -0
  243. diffneusim/data/reference/x016run/x016run_v3p25_s2_r2.npz +0 -0
  244. diffneusim/data/reference/x016run/x016run_v3p25_s2_r3.npz +0 -0
  245. diffneusim/data/reference/x016run/x016run_v3p25_s3_l0.npz +0 -0
  246. diffneusim/data/reference/x016run/x016run_v3p25_s3_l1.npz +0 -0
  247. diffneusim/data/reference/x016run/x016run_v3p25_s3_l2.npz +0 -0
  248. diffneusim/data/reference/x016run/x016run_v3p25_s3_l3.npz +0 -0
  249. diffneusim/data/reference/x016run/x016run_v3p25_s3_r0.npz +0 -0
  250. diffneusim/data/reference/x016run/x016run_v3p25_s3_r1.npz +0 -0
  251. diffneusim/data/reference/x016run/x016run_v3p25_s3_r2.npz +0 -0
  252. diffneusim/data/reference/x016run/x016run_v3p25_s3_r3.npz +0 -0
  253. diffneusim/data/reference/x016run/x016run_v3p25_s4_l0.npz +0 -0
  254. diffneusim/data/reference/x016run/x016run_v3p25_s4_l1.npz +0 -0
  255. diffneusim/data/reference/x016run/x016run_v3p25_s4_l2.npz +0 -0
  256. diffneusim/data/reference/x016run/x016run_v3p25_s4_l3.npz +0 -0
  257. diffneusim/data/reference/x016run/x016run_v3p25_s4_r0.npz +0 -0
  258. diffneusim/data/reference/x016run/x016run_v3p25_s4_r1.npz +0 -0
  259. diffneusim/data/reference/x016run/x016run_v3p25_s4_r2.npz +0 -0
  260. diffneusim/data/reference/x016run/x016run_v3p25_s4_r3.npz +0 -0
  261. diffneusim/data/reference/x016run/x016run_v3p25_s5_l0.npz +0 -0
  262. diffneusim/data/reference/x016run/x016run_v3p25_s5_l1.npz +0 -0
  263. diffneusim/data/reference/x016run/x016run_v3p25_s5_l2.npz +0 -0
  264. diffneusim/data/reference/x016run/x016run_v3p25_s5_l3.npz +0 -0
  265. diffneusim/data/reference/x016run/x016run_v3p25_s5_r0.npz +0 -0
  266. diffneusim/data/reference/x016run/x016run_v3p25_s5_r1.npz +0 -0
  267. diffneusim/data/reference/x016run/x016run_v3p25_s5_r2.npz +0 -0
  268. diffneusim/data/reference/x016run/x016run_v3p25_s5_r3.npz +0 -0
  269. diffneusim/data/reference/x016run/x016run_v3p25_s6_l0.npz +0 -0
  270. diffneusim/data/reference/x016run/x016run_v3p25_s6_l1.npz +0 -0
  271. diffneusim/data/reference/x016run/x016run_v3p25_s6_l2.npz +0 -0
  272. diffneusim/data/reference/x016run/x016run_v3p25_s6_l3.npz +0 -0
  273. diffneusim/data/reference/x016run/x016run_v3p25_s6_r0.npz +0 -0
  274. diffneusim/data/reference/x016run/x016run_v3p25_s6_r1.npz +0 -0
  275. diffneusim/data/reference/x016run/x016run_v3p25_s6_r2.npz +0 -0
  276. diffneusim/data/reference/x016run/x016run_v3p25_s6_r3.npz +0 -0
  277. diffneusim/data/reference/x016run/x016run_v3p25_s7_l0.npz +0 -0
  278. diffneusim/data/reference/x016run/x016run_v3p25_s7_l1.npz +0 -0
  279. diffneusim/data/reference/x016run/x016run_v3p25_s7_l2.npz +0 -0
  280. diffneusim/data/reference/x016run/x016run_v3p25_s7_l3.npz +0 -0
  281. diffneusim/data/reference/x016run/x016run_v3p25_s7_r0.npz +0 -0
  282. diffneusim/data/reference/x016run/x016run_v3p25_s7_r1.npz +0 -0
  283. diffneusim/data/reference/x016run/x016run_v3p25_s7_r2.npz +0 -0
  284. diffneusim/data/reference/x016run/x016run_v3p25_s7_r3.npz +0 -0
  285. diffneusim/data/reference/x016run/x016run_v3p50_s0_l0.npz +0 -0
  286. diffneusim/data/reference/x016run/x016run_v3p50_s0_l1.npz +0 -0
  287. diffneusim/data/reference/x016run/x016run_v3p50_s0_l2.npz +0 -0
  288. diffneusim/data/reference/x016run/x016run_v3p50_s0_l3.npz +0 -0
  289. diffneusim/data/reference/x016run/x016run_v3p50_s0_r0.npz +0 -0
  290. diffneusim/data/reference/x016run/x016run_v3p50_s0_r1.npz +0 -0
  291. diffneusim/data/reference/x016run/x016run_v3p50_s0_r2.npz +0 -0
  292. diffneusim/data/reference/x016run/x016run_v3p50_s0_r3.npz +0 -0
  293. diffneusim/data/reference/x016run/x016run_v3p50_s1_l0.npz +0 -0
  294. diffneusim/data/reference/x016run/x016run_v3p50_s1_l1.npz +0 -0
  295. diffneusim/data/reference/x016run/x016run_v3p50_s1_l2.npz +0 -0
  296. diffneusim/data/reference/x016run/x016run_v3p50_s1_l3.npz +0 -0
  297. diffneusim/data/reference/x016run/x016run_v3p50_s1_r0.npz +0 -0
  298. diffneusim/data/reference/x016run/x016run_v3p50_s1_r1.npz +0 -0
  299. diffneusim/data/reference/x016run/x016run_v3p50_s1_r2.npz +0 -0
  300. diffneusim/data/reference/x016run/x016run_v3p50_s1_r3.npz +0 -0
  301. diffneusim/data/reference/x016run/x016run_v3p50_s2_l0.npz +0 -0
  302. diffneusim/data/reference/x016run/x016run_v3p50_s2_l1.npz +0 -0
  303. diffneusim/data/reference/x016run/x016run_v3p50_s2_l2.npz +0 -0
  304. diffneusim/data/reference/x016run/x016run_v3p50_s2_l3.npz +0 -0
  305. diffneusim/data/reference/x016run/x016run_v3p50_s2_r0.npz +0 -0
  306. diffneusim/data/reference/x016run/x016run_v3p50_s2_r1.npz +0 -0
  307. diffneusim/data/reference/x016run/x016run_v3p50_s2_r2.npz +0 -0
  308. diffneusim/data/reference/x016run/x016run_v3p50_s2_r3.npz +0 -0
  309. diffneusim/data/reference/x016run/x016run_v3p50_s3_l0.npz +0 -0
  310. diffneusim/data/reference/x016run/x016run_v3p50_s3_l1.npz +0 -0
  311. diffneusim/data/reference/x016run/x016run_v3p50_s3_l2.npz +0 -0
  312. diffneusim/data/reference/x016run/x016run_v3p50_s3_l3.npz +0 -0
  313. diffneusim/data/reference/x016run/x016run_v3p50_s3_r0.npz +0 -0
  314. diffneusim/data/reference/x016run/x016run_v3p50_s3_r1.npz +0 -0
  315. diffneusim/data/reference/x016run/x016run_v3p50_s3_r2.npz +0 -0
  316. diffneusim/data/reference/x016run/x016run_v3p50_s3_r3.npz +0 -0
  317. diffneusim/data/reference/x016run/x016run_v3p50_s5_l0.npz +0 -0
  318. diffneusim/data/reference/x016run/x016run_v3p50_s5_l1.npz +0 -0
  319. diffneusim/data/reference/x016run/x016run_v3p50_s5_l2.npz +0 -0
  320. diffneusim/data/reference/x016run/x016run_v3p50_s5_l3.npz +0 -0
  321. diffneusim/data/reference/x016run/x016run_v3p50_s5_r0.npz +0 -0
  322. diffneusim/data/reference/x016run/x016run_v3p50_s5_r1.npz +0 -0
  323. diffneusim/data/reference/x016run/x016run_v3p50_s5_r2.npz +0 -0
  324. diffneusim/data/reference/x016run/x016run_v3p50_s5_r3.npz +0 -0
  325. diffneusim/data/reference/x016run/x016run_v3p50_s6_l0.npz +0 -0
  326. diffneusim/data/reference/x016run/x016run_v3p50_s6_l1.npz +0 -0
  327. diffneusim/data/reference/x016run/x016run_v3p50_s6_l2.npz +0 -0
  328. diffneusim/data/reference/x016run/x016run_v3p50_s6_l3.npz +0 -0
  329. diffneusim/data/reference/x016run/x016run_v3p50_s6_r0.npz +0 -0
  330. diffneusim/data/reference/x016run/x016run_v3p50_s6_r1.npz +0 -0
  331. diffneusim/data/reference/x016run/x016run_v3p50_s6_r2.npz +0 -0
  332. diffneusim/data/reference/x016run/x016run_v3p50_s6_r3.npz +0 -0
  333. diffneusim/data/reference/x016run/x016run_v3p50_s7_l0.npz +0 -0
  334. diffneusim/data/reference/x016run/x016run_v3p50_s7_l1.npz +0 -0
  335. diffneusim/data/reference/x016run/x016run_v3p50_s7_l2.npz +0 -0
  336. diffneusim/data/reference/x016run/x016run_v3p50_s7_l3.npz +0 -0
  337. diffneusim/data/reference/x016run/x016run_v3p50_s7_r0.npz +0 -0
  338. diffneusim/data/reference/x016run/x016run_v3p50_s7_r1.npz +0 -0
  339. diffneusim/data/reference/x016run/x016run_v3p50_s7_r2.npz +0 -0
  340. diffneusim/data/reference/x016run/x016run_v3p50_s7_r3.npz +0 -0
  341. diffneusim/data/reference/x016run/x016run_v3p75_s0_l0.npz +0 -0
  342. diffneusim/data/reference/x016run/x016run_v3p75_s0_l1.npz +0 -0
  343. diffneusim/data/reference/x016run/x016run_v3p75_s0_l2.npz +0 -0
  344. diffneusim/data/reference/x016run/x016run_v3p75_s0_l3.npz +0 -0
  345. diffneusim/data/reference/x016run/x016run_v3p75_s0_r0.npz +0 -0
  346. diffneusim/data/reference/x016run/x016run_v3p75_s0_r1.npz +0 -0
  347. diffneusim/data/reference/x016run/x016run_v3p75_s0_r2.npz +0 -0
  348. diffneusim/data/reference/x016run/x016run_v3p75_s0_r3.npz +0 -0
  349. diffneusim/data/reference/x016run/x016run_v3p75_s1_l0.npz +0 -0
  350. diffneusim/data/reference/x016run/x016run_v3p75_s1_l1.npz +0 -0
  351. diffneusim/data/reference/x016run/x016run_v3p75_s1_l2.npz +0 -0
  352. diffneusim/data/reference/x016run/x016run_v3p75_s1_l3.npz +0 -0
  353. diffneusim/data/reference/x016run/x016run_v3p75_s1_r0.npz +0 -0
  354. diffneusim/data/reference/x016run/x016run_v3p75_s1_r1.npz +0 -0
  355. diffneusim/data/reference/x016run/x016run_v3p75_s1_r2.npz +0 -0
  356. diffneusim/data/reference/x016run/x016run_v3p75_s1_r3.npz +0 -0
  357. diffneusim/data/reference/x016run/x016run_v3p75_s2_l0.npz +0 -0
  358. diffneusim/data/reference/x016run/x016run_v3p75_s2_l1.npz +0 -0
  359. diffneusim/data/reference/x016run/x016run_v3p75_s2_l2.npz +0 -0
  360. diffneusim/data/reference/x016run/x016run_v3p75_s2_l3.npz +0 -0
  361. diffneusim/data/reference/x016run/x016run_v3p75_s2_r0.npz +0 -0
  362. diffneusim/data/reference/x016run/x016run_v3p75_s2_r1.npz +0 -0
  363. diffneusim/data/reference/x016run/x016run_v3p75_s2_r2.npz +0 -0
  364. diffneusim/data/reference/x016run/x016run_v3p75_s2_r3.npz +0 -0
  365. diffneusim/data/reference/x016run/x016run_v3p75_s3_l0.npz +0 -0
  366. diffneusim/data/reference/x016run/x016run_v3p75_s3_l1.npz +0 -0
  367. diffneusim/data/reference/x016run/x016run_v3p75_s3_l2.npz +0 -0
  368. diffneusim/data/reference/x016run/x016run_v3p75_s3_l3.npz +0 -0
  369. diffneusim/data/reference/x016run/x016run_v3p75_s3_r0.npz +0 -0
  370. diffneusim/data/reference/x016run/x016run_v3p75_s3_r1.npz +0 -0
  371. diffneusim/data/reference/x016run/x016run_v3p75_s3_r2.npz +0 -0
  372. diffneusim/data/reference/x016run/x016run_v3p75_s3_r3.npz +0 -0
  373. diffneusim/data/reference/x016run/x016run_v3p75_s5_l0.npz +0 -0
  374. diffneusim/data/reference/x016run/x016run_v3p75_s5_l1.npz +0 -0
  375. diffneusim/data/reference/x016run/x016run_v3p75_s5_l2.npz +0 -0
  376. diffneusim/data/reference/x016run/x016run_v3p75_s5_l3.npz +0 -0
  377. diffneusim/data/reference/x016run/x016run_v3p75_s5_r0.npz +0 -0
  378. diffneusim/data/reference/x016run/x016run_v3p75_s5_r1.npz +0 -0
  379. diffneusim/data/reference/x016run/x016run_v3p75_s5_r2.npz +0 -0
  380. diffneusim/data/reference/x016run/x016run_v3p75_s5_r3.npz +0 -0
  381. diffneusim/data/reference/x016run/x016run_v3p75_s6_l0.npz +0 -0
  382. diffneusim/data/reference/x016run/x016run_v3p75_s6_l1.npz +0 -0
  383. diffneusim/data/reference/x016run/x016run_v3p75_s6_l2.npz +0 -0
  384. diffneusim/data/reference/x016run/x016run_v3p75_s6_l3.npz +0 -0
  385. diffneusim/data/reference/x016run/x016run_v3p75_s6_r0.npz +0 -0
  386. diffneusim/data/reference/x016run/x016run_v3p75_s6_r1.npz +0 -0
  387. diffneusim/data/reference/x016run/x016run_v3p75_s6_r2.npz +0 -0
  388. diffneusim/data/reference/x016run/x016run_v3p75_s6_r3.npz +0 -0
  389. diffneusim/data/reference/x016run/x016run_v3p75_s7_l0.npz +0 -0
  390. diffneusim/data/reference/x016run/x016run_v3p75_s7_l1.npz +0 -0
  391. diffneusim/data/reference/x016run/x016run_v3p75_s7_l2.npz +0 -0
  392. diffneusim/data/reference/x016run/x016run_v3p75_s7_l3.npz +0 -0
  393. diffneusim/data/reference/x016run/x016run_v3p75_s7_r0.npz +0 -0
  394. diffneusim/data/reference/x016run/x016run_v3p75_s7_r1.npz +0 -0
  395. diffneusim/data/reference/x016run/x016run_v3p75_s7_r2.npz +0 -0
  396. diffneusim/data/reference/x016run/x016run_v3p75_s7_r3.npz +0 -0
  397. diffneusim/data/state_prior/lumbar_poly_fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
  398. diffneusim/engine/__init__.py +0 -0
  399. diffneusim/engine/build_tag.py +52 -0
  400. diffneusim/engine/case_tables.py +46 -0
  401. diffneusim/engine/d16_body.py +80 -0
  402. diffneusim/engine/engine14.py +367 -0
  403. diffneusim/engine/gen_split.py +159 -0
  404. diffneusim/engine/hand_format.py +69 -0
  405. diffneusim/engine/live14.py +149 -0
  406. diffneusim/engine/phase_b_tree.py +137 -0
  407. diffneusim/engine/soft14.py +130 -0
  408. diffneusim/engine/soft_capi.py +373 -0
  409. diffneusim/engine/soft_engine.py +165 -0
  410. diffneusim/engine/step14.py +132 -0
  411. diffneusim/engine/tape_format.py +89 -0
  412. diffneusim/engine/x14cpu.py +163 -0
  413. diffneusim/env/__init__.py +0 -0
  414. diffneusim/env/absent.py +20 -0
  415. diffneusim/env/cpu14.py +105 -0
  416. diffneusim/env/e0loop14.py +224 -0
  417. diffneusim/env/env14.py +568 -0
  418. diffneusim/env/kin_contact14.py +193 -0
  419. diffneusim/env/mimic_sites_x14.json +366 -0
  420. diffneusim/env/old_count.py +78 -0
  421. diffneusim/env/rew14.py +114 -0
  422. diffneusim/env/rew14_hook.py +105 -0
  423. diffneusim/g1/__init__.py +1 -0
  424. diffneusim/g1/arm_a2.py +165 -0
  425. diffneusim/g1/arm_a3.py +576 -0
  426. diffneusim/g1/read_a3.py +79 -0
  427. diffneusim/g1/rg1_read.py +89 -0
  428. diffneusim/model/__init__.py +66 -0
  429. diffneusim/model/case.py +17 -0
  430. diffneusim/model/dnmodel.py +79 -0
  431. diffneusim/model/fuse_fixed.py +281 -0
  432. diffneusim/model/monitor.py +834 -0
  433. diffneusim/models/BODIES.toml +48 -0
  434. diffneusim/models/MANIFEST.toml +979 -0
  435. diffneusim/models/cases/G290/case.bin +0 -0
  436. diffneusim/models/cases/G290/case.json +1 -0
  437. diffneusim/models/cases/G356-SRC/case.bin +0 -0
  438. diffneusim/models/cases/G356-SRC/case.json +1 -0
  439. diffneusim/models/cases/G416/case.bin +0 -0
  440. diffneusim/models/cases/G416/case.json +1 -0
  441. diffneusim/models/cases/M290C-SRC/case.bin +0 -0
  442. diffneusim/models/cases/M290C-SRC/case.json +1 -0
  443. diffneusim/models/cases/M290R-SRC/case.bin +0 -0
  444. diffneusim/models/cases/M290R-SRC/case.json +1 -0
  445. diffneusim/models/cases/M356C-SRC/case.bin +0 -0
  446. diffneusim/models/cases/M356C-SRC/case.json +1 -0
  447. diffneusim/models/cases/M356R-SRC/case.bin +0 -0
  448. diffneusim/models/cases/M356R-SRC/case.json +1 -0
  449. diffneusim/models/cases/M416C-SRC/case.bin +0 -0
  450. diffneusim/models/cases/M416C-SRC/case.json +1 -0
  451. diffneusim/models/derived/d16_expanded_62f77a4bb16b1e67_mmfloor.xml +673 -0
  452. diffneusim/models/derived/d16_expanded_a1e8b196b2cd7b3c_mmfloor.xml +673 -0
  453. diffneusim/models/derived/d16_soft_law_019e20820f8633b9_mmfloor.json +7844 -0
  454. diffneusim/models/derived/d16_soft_law_62f77a4bb16b1e67_mmfloor.json +16855 -0
  455. diffneusim/models/derived/d16_soft_law_77dbb7213f26e821_mmfloor_rampsb3l_n6t12.json +7883 -0
  456. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rampsb3l_n6t12.json +7883 -0
  457. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsd05_n6t12.json +7868 -0
  458. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsdef_n6t12.json +7868 -0
  459. diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsmjd_n6t12.json +7868 -0
  460. diffneusim/models/derived/d16_soft_law_a1e8b196b2cd7b3c_mmfloor_rampsb3l_n6t12.json +16894 -0
  461. diffneusim/models/derived/d16_soft_law_a944653edd642082_mmfloor.json +12655 -0
  462. diffneusim/models/derived/d16_soft_law_a944653edd642082_mmfloor_rampsb3l_n6t12.json +12700 -0
  463. diffneusim/models/derived/unitree_g1_soft_law.json +15580 -0
  464. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +28913 -0
  465. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
  466. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.dnmodel +29202 -0
  467. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid_qk.txt +1 -0
  468. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfixlegs01.dnmodel +1 -0
  469. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
  470. diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
  471. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +46970 -0
  472. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
  473. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
  474. diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
  475. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +38570 -0
  476. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
  477. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.dnmodel +38923 -0
  478. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid_qk.txt +1 -0
  479. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
  480. diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
  481. diffneusim/models/fullbody_meshes/1mc.stl +0 -0
  482. diffneusim/models/fullbody_meshes/2distph.stl +0 -0
  483. diffneusim/models/fullbody_meshes/2mc.stl +0 -0
  484. diffneusim/models/fullbody_meshes/2midph.stl +0 -0
  485. diffneusim/models/fullbody_meshes/2proxph.stl +0 -0
  486. diffneusim/models/fullbody_meshes/3distph.stl +0 -0
  487. diffneusim/models/fullbody_meshes/3mc.stl +0 -0
  488. diffneusim/models/fullbody_meshes/3midph.stl +0 -0
  489. diffneusim/models/fullbody_meshes/3proxph.stl +0 -0
  490. diffneusim/models/fullbody_meshes/4distph.stl +0 -0
  491. diffneusim/models/fullbody_meshes/4mc.stl +0 -0
  492. diffneusim/models/fullbody_meshes/4midph.stl +0 -0
  493. diffneusim/models/fullbody_meshes/4proxph.stl +0 -0
  494. diffneusim/models/fullbody_meshes/5distph.stl +0 -0
  495. diffneusim/models/fullbody_meshes/5mc.stl +0 -0
  496. diffneusim/models/fullbody_meshes/5midph.stl +0 -0
  497. diffneusim/models/fullbody_meshes/5proxph.stl +0 -0
  498. diffneusim/models/fullbody_meshes/NOTICE +2 -0
  499. diffneusim/models/fullbody_meshes/capitate.stl +0 -0
  500. diffneusim/models/fullbody_meshes/clavicle.stl +0 -0
  501. diffneusim/models/fullbody_meshes/hamate.stl +0 -0
  502. diffneusim/models/fullbody_meshes/hat_cervical.stl +0 -0
  503. diffneusim/models/fullbody_meshes/hat_jaw.stl +0 -0
  504. diffneusim/models/fullbody_meshes/hat_skull.stl +0 -0
  505. diffneusim/models/fullbody_meshes/humerus.stl +0 -0
  506. diffneusim/models/fullbody_meshes/l_bofoot.stl +0 -0
  507. diffneusim/models/fullbody_meshes/l_femur.stl +0 -0
  508. diffneusim/models/fullbody_meshes/l_fibula.stl +0 -0
  509. diffneusim/models/fullbody_meshes/l_foot.stl +0 -0
  510. diffneusim/models/fullbody_meshes/l_patella.stl +0 -0
  511. diffneusim/models/fullbody_meshes/l_pelvis.stl +0 -0
  512. diffneusim/models/fullbody_meshes/l_talus.stl +0 -0
  513. diffneusim/models/fullbody_meshes/l_tibia.stl +0 -0
  514. diffneusim/models/fullbody_meshes/lumbar1.stl +0 -0
  515. diffneusim/models/fullbody_meshes/lumbar2.stl +0 -0
  516. diffneusim/models/fullbody_meshes/lumbar3.stl +0 -0
  517. diffneusim/models/fullbody_meshes/lumbar4.stl +0 -0
  518. diffneusim/models/fullbody_meshes/lumbar5.stl +0 -0
  519. diffneusim/models/fullbody_meshes/lunate.stl +0 -0
  520. diffneusim/models/fullbody_meshes/pisiform.stl +0 -0
  521. diffneusim/models/fullbody_meshes/r_bofoot.stl +0 -0
  522. diffneusim/models/fullbody_meshes/r_femur.stl +0 -0
  523. diffneusim/models/fullbody_meshes/r_fibula.stl +0 -0
  524. diffneusim/models/fullbody_meshes/r_foot.stl +0 -0
  525. diffneusim/models/fullbody_meshes/r_patella.stl +0 -0
  526. diffneusim/models/fullbody_meshes/r_pelvis.stl +0 -0
  527. diffneusim/models/fullbody_meshes/r_talus.stl +0 -0
  528. diffneusim/models/fullbody_meshes/r_tibia.stl +0 -0
  529. diffneusim/models/fullbody_meshes/radius.stl +0 -0
  530. diffneusim/models/fullbody_meshes/sacrum.stl +0 -0
  531. diffneusim/models/fullbody_meshes/scaphoid.stl +0 -0
  532. diffneusim/models/fullbody_meshes/scapula.stl +0 -0
  533. diffneusim/models/fullbody_meshes/thoracic10_s.stl +0 -0
  534. diffneusim/models/fullbody_meshes/thoracic11_s.stl +0 -0
  535. diffneusim/models/fullbody_meshes/thoracic12_s.stl +0 -0
  536. diffneusim/models/fullbody_meshes/thoracic1_s.stl +0 -0
  537. diffneusim/models/fullbody_meshes/thoracic2_s.stl +0 -0
  538. diffneusim/models/fullbody_meshes/thoracic3_s.stl +0 -0
  539. diffneusim/models/fullbody_meshes/thoracic4_s.stl +0 -0
  540. diffneusim/models/fullbody_meshes/thoracic5_s.stl +0 -0
  541. diffneusim/models/fullbody_meshes/thoracic6_s.stl +0 -0
  542. diffneusim/models/fullbody_meshes/thoracic7_s.stl +0 -0
  543. diffneusim/models/fullbody_meshes/thoracic8_s.stl +0 -0
  544. diffneusim/models/fullbody_meshes/thoracic9_s.stl +0 -0
  545. diffneusim/models/fullbody_meshes/thorax.stl +0 -0
  546. diffneusim/models/fullbody_meshes/thumbdist.stl +0 -0
  547. diffneusim/models/fullbody_meshes/thumbprox.stl +0 -0
  548. diffneusim/models/fullbody_meshes/trapezium.stl +0 -0
  549. diffneusim/models/fullbody_meshes/trapezoid.stl +0 -0
  550. diffneusim/models/fullbody_meshes/triquetrum.stl +0 -0
  551. diffneusim/models/fullbody_meshes/ulna.stl +0 -0
  552. diffneusim/models/source/myo_fullbody/UPSTREAM.md +91 -0
  553. diffneusim/models/source/myoleg/UPSTREAM.md +52 -0
  554. diffneusim/models/source/unitree_g1/LICENSE.mjlab +202 -0
  555. diffneusim/models/source/unitree_g1/UPSTREAM.md +38 -0
  556. diffneusim/models/source/unitree_g1/assets/head_link.STL +0 -0
  557. diffneusim/models/source/unitree_g1/assets/left_ankle_pitch_link.STL +0 -0
  558. diffneusim/models/source/unitree_g1/assets/left_ankle_roll_link.STL +0 -0
  559. diffneusim/models/source/unitree_g1/assets/left_elbow_link.STL +0 -0
  560. diffneusim/models/source/unitree_g1/assets/left_hip_pitch_link.STL +0 -0
  561. diffneusim/models/source/unitree_g1/assets/left_hip_roll_link.STL +0 -0
  562. diffneusim/models/source/unitree_g1/assets/left_hip_yaw_link.STL +0 -0
  563. diffneusim/models/source/unitree_g1/assets/left_knee_link.STL +0 -0
  564. diffneusim/models/source/unitree_g1/assets/left_rubber_hand.STL +0 -0
  565. diffneusim/models/source/unitree_g1/assets/left_shoulder_pitch_link.STL +0 -0
  566. diffneusim/models/source/unitree_g1/assets/left_shoulder_roll_link.STL +0 -0
  567. diffneusim/models/source/unitree_g1/assets/left_shoulder_yaw_link.STL +0 -0
  568. diffneusim/models/source/unitree_g1/assets/left_wrist_pitch_link.STL +0 -0
  569. diffneusim/models/source/unitree_g1/assets/left_wrist_roll_link.STL +0 -0
  570. diffneusim/models/source/unitree_g1/assets/left_wrist_yaw_link.STL +0 -0
  571. diffneusim/models/source/unitree_g1/assets/logo_link.STL +0 -0
  572. diffneusim/models/source/unitree_g1/assets/pelvis.STL +0 -0
  573. diffneusim/models/source/unitree_g1/assets/pelvis_contour_link.STL +0 -0
  574. diffneusim/models/source/unitree_g1/assets/right_ankle_pitch_link.STL +0 -0
  575. diffneusim/models/source/unitree_g1/assets/right_ankle_roll_link.STL +0 -0
  576. diffneusim/models/source/unitree_g1/assets/right_elbow_link.STL +0 -0
  577. diffneusim/models/source/unitree_g1/assets/right_hip_pitch_link.STL +0 -0
  578. diffneusim/models/source/unitree_g1/assets/right_hip_roll_link.STL +0 -0
  579. diffneusim/models/source/unitree_g1/assets/right_hip_yaw_link.STL +0 -0
  580. diffneusim/models/source/unitree_g1/assets/right_knee_link.STL +0 -0
  581. diffneusim/models/source/unitree_g1/assets/right_rubber_hand.STL +0 -0
  582. diffneusim/models/source/unitree_g1/assets/right_shoulder_pitch_link.STL +0 -0
  583. diffneusim/models/source/unitree_g1/assets/right_shoulder_roll_link.STL +0 -0
  584. diffneusim/models/source/unitree_g1/assets/right_shoulder_yaw_link.STL +0 -0
  585. diffneusim/models/source/unitree_g1/assets/right_wrist_pitch_link.STL +0 -0
  586. diffneusim/models/source/unitree_g1/assets/right_wrist_roll_link.STL +0 -0
  587. diffneusim/models/source/unitree_g1/assets/right_wrist_yaw_link.STL +0 -0
  588. diffneusim/models/source/unitree_g1/assets/torso_link_rev_1_0.STL +0 -0
  589. diffneusim/models/source/unitree_g1/assets/waist_roll_link_rev_1_0.STL +0 -0
  590. diffneusim/models/source/unitree_g1/assets/waist_yaw_link_rev_1_0.STL +0 -0
  591. diffneusim/models/source/unitree_g1/dump_mjlab_reference.py +30 -0
  592. diffneusim/models/source/unitree_g1/g1.xml +308 -0
  593. diffneusim/models/source/unitree_g1/g1_constants.py +298 -0
  594. diffneusim/models/source/unitree_g1/mjlab_compiled_reference.json +857 -0
  595. diffneusim/models/unitree_g1.dnmodel +4393 -0
  596. diffneusim/models/unitree_g1_selfcol.dnmodel +20824 -0
  597. diffneusim/rl/__init__.py +2 -0
  598. diffneusim/rl/dynsyn_layer.py +146 -0
  599. diffneusim/rl/footstep_plan.py +337 -0
  600. diffneusim/rl/g1_bm_env.py +572 -0
  601. diffneusim/rl/g1_bm_eval.py +168 -0
  602. diffneusim/rl/g1_bm_fused.py +275 -0
  603. diffneusim/rl/g1_bm_ppo.py +622 -0
  604. diffneusim/rl/g1_bm_sapo.py +551 -0
  605. diffneusim/rl/g1_ppo.py +395 -0
  606. diffneusim/rl/g1_sapo_soft.py +240 -0
  607. diffneusim/rl/g1_soft_env.py +452 -0
  608. diffneusim/rl/g1_soft_grad.py +145 -0
  609. diffneusim/rl/geyer_curves_torch.py +108 -0
  610. diffneusim/rl/gpu_fullbody_vec_env.py +1241 -0
  611. diffneusim/rl/imitation.py +2027 -0
  612. diffneusim/rl/imitation_reward_v2.py +248 -0
  613. diffneusim/rl/imitation_reward_v3.py +349 -0
  614. diffneusim/rl/latent_task.py +175 -0
  615. diffneusim/rl/llc_reward.py +316 -0
  616. diffneusim/rl/millard_curves_torch.py +154 -0
  617. diffneusim/rl/mirror_symmetry.py +212 -0
  618. diffneusim/rl/model_path.py +35 -0
  619. diffneusim/rl/mvae_recon.py +123 -0
  620. diffneusim/rl/nets_shac.py +599 -0
  621. diffneusim/rl/reset_pool.py +154 -0
  622. diffneusim/rl/sapo_capture.py +873 -0
  623. diffneusim/rl/sapo_vec.py +1051 -0
  624. diffneusim/rl/shac_vec.py +346 -0
  625. diffneusim/rl/state_prior.py +151 -0
  626. diffneusim/rl/step_library.py +105 -0
  627. diffneusim/rl/task_walk_env.py +1793 -0
  628. diffneusim/rl/task_walk_reward.py +3300 -0
  629. diffneusim/run.py +23 -0
  630. diffneusim/run_env.py +46 -0
  631. diffneusim/tasks/__init__.py +147 -0
  632. diffneusim/tasks/legacy_names.py +63 -0
  633. diffneusim/tasks/paths.py +79 -0
  634. diffneusim/tasks/settings.py +202 -0
  635. diffneusim/third_party/instantmimic_947430ee/LICENSE +202 -0
  636. diffneusim/third_party/instantmimic_947430ee/NOTICE +19 -0
  637. diffneusim/third_party/instantmimic_947430ee/README.md +31 -0
  638. diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/benchmark_protocol.py +106 -0
  639. diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/metrics.py +214 -0
  640. diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/reference.py +513 -0
  641. diffneusim/third_party/instantmimic_947430ee/instantmimic/motion/quaternion.py +193 -0
  642. diffneusim/train/__init__.py +0 -0
  643. diffneusim/train/eval_ckpt.py +239 -0
  644. diffneusim/train/eval_mimic.py +133 -0
  645. diffneusim/train/gait_report.py +203 -0
  646. diffneusim/train/gcot_chain.py +51 -0
  647. diffneusim/train/levers.py +135 -0
  648. diffneusim/train/masked_reset.py +314 -0
  649. diffneusim/train/rl_algorithm_suite.py +917 -0
  650. diffneusim/train/train14.py +240 -0
  651. diffneusim/train/train_tw14.py +674 -0
  652. diffneusim/viz/__init__.py +5 -0
  653. diffneusim/viz/__main__.py +41 -0
  654. diffneusim/viz/camera.py +115 -0
  655. diffneusim/viz/dnrec.py +118 -0
  656. diffneusim/viz/dnrec_io.py +686 -0
  657. diffneusim/viz/hud.py +565 -0
  658. diffneusim/viz/meshes.py +458 -0
  659. diffneusim/viz/play.py +237 -0
  660. diffneusim/viz/record.py +74 -0
  661. diffneusim/viz/render.py +1402 -0
  662. diffneusim/viz/renderer.py +268 -0
  663. diffneusim/viz/rl_env_render.py +635 -0
  664. diffneusim/viz/snapshot.py +54 -0
  665. diffneusim/viz/strobe.py +124 -0
  666. diffneusim/viz/to_mp4.py +58 -0
  667. diffneusim/viz/ui.py +481 -0
  668. diffneusim/viz/viewer.py +2086 -0
  669. diffneusim-1.0.0.dist-info/METADATA +226 -0
  670. diffneusim-1.0.0.dist-info/RECORD +682 -0
  671. diffneusim-1.0.0.dist-info/WHEEL +5 -0
  672. diffneusim-1.0.0.dist-info/licenses/LICENSE +201 -0
  673. diffneusim-1.0.0.dist-info/licenses/LICENSES/BSD-3-Clause-NC-ARMS-hand-wrist-4.3.txt +20 -0
  674. diffneusim-1.0.0.dist-info/licenses/LICENSES/BSD-3-Clause-NC-MoBL-ARMS.txt +25 -0
  675. diffneusim-1.0.0.dist-info/licenses/LICENSES/CC-BY-3.0-OpenSim-geometry.txt +25 -0
  676. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Christophy2012-lumbarspine.txt +10 -0
  677. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Lai2017-model-high-flex.txt +10 -0
  678. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Lee2015-hand_muscle.txt +11 -0
  679. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Rajagopal2016-full_body.txt +11 -0
  680. diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Uhlrich2022-fbmodpassivecal.txt +10 -0
  681. diffneusim-1.0.0.dist-info/licenses/NOTICE +274 -0
  682. diffneusim-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1793 @@
1
+ """Env-side wiring for the reference-free task-walking reward (arXiv:2603.04166), shared by every model.
2
+
3
+ `task_walk_reward.TaskWalkReward` is the reward math; this is everything the ENV has to do around it --
4
+ the start-state grounding, the slope curriculum, the commanded-speed schedule, the knee-load readout, and
5
+ the termination flag. All of it is model-agnostic given a `TaskWalkSpec`, so it lives here ONCE and both
6
+ `GpuFullBodyVecEnv` and `GpuMyoLeg26VecEnv` mix it in rather than carrying two copies that drift.
7
+
8
+ The mixin expects the host env to provide, by the time `_tw_setup` is called: `nq`, `nm`, `num_envs`,
9
+ `device`, `rng`, `model`, `sim`, `_monitor`, `_train_steps`, the contact count as either `ncon` or
10
+ `ncontact` (the two envs spell it differently), and the state tensors `q`, `qd`, `z`.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import dataclasses
15
+ import math
16
+ import os
17
+
18
+ import torch
19
+
20
+ from diffneusim.env.absent import Absent
21
+ from diffneusim.model import read_model as _load_dnmodel
22
+
23
+ _bridge = gpu_bridge = Absent("gpu_bridge") # the earlier engine's contact force (diffneusim/env/absent.py)
24
+ _mtu_gpu = Absent("mtu_gpu") # the earlier engine's ground normals
25
+ from diffneusim.model.monitor import _quat_rotate_batched
26
+
27
+
28
+ _M32 = 0xFFFFFFFF
29
+
30
+
31
+ def _mul32(x, c):
32
+ """(x c) mod 2^32 for int64 x in [0, 2^32) and a constant c < 2^32, with every intermediate below 2^49 (no int64 overflow)"""
33
+ return (x * (c & 0xFFFF) + (((x * (c >> 16)) & 0xFFFF) << 16)) & _M32
34
+
35
+
36
+ def _fmix32(h):
37
+ """MurmurHash3's 32-bit finalizer (a bijection on [0, 2^32)) on int64 tensors"""
38
+ h = h & _M32
39
+ h = h ^ (h >> 16)
40
+ h = _mul32(h, 0x85EBCA6B)
41
+ h = h ^ (h >> 13)
42
+ h = _mul32(h, 0xC2B2AE35)
43
+ return h ^ (h >> 16)
44
+
45
+
46
+ def heading_due_per_metre(s, next_s, v, dt, per_m):
47
+ """One control step of the per-metre random plan: the commanded distance s advances by v dt; an env is DUE when it reaches
48
+ next_s, which then moves on by per_m. Returns (s, due, next_s)."""
49
+ s = s + v * dt
50
+ due = s >= next_s - 1e-9
51
+ return s, due, torch.where(due, next_s + per_m, next_s)
52
+
53
+
54
+ @dataclasses.dataclass(frozen=True)
55
+ class TaskWalkSpec:
56
+ """The per-model facts the task-walk wiring needs. Everything else is derived.
57
+
58
+ feet (right, left) body indices whose height the fall test measures the COM against --
59
+ the authors use the calcanei.
60
+ contact_bodies every body carrying a foot contact sphere (the grounding FKs exactly these).
61
+ right_bodies which of those belong to the RIGHT foot, for the per-side GRF split.
62
+ foot_bodies every body carrying a contact sphere that belongs to a FOOT -- calcanei AND toes.
63
+ Distinct from `feet` (the calcanei alone) and from `contact_bodies` (which also
64
+ carries the pelvis/torso spheres that exist to catch a fall). Only read by the
65
+ TASKWALK_FALL_FOOT_GEOM gate; empty means that gate cannot be used on this model.
66
+ knee_muscles muscle base names (no _r/_l suffix) that SPAN the knee; their tension is the
67
+ tibiofemoral compression proxy. Empty = the model has no such map, and w_knee_load must
68
+ then be 0.
69
+ root_from_world rows of the matrix taking a WORLD displacement to the root joint's TRANSLATION qpos
70
+ ordering. Identity for the full body, whose free joint is plain (x, y, z). NOT
71
+ identity for myoleg26, whose free joint is ordered (x, z, -y) -- so the grounding
72
+ shift, which is computed against a world plane normal, has to be mapped before it is
73
+ subtracted from q[0:3]. Getting this wrong is silent on flat ground (the shift is
74
+ along one axis) and wrong on every slope.
75
+ """
76
+ feet: tuple
77
+ contact_bodies: tuple
78
+ right_bodies: tuple
79
+ foot_bodies: tuple = ()
80
+ knee_muscles: tuple = ()
81
+ root_from_world: tuple = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))
82
+
83
+
84
+ def _tw_parse_w_sched(tw):
85
+ """The TASKWALK_W_* weight schedules: [(name, start, end, steps, after)] and the optional SECOND segments
86
+ [(name, end, end2, steps2, after2)]. A schedule walks the weight from its start value to _END over _STEPS control steps
87
+ beginning at _AFTER; _END2 / _STEPS2 / _AFTER2 then walk it from _END to _END2, starting no earlier than the first segment's
88
+ end. WHY THE SECOND SEGMENT (2026-10-11, docs/training/gradient-field-ioc.md STATE 17:1x): the toe spring must ramp IN with
89
+ the other end-weight terms (on from step 0 the cold learner chose a flat-foot crouch, the fifth cold screen) and then OUT
90
+ once the heel-down gait has formed (it holds the push-off down inside that basin, the cold-2 warm probe). Without _END2
91
+ every schedule is the single ramp it always was."""
92
+ sched, sched2 = [], []
93
+ for _name in [n for n in dir(tw) if n.startswith("w_")]:
94
+ _v = getattr(tw, _name, None)
95
+ if not isinstance(_v, float):
96
+ continue
97
+ _var = "TASKWALK_" + _name.upper() # w_head_accel -> TASKWALK_W_HEAD_ACCEL
98
+ _end = os.environ.get(_var + "_END")
99
+ if _end is None:
100
+ assert os.environ.get(_var + "_END2") is None, f"{_var}_END2 needs a first segment ({_var}_END / _STEPS)"
101
+ continue
102
+ _steps = int(os.environ.get(_var + "_STEPS", "0"))
103
+ _after = int(os.environ.get(_var + "_AFTER", "0"))
104
+ assert _steps > 0, (
105
+ f"{_var}_END needs {_var}_STEPS > 0 -- a schedule with no length is a silent step change "
106
+ f"at step {_after}, which is just a different constant.")
107
+ assert _steps + _after <= 200000, (
108
+ f"{_var}_STEPS={_steps} + _AFTER={_after} counts CONTROL steps (32 per epoch at "
109
+ f"steps_num=32), so this is {(_steps + _after) // 32} epochs -- longer than any run on "
110
+ f"this line. Did you multiply by n_env? 400 epochs is 12800.")
111
+ sched.append((_name, _v, float(_end), _steps, _after))
112
+ _end2 = os.environ.get(_var + "_END2")
113
+ if _end2 is not None:
114
+ _steps2 = int(os.environ.get(_var + "_STEPS2", "0"))
115
+ _after2 = int(os.environ.get(_var + "_AFTER2", "0"))
116
+ assert _steps2 > 0, f"{_var}_END2 needs {_var}_STEPS2 > 0"
117
+ assert _after2 >= _after + _steps, (
118
+ f"{_var}_AFTER2={_after2} starts before the first segment ends at {_after + _steps}")
119
+ assert _steps2 + _after2 <= 200000, f"{_var}_STEPS2 + _AFTER2 = {_steps2 + _after2} control steps is too long"
120
+ sched2.append((_name, float(_end), float(_end2), _steps2, _after2))
121
+ return sched, sched2
122
+
123
+
124
+ def speed_shortfall_step(buf, progress, x, v_cmd, frac, grace_steps, control_dt):
125
+ """M4's test for one control step (TASKWALK_SPEED_TERM_FRAC, _tw_setup says why), in place on the ring buffer buf (W, n): reads x W
126
+ steps ago at slot progress % W, writes this step's x there, and returns the envs whose trailing speed (x - x_old) / (W control_dt) is
127
+ below frac x v_cmd once progress > max(grace_steps, W) (by then W fresh samples since the reset are in the buffer). x, v_cmd: (n,);
128
+ progress: (n,) long, the env's step count since its reset (1 at the first step). No host read. Shared with the unit test."""
129
+ W = buf.shape[0]
130
+ k = (progress % W).unsqueeze(0)
131
+ x_old = buf.gather(0, k).squeeze(0)
132
+ buf.scatter_(0, k, x.to(buf.dtype).unsqueeze(0))
133
+ v_tr = (x.to(buf.dtype) - x_old) / (W * control_dt)
134
+ return (progress > max(grace_steps, W)) & (v_tr < frac * v_cmd.to(buf.dtype))
135
+
136
+
137
+ class TaskWalkEnvMixin:
138
+ """Mix in BEFORE the env's own bases. Every method is inert unless `_tw_setup` ran."""
139
+
140
+ # ---------------------------------------------------------------- setup
141
+
142
+ def _tw_setup(self, spec: TaskWalkSpec):
143
+ from diffneusim.rl.task_walk_reward import TaskWalkReward
144
+ self._tw_spec = spec
145
+ self.taskwalk = TaskWalkReward(self)
146
+ # FK body set for the reward: the head (r_speed_track's orientation + angular-velocity Gaussians) and the
147
+ # two feet. need_com is requested at call time, which is what actually costs -- the body list only
148
+ # controls which poses come back.
149
+ self._tw_feet = tuple(spec.feet)
150
+ self._tw_contact_bodies = sorted(set(int(b) for b in spec.contact_bodies))
151
+ # contact-sphere tables, built ONCE: the grounding used to .to()/.expand() them per sphere
152
+ self._tw_c_body = [int(b) for b in self._monitor.contact_body]
153
+ self._tw_c_centre = torch.stack([c.to(self.device) for c in self._monitor.contact_center])
154
+ self._tw_c_radius = torch.tensor([float(r) for r in self._monitor.contact_radius],
155
+ device=self.device)
156
+ self._tw_bodies = sorted({self.taskwalk.i_head, *self._tw_contact_bodies, *getattr(self, "_tw_llc_bodies", ())}
157
+ | ({self.taskwalk.i_up_body} if self.taskwalk.i_up_body is not None else set())) # TASKWALK_UP_BODY=thorax
158
+ self._tw_last_u = torch.zeros(self.nm, self.num_envs, device=self.device)
159
+ # Per-foot vertical GRF in bodyweights, summed over that foot's contact spheres (r_knee_load's proxy).
160
+ _right = torch.tensor([1.0 if b in set(spec.right_bodies) else 0.0 for b in self._tw_c_body],
161
+ device=self.device)
162
+ self._tw_grf_sel = torch.stack([_right, 1.0 - _right]) # (2, ncon)
163
+ self._tw_diag_ceiling_z = 0.0
164
+ import math as _math
165
+ self._tw_diag_lean_ref = _math.radians(0.0)
166
+ self._tw_diag_lean_tol = _math.radians(4.0)
167
+ self._tw_diag_ceiling_z0 = float(str(self._tw_diag_ceiling_z))
168
+ # TASKWALK_DIAG_MIDKNEE_W (diagnostic posture constraint, see _tw_reward): caps the loaded leg's knee flexion in the
169
+ # mid-stance window _T0.._T1 s after that foot's load onset
170
+ self._tw_diag_midknee_w = 0.0
171
+ assert self._tw_diag_midknee_w >= 0.0, self._tw_diag_midknee_w
172
+ if self._tw_diag_midknee_w > 0.0:
173
+ self._tw_mk_max = _math.radians(12.0)
174
+ self._tw_mk_max0 = _math.radians(12.0)
175
+ self._tw_mk_after = 0
176
+ self._tw_mk_steps = 0
177
+ self._tw_mk_t0 = 0.25
178
+ self._tw_mk_t1 = 0.45
179
+ self._tw_mk_gate = 0.2
180
+ names = [b["name"] for b in self._monitor.jm["bodies"]]
181
+ side = [names[b][-2:] for b in self._tw_c_body]
182
+ assert all(names[b].startswith(("calcn_", "toes_")) for b in self._tw_c_body), "foot-only contact set expected"
183
+ self._tw_mk_idx = [torch.tensor([i for i, s in enumerate(side) if s == k], dtype=torch.long, device=self.device)
184
+ for k in ("_r", "_l")]
185
+ assert all(len(x) > 0 for x in self._tw_mk_idx), side
186
+ self._tw_mk_t = torch.zeros(2, self.num_envs, device=self.device) # s since that foot's load onset
187
+ self._tw_mk_on = torch.zeros(2, self.num_envs, dtype=torch.bool, device=self.device)
188
+ print(f"[taskwalk] DIAGNOSTIC mid-stance knee cap W {self._tw_diag_midknee_w}: knee <= "
189
+ f"{_math.degrees(self._tw_mk_max0):.1f} -> {_math.degrees(self._tw_mk_max):.1f} deg over {self._tw_mk_steps} steps "
190
+ f"after step {self._tw_mk_after}, {self._tw_mk_t0}-{self._tw_mk_t1} s after load onset (> {self._tw_mk_gate} BW)")
191
+ # FALL GATE AGAINST THE FOOT'S CONTACT SPHERES rather than the calcaneus body ORIGIN. Opt-in;
192
+ # unset leaves the reward bit-identical, because switching it shifts every FALL_H threshold and
193
+ # the shift is NOT a constant that the corpus could be rescaled by.
194
+ #
195
+ # WHY IT IS WRONG AS SHIPPED. The gate is `com[2] - min(calcn_r.z, calcn_l.z)` -- a true
196
+ # whole-body COM measured against a foot BODY FRAME. Two errors compound:
197
+ # (a) the calcaneus origin is not the ground contact; it sits a mean 25.2 mm above the lowest
198
+ # contact sphere (range 17.8-61.1, widening as the foot rotates), and
199
+ # (b) the TOES bodies are not in `feet` at all, yet they are the lowest contact for 26-45% of a
200
+ # stride -- so for much of every cycle the gate measures against a body that is airborne.
201
+ # Together the shipped quantity runs 25-39 mm BELOW the true COM-above-ground (measured -25.2+-7.2
202
+ # on squeeze_s3, -39.2+-18.8 on c50fh81), i.e. FALL_H 0.90 actually cuts near 0.93.
203
+ #
204
+ # AND THE BIAS IS NOT NEUTRAL. Its size is set by how much of the cycle the toes are lowest, i.e.
205
+ # by how much TOE-OFF the gait has, so the gate penalises push-off -- the very thing a long stride
206
+ # needs. That is a second route from FALL_H to the measured stride ceiling, independent of the
207
+ # COM-dip geometry. See docs/logs/bug-grad-audits.md 2026-08-23.
208
+ # FALL-GATE SCHEDULE (opt-in). `TASKWALK_FALL_H` becomes the START value and the gate walks
209
+ # linearly to TASKWALK_FALL_H_END over the first TASKWALK_FALL_H_STEPS control steps, then holds.
210
+ # Unset => the gate is the constant it has always been, bit-identical.
211
+ #
212
+ # WHY A SCHEDULE AND NOT A VALUE. Measured 2026-08-23, FALL_H has no interior: 0.88 gives knee -26.1
213
+ # and 0.90 gives -15.8 on the same base, with the -17..-4 band between them and nothing landing in
214
+ # it. K_LIM is worse -- 800 is MORE pinned than 1000. Four axes now behave as basin switches rather
215
+ # than dials, so the remaining way to reach a posture the corpus cannot hold is to drive the basin
216
+ # over TIME: hold a tight gate while the upright posture is learned, then release it so the stride
217
+ # can grow without the crouch being available to fall back into.
218
+ #
219
+ # THE TIMING IS MEASURED, NOT GUESSED. A checkpoint sweep of `ml26_k2e5_klim400` on an RTX 3080 Ti laptop GPU at
220
+ # 1.0 m/s (ep240/360/480 against the ep600 sweep):
221
+ #
222
+ # ckpt surv strides stop% knee_hs wave cadence
223
+ # 0240 0 0 -- -- -- -- not walking yet
224
+ # 0360 1 29 0.0 -41.8 2.1 108.5
225
+ # 0480 3 66 0.0 -22.2 13.0 85.0
226
+ # 0600 7 155 0.0 -23.0 16.1 84.2
227
+ #
228
+ # The BASIN is fixed before the policy can walk (stop 0.0 from ep360 on) and the knee VALUE settles
229
+ # by ep480; the last 120 epochs only add robustness (surv 3 -> 7). So a gate released around ep400
230
+ # acts after the posture has committed and still leaves a third of training for the stride. That
231
+ # sweep is one cell and it never had a pinned phase, so it shows the free basin is entered early --
232
+ # NOT that a late release preserves an upright one. This knob is how that gets tested.
233
+ # UNITS: _STEPS counts CONTROL steps -- `self._train_steps` increments once per batched `step()`,
234
+ # NOT once per env. At the suite's steps_num=32 that is 32 per epoch regardless of n_env, so 400
235
+ # epochs is 12800, not 400*1024. The first version of this cell used 409600 and the gate would have
236
+ # moved 4.7% of the way across the whole run (0.81 -> 0.8142), i.e. the schedule would have been a
237
+ # no-op that looked configured. The assert below refuses a value that cannot complete in a
238
+ # plausible run.
239
+ # _AFTER holds the start value for that many control steps before the ramp begins. Needed because
240
+ # the gate is INERT until the policy can walk: measured on `ml26_k2e5_fhsched` against its fixed-gate
241
+ # control, eplen is identical to ep192 (28.1 vs 28.3) while the gate differs by 43 mm, then diverges
242
+ # once walking starts. A ramp from step 0 therefore spends its first third doing nothing and arrives
243
+ # at the far end exactly when the gate begins to matter.
244
+ self._tw_fall_h_end = None
245
+ self._tw_fall_h_steps = 0
246
+ self._tw_fall_h_after = 0
247
+ if self._tw_fall_h_end is not None:
248
+ assert self._tw_fall_h_steps > 0, (
249
+ "TASKWALK_FALL_H_END needs TASKWALK_FALL_H_STEPS > 0 -- a schedule with no length is a "
250
+ "silent step change at step 0, which is just a different constant.")
251
+ self._tw_fall_h_start = float(self.taskwalk.fall_h)
252
+ self._tw_fall_h_end = float(self._tw_fall_h_end)
253
+ # ---- WEIGHT SCHEDULES, for any TASKWALK_W_* term ------------------------------------------
254
+ # `TASKWALK_W_<TERM>` becomes the START weight and walks linearly to `TASKWALK_W_<TERM>_END`
255
+ # over `_STEPS` control steps, beginning after `_AFTER`. Unset => the weight is the constant it
256
+ # has always been, bit-identical. Same mechanism and same three names as the fall-gate schedule
257
+ # above; generic because the reason is generic.
258
+ #
259
+ # WHY A PENALTY NEEDS THE `_AFTER` AND THE FALL GATE DID NOT. The fall gate is INERT until the
260
+ # policy can walk, so a ramp from step 0 costs nothing (measured: `ml26_k2e5_fhsched`, eplen
261
+ # 28.1 vs 28.3 at ep192 while the gate differed by 43 mm). A COST is the opposite -- it is
262
+ # maximally harmful exactly when the policy cannot walk yet. Measured on this line:
263
+ # `ml26_fxfhsc_head_s1` put HeadStab at 2.0 from step 0 and never walked (eplen flat 21-27 for
264
+ # 260 epochs, return NEGATIVE throughout, straight through the ep 192-216 takeoff window),
265
+ # because (a_head/g)^2 is enormous while the model is still flailing. Dropping the weight to 0.2
266
+ # let it walk but at roughly a fifth of the parent's learning rate. A schedule fixes the SHAPE
267
+ # of the problem instead of trading it: no penalty while the gait is being found, full penalty
268
+ # once there is a gait to shape.
269
+ self._tw_w_sched, self._tw_w_sched2 = _tw_parse_w_sched(self.taskwalk)
270
+ # TASKWALK_ACTIVE_SAT_GATE (see the reward): the gate's state, a dict (no env scalar attribute changes, so TW1's baked-scalar check
271
+ # is untouched); read and written only at window boundaries (_asat_gate_update), never inside a step. TASKWALK_ACTIVE_SAT_GATE_FORCE_AT
272
+ # is TEST-ONLY (the GPU gate): from that control step the gate counts as open; train_tw14.check_env refuses it in a training cell.
273
+ self._asat_gate = None
274
+ if getattr(self.taskwalk, "active_sat_gate", False):
275
+ self._asat_gate = dict(self.taskwalk.asat_gate_par, r=0.0, c=0.0, s=0.0, x_prev=None, t_prev=None, n=0, dir=0, force=None,
276
+ target=self.taskwalk.asat_gate_target)
277
+ print(f"[taskwalk] active-sat performance gate: {self.taskwalk.asat_gate_par}, carrying {self.taskwalk.asat_gate_target}. Schumacher et al. 2025 Algorithm 1 (arXiv 2309.02976) "
278
+ "with two departures from the printed box: its s_mean (tested, never updated) is read as c_mean, and lambda = 1 (no "
279
+ "Delta-alpha decay); beta per window, not per episode. Signal = the eplen column with standing worlds (survived the "
280
+ "window, root speed < v_min) zeroed.", flush=True)
281
+ # the epoch labels use the run's own window (DN_STEPS_NUM control steps per epoch; 11-14: the old fixed 32 mislabelled the
282
+ # window-64 runs by 2x). Print only: the schedule itself counts control steps either way.
283
+ _spe = os.environ.get("DN_STEPS_NUM")
284
+ _ep = (lambda x: f"{x / int(_spe):g} epochs at {_spe} per epoch") if _spe else (lambda x: "epochs: DN_STEPS_NUM unset") # noqa: E731
285
+ for _n, _s, _e, _st, _af in self._tw_w_sched:
286
+ print(f"[taskwalk] weight schedule: {_n} {_s} -> {_e} over {_st} control steps "
287
+ f"({_ep(_st)}) starting at step {_af} ({_ep(_af)})", flush=True)
288
+ for _n, _s, _e, _st, _af in self._tw_w_sched2:
289
+ print(f"[taskwalk] weight schedule (second segment): {_n} {_s} -> {_e} over {_st} control steps "
290
+ f"({_ep(_st)}) starting at step {_af} ({_ep(_af)})", flush=True)
291
+ # BOLT'S LANE TERMINATIONS (2026-11-23, R17: msk_envs envs/lanes.py _get_lane_terminated, as his code has them). Opt-in, both 0 =
292
+ # off (default): nothing below is computed and every cell is bit-identical. They end the episode like a fall (_tw_fell; the
293
+ # fall penalty is not charged for them).
294
+ # TASKWALK_BOLT_LANE_TOES_W = W > 0: either toe body's WORLD lateral position farther than W m from the lane centre (lateral 0);
295
+ # Bolt's LANE_HALF_W 0.6. The toes are contact bodies, so their poses already come back in the reward's FK subset.
296
+ # TASKWALK_BOLT_HEADING_DEG = D > 0: the pelvis (root) facing more than D degrees off the lane (+x): |atan2(R10, R00)| > D; Bolt's 30.
297
+ self._tw_bolt_lane_w = float(os.environ.get("TASKWALK_BOLT_LANE_TOES_W", "0"))
298
+ self._tw_bolt_head = math.radians(float(os.environ.get("TASKWALK_BOLT_HEADING_DEG", "0")))
299
+ assert self._tw_bolt_lane_w >= 0.0 and self._tw_bolt_head >= 0.0, (self._tw_bolt_lane_w, self._tw_bolt_head)
300
+ self._tw_bolt_on = self._tw_bolt_lane_w > 0.0 or self._tw_bolt_head > 0.0
301
+ if self._tw_bolt_lane_w > 0.0:
302
+ _bn = [b["name"] for b in self._monitor.jm["bodies"]]
303
+ self._tw_bolt_toes = (_bn.index("toes_r"), _bn.index("toes_l"))
304
+ assert all(t in self._tw_bodies for t in self._tw_bolt_toes), ("TASKWALK_BOLT_LANE_TOES_W: the toes are not in the FK subset", self._tw_bolt_toes)
305
+ if self._tw_bolt_on:
306
+ assert float(os.environ.get("TASKWALK_LANE_HALF_W", "0")) == 0.0, "TASKWALK_BOLT_*: set TASKWALK_LANE_HALF_W 0 (the root-offset lane termination is the other rule)"
307
+ print(f"[taskwalk] BOLT LANE TERMINATIONS: toes lateral > {self._tw_bolt_lane_w:g} m (0 = off), root heading > "
308
+ f"{math.degrees(self._tw_bolt_head):g} deg (0 = off); the lane centre is the world's lateral 0", flush=True)
309
+ self._tw_fall_foot_geom = os.environ.get("TASKWALK_FALL_FOOT_GEOM", "0") == "1"
310
+ if self._tw_fall_foot_geom:
311
+ fb = set(int(b) for b in spec.foot_bodies)
312
+ assert fb, ("TASKWALK_FALL_FOOT_GEOM needs TaskWalkSpec.foot_bodies, which this model does "
313
+ "not define. It is NOT inferred from `feet`: `feet` is the calcanei and the toes "
314
+ "carry contact spheres of their own.")
315
+ sel = [i for i, b in enumerate(self._tw_c_body) if b in fb]
316
+ assert sel, f"foot_bodies {sorted(fb)} carry no contact spheres"
317
+ self._tw_foot_sph = torch.tensor(sel, device=self.device)
318
+ # the spheres' bodies as a Python list, once: the step reads them every control step, and int() over the device index
319
+ # tensor there was 10 host syncs per step (TW1's census, 11-10)
320
+ self._tw_foot_sph_bodies = [self._tw_c_body[i] for i in sel]
321
+ # TASKWALK_W_STANCE_KNEE_PROX: the rows of the foot spheres (in `sel` order) that are on each leg, for the per-leg lowest bottom
322
+ _rb = set(int(b) for b in spec.right_bodies)
323
+ self._tw_foot_sph_lr = (torch.tensor([j for j, b in enumerate(self._tw_foot_sph_bodies) if b in _rb], device=self.device),
324
+ torch.tensor([j for j, b in enumerate(self._tw_foot_sph_bodies) if b not in _rb], device=self.device))
325
+ assert len(self._tw_foot_sph_lr[0]) and len(self._tw_foot_sph_lr[1]), "each foot needs contact spheres"
326
+ # the walking gate carries the stance-knee-proximity cost: h is computed from the start (w 0 included), so every captured window
327
+ # holds the term's path whatever the gate does
328
+ self._tw_skp_gated = self._asat_gate is not None and self._asat_gate["target"] == "w_stance_knee_prox"
329
+ if not self._tw_fall_foot_geom:
330
+ assert self.taskwalk.w_stance_knee_prox == 0.0 and not self._tw_skp_gated and not any(n == "w_stance_knee_prox" for n, *_ in self._tw_w_sched), \
331
+ "TASKWALK_W_STANCE_KNEE_PROX reads the foot spheres' heights: set TASKWALK_FALL_FOOT_GEOM=1"
332
+ self._tw_ncon = int(getattr(self, "ncon", None) or self.ncontact) # the envs spell it differently
333
+ # WORLD displacement -> root translation qpos (see TaskWalkSpec.root_from_world)
334
+ self._tw_root_from_world = torch.tensor(spec.root_from_world, dtype=torch.float32,
335
+ device=self.device)
336
+ if spec.knee_muscles:
337
+ # the CANONICAL parser (issue #7): a raw json.loads here is one of the hand-rolled
338
+ # readers that consolidation removed, and it throws on any model carrying a `//`
339
+ # header -- which myoleg26_3d.dnmodel does, so the knee map could never be built.
340
+ _mn = [m["name"] for m in _load_dnmodel(self.model)["muscles"]]
341
+ self._tw_knee_mus = [
342
+ torch.tensor([i for i, nm in enumerate(_mn)
343
+ if nm.endswith(sd) and nm[:-2] in spec.knee_muscles],
344
+ dtype=torch.long, device=self.device) for sd in ("_r", "_l")]
345
+ assert all(len(v) == len(spec.knee_muscles) for v in self._tw_knee_mus), \
346
+ f"knee-muscle map incomplete: {[len(v) for v in self._tw_knee_mus]} of {len(spec.knee_muscles)}"
347
+ else:
348
+ self._tw_knee_mus = None
349
+ assert self._tw_knee_mus is not None or self.taskwalk.w_knee_load == 0.0, \
350
+ "TASKWALK_W_KNEE_LOAD != 0 but this model has no knee-muscle map in its TaskWalkSpec"
351
+ # The load term needs these and computes the tendon force itself, IN-GRAPH; the env no longer
352
+ # hands it a finished load off the detached side channel.
353
+ self.taskwalk.knee_mus = self._tw_knee_mus
354
+ self.taskwalk.bw_n = (self._tw_mass_kg() * 9.81)
355
+ # The MTU tension side channel is NOT armed any more. It was the load term's only consumer and
356
+ # it is `.detach()`ed at source, which is exactly why that term never reached the policy; the
357
+ # term now derives the same force in-graph. Leaving the channel off also restores the guarantee
358
+ # in gpu_bridge that a run which does not ask pays nothing, not even the .detach().
359
+ # (v_fwd target) observation + the paper's cyclic speed curriculum 0.7 -> 1.5 -> 0.7 m/s
360
+ self.TW_V_LO = float(os.environ.get("TASKWALK_V_LO", "0.7"))
361
+ self.TW_V_HI = float(os.environ.get("TASKWALK_V_HI", "1.5"))
362
+ self.TW_V_PERIOD = int(os.environ.get("TASKWALK_V_PERIOD", "400")) # only for the cyclic mode
363
+ self.TW_V_CYCLIC = bool(int(os.environ.get("TASKWALK_V_CYCLIC", "0"))) # 1 = the authors' schedule
364
+ _vf = os.environ.get("TASKWALK_V_FIXED", "")
365
+ self.TW_V_FIXED = float(_vf) if _vf else None # eval-only: pin the commanded speed
366
+ # TASKWALK_V_FIXED_SCHEDULE="0:v0,t1:v1,..." (11-23; the review, the speed-step eval of the start-transient analysis): EVAL ONLY. The
367
+ # pinned command steps to v_i from t_i seconds after each world's reset (v0 = TASKWALK_V_FIXED, the reset's command; t0 = 0), so one
368
+ # eval asks "does a policy that falls accelerating from rest to 6 m/s stay up when it is already running at 4 m/s and then asked for 6".
369
+ # Refused in training (asserted on eval_mode at every step, and by train_tw14.check_env). Unset: nothing parsed or read, bit-identical.
370
+ self._tw_vfs = None
371
+ # COMMAND RAMP (default 0 = OFF, byte-identical to before). RSI drops the body in at the clip's own
372
+ # speed -- 07_01_loop runs 1.19-1.65 m/s, mean 1.37 -- while the command is redrawn U(V_LO, V_HI).
373
+ # Measured 2026-08-19: the mean |v - v_cmd| at reset is 0.300 m/s, SIX times the 0.05 dead band, so
374
+ # g_fwd starts at 0.540 on average and at 0.089 for the 22% of envs commanded 0.7-0.9. That is a
375
+ # 4.60 reward deficit on the first step of every episode -- 30x the 0.152 gap between the two gait
376
+ # attractors this line has been chasing -- and none of it is the policy's control error. What the
377
+ # policy can learn from it is to decelerate abruptly.
378
+ # The ramp starts v_tgt at the body's ACTUAL forward speed and closes on the command linearly over
379
+ # N control steps. Both the reward (task_walk_reward.v_tgt) and the observation
380
+ # (gpu_myoleg26_vec_env: taskwalk.v_tgt) read the SAME tensor, so they cannot disagree.
381
+ # NOT what the authors do: their wrapper sets one target per episode (`speed_schedule` stepped on
382
+ # reset) and their `Ramp` wrapper is a terrain ramp, not a velocity one.
383
+ # V_HI CURRICULUM: widen the commanded-speed ceiling over training. None = OFF, bit-identical.
384
+ #
385
+ # WHY. 0.7-1.6 trains well (peak eplen 490-505) and 0.7-2.5 does not (345.9, and it stilts, with
386
+ # nothing surviving above v=1.0 on any of the six axes tried). With U(0.7, 2.5) HALF of every
387
+ # batch asks for a speed above 1.6 -- which even the trained 0.7-1.6 policy cannot do (0/8 at
388
+ # 1.6) -- so half the episodes are unreachable, r_speed_track ~ 0 there, and those steps contribute only
389
+ # penalty. Learning to walk first and widening after is the standard answer, and this file
390
+ # already anneals `fall_h` the same way (_tw_advance_fall_h), so the mechanism is not new.
391
+ self._tw_v_hi_end = os.environ.get("TASKWALK_V_HI_END")
392
+ self._tw_v_hi_steps = int(os.environ.get("TASKWALK_V_HI_STEPS", "0"))
393
+ # `_AFTER`, for parity with the fall-gate and TASKWALK_W_* schedules, which both have one. It
394
+ # exists for the sprint curriculum: the walk phase must keep the parent's ceiling EXACTLY, and a
395
+ # ramp from step 0 would widen the commanded speed during the phase whose whole job is to
396
+ # reproduce a known-walking configuration. Default 0 = ramp from step 0, unchanged.
397
+ self._tw_v_hi_after = int(os.environ.get("TASKWALK_V_HI_AFTER", "0"))
398
+ # THE FLOOR MOVES TOO, and the sprint curriculum is why. The commanded speed is an OBSERVATION
399
+ # (`_obs` appends `taskwalk.v_tgt`), and the curriculum turns `w_speed_track` off -- so from the
400
+ # moment the tracking gate is gone the policy is reading a number drawn U(V_LO, V_HI) that no
401
+ # longer affects any reward. That is worse than noise: the walk phase spends 500 epochs teaching
402
+ # the policy to CONDITION on it, and a low draw then still asks for a slow gait. Ramping the
403
+ # floor up with the ceiling collapses the draw onto a single value, so the input keeps meaning
404
+ # "the speed being asked for" all the way through and the two speed terms agree during the ramp.
405
+ # Default: no schedule, V_LO is the constant it has always been.
406
+ self._tw_v_lo_end = os.environ.get("TASKWALK_V_LO_END")
407
+ self._tw_v_lo_steps = int(os.environ.get("TASKWALK_V_LO_STEPS", "0"))
408
+ self._tw_v_lo_after = int(os.environ.get("TASKWALK_V_LO_AFTER", "0"))
409
+ self._tw_v_lo_start = self.TW_V_LO
410
+ if self._tw_v_lo_end is not None:
411
+ assert self._tw_v_lo_steps > 0, (
412
+ "TASKWALK_V_LO_END needs TASKWALK_V_LO_STEPS > 0 -- a schedule with no length is a "
413
+ "step change, not a curriculum")
414
+ self._tw_v_lo_end = float(self._tw_v_lo_end)
415
+ self._tw_v_hi_start = self.TW_V_HI
416
+ if self._tw_v_hi_end is not None:
417
+ assert self._tw_v_hi_steps > 0, (
418
+ "TASKWALK_V_HI_END needs TASKWALK_V_HI_STEPS > 0 -- a schedule with no length is a "
419
+ "step change, not a curriculum")
420
+ self._tw_v_hi_end = float(self._tw_v_hi_end)
421
+ self.TW_V_RAMP = 0
422
+ # TASKWALK_LOG_VTGT_EVERY = N > 0 (2026-11-21): at the start of every N-th training window (initialize_trajectory, outside any
423
+ # captured graph) print the scheduled command (V_LO / V_HI / V_FIXED) and the per-world commands the reward and the observation
424
+ # read (taskwalk.v_tgt: min / mean / max). WHY: a captured replay runs no Python, and a command schedule once stayed frozen for a
425
+ # whole run under the capture while every check passed (RUN290, 11-11); this line reads what the resets actually drew, on the
426
+ # training path itself. A read only (one host sync per logged window); the window count lives in a dict, outside the capture's
427
+ # stale-scalar census. 0 (default) = no line, bit-identical.
428
+ self._tw_log_vtgt_every = int(os.environ.get("TASKWALK_LOG_VTGT_EVERY", "0"))
429
+ assert self._tw_log_vtgt_every >= 0, self._tw_log_vtgt_every
430
+ self._tw_log_vtgt_state = {"n": 0}
431
+ # M4 of PAPER-SPEED-CONSTRAINT-M1-M4 (11-22, the design's study): SPEED-SHORTFALL TERMINATION. TASKWALK_SPEED_TERM_FRAC = f > 0:
432
+ # after a grace of TASKWALK_SPEED_TERM_GRACE_S seconds from the reset, an env whose COM forward speed over the trailing
433
+ # TASKWALK_SPEED_TERM_WIN_S seconds is below f x its command (the ramped v_tgt the reward reads) is TERMINATED as a failure, and
434
+ # that step PAYS the fall penalty (TASKWALK_W_FALL_PENALTY): a shortfall is priced as a fall, so ending the episode is never free
435
+ # (the free-terminal dive R5M / R5M2 found). Training only: an env in eval_mode, and every eval_tw14 / eval_tw14_batched run (they
436
+ # set the knob to 0 unless D16_EVAL_SPEED_TERM=1), measures the policy without it. The trailing speed is (x_t - x_{t-W}) / (W dt)
437
+ # of the reward's own COM, from a per-env ring buffer of W samples written in place (allocated here, before any capture; no reset
438
+ # handling is needed because the test reads it only once progress > max(grace, W), after W fresh writes). Detached: the
439
+ # termination and its constant penalty carry no gradient, as the fall. 0 (default) = OFF, bit-identical (nothing allocated).
440
+ self._tw_sterm_frac = 0.0
441
+ assert 0.0 <= self._tw_sterm_frac < 1.0, self._tw_sterm_frac
442
+ if self._tw_sterm_frac > 0.0:
443
+ for _k in ("TASKWALK_SPEED_TERM_GRACE_S", "TASKWALK_SPEED_TERM_WIN_S"):
444
+ assert os.environ.get(_k) is not None, f"TASKWALK_SPEED_TERM_FRAC needs {_k} (no default: the cell's header sets it)"
445
+ dtc = self.SUBSTEPS * self.dt
446
+ self._tw_sterm_w = int(round(float(os.environ["TASKWALK_SPEED_TERM_WIN_S"]) / dtc))
447
+ self._tw_sterm_g = max(int(round(float(os.environ["TASKWALK_SPEED_TERM_GRACE_S"]) / dtc)), self._tw_sterm_w)
448
+ assert self._tw_sterm_w >= 1, self._tw_sterm_w
449
+ self._tw_sterm_buf = torch.zeros(self._tw_sterm_w, self.num_envs, dtype=torch.float32, device=self.device)
450
+ self._tw_sterm_n = torch.zeros((), dtype=torch.long, device=self.device) # terminations so far (device counter)
451
+ self._tw_sterm_logged = {"n": 0, "w": 0}
452
+ print(f"[taskwalk] M4 speed-shortfall termination ON: after {self._tw_sterm_g * dtc:.2f} s, terminate when the COM speed over the "
453
+ f"last {self._tw_sterm_w * dtc:.2f} s < {self._tw_sterm_frac:g} x v_tgt; the step pays the fall penalty; training only", flush=True)
454
+ else:
455
+ for _k in ("TASKWALK_SPEED_TERM_GRACE_S", "TASKWALK_SPEED_TERM_WIN_S"):
456
+ assert os.environ.get(_k) is None, f"{_k} without TASKWALK_SPEED_TERM_FRAC"
457
+ self._tw_tlog = None
458
+ self._tw_v_cmd = None # the final commanded speed per env
459
+ self._tw_v_start = None # the body speed at reset per env
460
+ self._tw_v_left = None # ramp steps remaining per env
461
+ # ADAPTIVE SLOPE CURRICULUM (the paper's): eleven discrete slopes over [lo, hi] in 1-degree
462
+ # steps, sampled per EPISODE from a categorical whose per-slope difficulty score rises on a
463
+ # fall and falls on a completion, bounded below. Per EPISODE, not per epoch: an episode spans
464
+ # ~10 epochs, so an epoch-level slope would tilt the ground underneath a walking policy.
465
+ self.TW_SLOPE_LO = float(os.environ.get("TASKWALK_SLOPE_LO_DEG", "-5"))
466
+ self.TW_SLOPE_HI = float(os.environ.get("TASKWALK_SLOPE_HI_DEG", "5"))
467
+ self.TW_SLOPE_N = int(os.environ.get("TASKWALK_SLOPE_N", "11"))
468
+ self.TW_SLOPE_UP = 0.25 # score += on a fall
469
+ self.TW_SLOPE_DN = 0.05 # score -= on success
470
+ self.TW_SLOPE_MIN = 0.25 # the bound below
471
+ self._tw_slope_deg = torch.linspace(self.TW_SLOPE_LO, self.TW_SLOPE_HI, self.TW_SLOPE_N,
472
+ device=self.device)
473
+ self._tw_slope_score = torch.ones(self.TW_SLOPE_N, device=self.device) # uniform at init
474
+ self._tw_env_slope = torch.zeros(self.num_envs, dtype=torch.long, device=self.device)
475
+ # (3, n_env) unit normals, mutated in place per restarting env and RE-UPLOADED after every change
476
+ # (_tw_upload_normals): the engine keeps typed copies, not this tensor's pointer (mtu_gpu.set_ground_normals).
477
+ self._tw_normals = torch.zeros(3, self.num_envs, device=self.device)
478
+ self._tw_normals[2] = 1.0
479
+ # The per-env normals are read by the CUDA kernels only; a CPU env (tests, reward smokes)
480
+ # cannot step anyway, so skip the upload rather than pulling in a CUDA context to fail on.
481
+ # torch.device(): the full body stores a torch.device, myoleg26 stores the string it was
482
+ # constructed with. Normalise rather than requiring the two envs to agree on the type.
483
+ # N == 1 with a NONZERO slope is a silent no-op: the mechanism needs N > 1 for the categorical,
484
+ # so `TASKWALK_SLOPE_N=1 LO=HI=5` reads like "one slope, five degrees" and delivers FLAT GROUND
485
+ # with no warning. Caught 2026-09-08 when three fixed-slope evals produced byte-identical
486
+ # dnrecs. Use N=2 with LO=HI: linspace(x,x,2) = [x,x], so the draw is x either way.
487
+ assert not (self.TW_SLOPE_N == 1 and (self.TW_SLOPE_LO != 0.0 or self.TW_SLOPE_HI != 0.0)), (
488
+ f"TASKWALK_SLOPE_N=1 with LO={self.TW_SLOPE_LO} HI={self.TW_SLOPE_HI} would run on FLAT "
489
+ f"ground: the slope curriculum needs N > 1. Pass N=2 with LO=HI for a fixed slope, or "
490
+ f"LO=HI=0 for flat.")
491
+ self._tw_slopes_live = (torch.device(self.device).type == "cuda" and self.TW_SLOPE_N > 1
492
+ and (self.TW_SLOPE_LO != 0.0 or self.TW_SLOPE_HI != 0.0))
493
+ if self._tw_slopes_live:
494
+ _mtu_gpu.set_ground_normals(self._tw_normals, self.model)
495
+ # TASKWALK_OBS_H_ABOVE_GROUND=1 (opt-in, the slope test's): the observation's root height above the env's plane under the
496
+ # root, as DeepLoco's state measures it (cCtController::BuildPoliStatePose: root_pos[1] - SampleGroundHeight(root_pos)), in
497
+ # place of world z. The same number on flat ground, so a flat-trained policy is unchanged; on a ramp world z reads the
498
+ # climbed height as the body rising (dl_slope.py on dlrepro2's ep2000: every grade fell after a fixed climb, ~10 cm up or
499
+ # ~17 cm down, not after a fixed time).
500
+ self._tw_obs_h_ground = False
501
+ self._tw_explore_tau_setup("")
502
+ self._tw_explore_servo_setup("")
503
+ self.set_exc_noise(0.0,
504
+ None)
505
+ # LANE TERMINATION (opt-in, 0 = off). Bolt ends the episode when either toe leaves a 0.6 m
506
+ # half-width lane (`msk_envs/envs/env_lanes.py:99`), and that termination -- not any symmetry
507
+ # term, which he does not have -- is what makes his gait symmetric: a lopsided gait veers and
508
+ # dies. MEASURED on ml26_sprint_v0_s1, which had no lane: 3.42 m of lateral drift in 10 s, and
509
+ # a right hip that never flexed past -6.3 deg while the left reached +48.4.
510
+ # ROOT, not the toes: the toes need an FK pass in the termination path, and what actually
511
+ # measures veering is where the body went. Stated as a deviation from his 0.6 m toe bound.
512
+ # RELATIVE TO THE RESET, for the same reason the reward's mid-lane term is (RSI drops the body
513
+ # at the clip's own lateral offset).
514
+ # RSI POOL CURRICULUM. `TASKWALK_INIT_REF_START` names the clips the run STARTS from and
515
+ # `TASKWALK_INIT_REF` the ones it ends on; the draw moves from the first pool to the second
516
+ # linearly over `TASKWALK_RSI_MIX_STEPS` control steps beginning at `_AFTER`. Unset => no mix
517
+ # and the single-pool draw is bit-identical.
518
+ #
519
+ # WHY. ml26_sprint_v0_s1 and _lane_s1 both converged to a ONE-LEGGED gait (right hip never
520
+ # flexing past -6.3 deg while the left reached +48.4; footfalls 1 right against 13 left), and
521
+ # both were trained directly on the sprint task from a running RSI. A walking policy is
522
+ # bilaterally alternating by construction, so starting the run as a WALK puts the policy in that
523
+ # basin before the reward asks for speed. The reward side of the same curriculum needs no new
524
+ # code -- every `TASKWALK_W_*` already takes `_END`/`_STEPS`/`_AFTER`.
525
+ self._tw_rsi_mix_steps = 0
526
+ self._tw_rsi_mix_after = 0
527
+ self.TW_LANE_HALF_W = float(os.environ.get("TASKWALK_LANE_HALF_W", "0"))
528
+ assert self.TW_LANE_HALF_W >= 0.0, "TASKWALK_LANE_HALF_W is a half-width in metres, >= 0"
529
+ self._tw_lane0 = torch.zeros(self.num_envs, device=self.device)
530
+ self.num_obs += 1 # the commanded speed
531
+ # COMMANDED HEADING (opt-in, TASKWALK_HEADING=1; 0 = off, nothing below runs and every cell is bit-identical). The
532
+ # steering task after DeepLoco (Peng et al. 2017) with its imitation dropped: the walker is told a world direction to
533
+ # walk in, the reward reads its speed terms in that direction (TaskWalkReward.heading_cmd) and the policy observes the
534
+ # heading ERROR in its own yaw frame as (sin, cos). See docs-dev/literature/20261020_1646_deeploco_review/README.md.
535
+ _hd = "0"
536
+ self._tw_heading_on = _hd == "1"
537
+ self._tw_heading = None
538
+ if self._tw_heading_on:
539
+ self._tw_heading_setup()
540
+ self.num_obs += 2 # the heading error as (sin, cos), or as one angle
541
+
542
+ # ---------------------------------------------------------------- commanded heading
543
+
544
+ def _tw_heading_setup(self):
545
+ """Parse the heading command's mode and constants, and refuse every term that still assumes travel along world +x.
546
+
547
+ Modes (TASKWALK_HEADING_MODE):
548
+ random TRAINING. DeepLoco's plan generator (ScenarioExpImitateStep.cpp CalcNextHeading): every DT seconds the
549
+ heading takes a N(0, SIGMA^2) step, or with probability SHARP_P a "sharp turn" uniform in (-pi, pi).
550
+ Defaults are DeepLoco's: DT 0.5 s (one plan per 0.5-s step), SIGMA 0.25 rad, SHARP_P 0.1.
551
+ schedule EVAL. TASKWALK_HEADING_SCHEDULE="t0:deg0,t1:deg1,...": from t_i seconds after the reset the command is
552
+ deg_i degrees left of the heading the episode started with (t0 must be 0).
553
+ target EVAL. TASKWALK_HEADING_TARGETS="x0:y0;x1:y1;..." waypoints in metres in the start pose's heading frame
554
+ (x ahead, y to the left); the command points the root at the current waypoint (DeepLoco's scripted
555
+ target heading, atan2 to the target) and moves to the next within TARGET_R of it (DeepLoco's path task:
556
+ 1 m). After the last it keeps pointing at the last.
557
+ TASKWALK_HEADING_TARGET_SPEEDS="v0;v1;..." (optional, one per waypoint): the commanded speed while
558
+ heading for waypoint i is v_i, so one eval varies speed and direction together (needs
559
+ TASKWALK_V_FIXED = v0, the command the reset shows before the first step).
560
+ """
561
+ mode = "random"
562
+ self._tw_hd_mode = mode
563
+ self._tw_hd_dt = 0.5
564
+ self._tw_hd_sigma = 0.25
565
+ self._tw_hd_sharp_p = 0.1
566
+ # PER-METRE random plan (2026-10-22): TASKWALK_HEADING_PER_M > 0 updates the random command after that many metres of
567
+ # COMMANDED travel (the integral of v_tgt, exogenous) instead of every TASKWALK_HEADING_DT seconds, so every commanded speed
568
+ # sees the same turning per metre. DeepLoco's per-second numbers came with one walking speed; on a 0.7-1.6 m/s range they
569
+ # give the slow walker 2.3x the turning per metre of the fast one. 0 = the per-second plan, bit-identical.
570
+ self._tw_hd_per_m = 0.0
571
+ _c = "0"
572
+ self._tw_hd_obs_coupled = _c == "1" # the heading error observed with the root yaw in the graph
573
+ # TASKWALK_HEADING_OBS_RAW=1: the error as one angle in (-pi, pi], DeepLoco's eTaskParamRootHeading (the plan's heading in
574
+ # the character's heading frame, atan2) in place of (sin, cos); 0 = (sin, cos), bit-identical. Unmirrored only (the
575
+ # mirror's heading block is the (sin, cos) pair).
576
+ _r = "0"
577
+ self._tw_hd_obs_raw = _r == "1"
578
+ self._tw_hd_sched = None
579
+ self._tw_hd_targets = None
580
+ self._tw_hd_speeds = None
581
+ # Every term that still reads a world +x quantity, refused rather than silently wrong under a turn: the touchdown cost
582
+ # (heel x velocity), the late-single-support gates (heel passes along +x), Bolt's mid-lane and the lane termination
583
+ # (world lateral position), and the slopes (the brake's ground tangent and the plane tilt assume travel along +x).
584
+ for name in ("w_touchdown", "w_mid_lane"):
585
+ assert self._tw_w_live(name) == 0.0, f"TASKWALK_HEADING: {name} reads world +x / y; it is not rotated yet"
586
+ tw = self.taskwalk
587
+ # the late-single-support stance-knee gate reads the heels along the commanded heading (task_walk_reward _cmd_frame)
588
+ assert not (tw.stance_ankle_single == 2 and self._tw_w_live("w_stance_ankle") != 0.0), (
589
+ "TASKWALK_HEADING: the late-single-support stance-ankle gate reads heel order along +x")
590
+ assert self.TW_LANE_HALF_W == 0.0, "TASKWALK_HEADING: the lane termination reads the world lateral position"
591
+ # slopes: the ramp rises along +x and the terms above read +x, so a heading task may stand on one only with the straight
592
+ # plan along the reset's own heading (TASKWALK_HEADING_MODE=schedule '0:0', tools/steer/dl_slope.py's Table 1 test)
593
+ straight = False
594
+ assert not self._tw_slopes_live, \
595
+ "TASKWALK_HEADING on slopes needs the straight plan (schedule '0:0'): the slope frame is not rotated"
596
+ n = self.num_envs
597
+ self._tw_heading = torch.zeros(n, device=self.device) # the command, world yaw (rad)
598
+ self._tw_hd_t = torch.zeros(n, device=self.device) # seconds since the reset
599
+ self._tw_hd_next = torch.full((n,), self._tw_hd_dt, device=self.device) # random mode: the next plan update
600
+ self._tw_hd_s = torch.zeros(n, device=self.device) # commanded metres since the reset (per-metre plan)
601
+ self._tw_hd_next_s = torch.full((n,), max(self._tw_hd_per_m, 1e-6), device=self.device)
602
+ self._tw_hd_yaw0 = torch.zeros(n, device=self.device) # the heading the episode started with
603
+ self._tw_hd_origin = torch.zeros(2, n, device=self.device) # the root's start position (target mode)
604
+ self._tw_hd_ti = torch.zeros(n, dtype=torch.long, device=self.device) # the current waypoint (target mode)
605
+ print(f"[taskwalk] heading command: mode {mode}, dt {self._tw_hd_dt} s, sigma {self._tw_hd_sigma} rad, "
606
+ f"sharp p {self._tw_hd_sharp_p}", flush=True)
607
+ self._tw_fs = None
608
+
609
+ @staticmethod
610
+ def _tw_root_yaw(q):
611
+ """(n,) world yaw of the root, the ZYX heading DnModelMonitor.yaw_quat divides out of the observation."""
612
+ w, x, y, z = q[3], q[4], q[5], q[6]
613
+ return torch.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z))
614
+
615
+ def _tw_heading_reset(self, env_ids):
616
+ """Restarting envs: the command starts as the body's own heading (DeepLoco's first plan points the way the character
617
+ faces), so a policy padded from a straight walker starts in its own distribution. Call AFTER the reset pose is in q."""
618
+ if not self._tw_heading_on:
619
+ return
620
+ with torch.no_grad():
621
+ yaw = self._tw_root_yaw(self.q[:, env_ids].detach())
622
+ h = self._tw_heading.clone(); h[env_ids] = yaw; self._tw_heading = h
623
+ y0 = self._tw_hd_yaw0.clone(); y0[env_ids] = yaw; self._tw_hd_yaw0 = y0
624
+ t = self._tw_hd_t.clone(); t[env_ids] = 0.0; self._tw_hd_t = t
625
+ nx = self._tw_hd_next.clone(); nx[env_ids] = self._tw_hd_dt; self._tw_hd_next = nx
626
+ sm = self._tw_hd_s.clone(); sm[env_ids] = 0.0; self._tw_hd_s = sm
627
+ ns = self._tw_hd_next_s.clone(); ns[env_ids] = max(self._tw_hd_per_m, 1e-6); self._tw_hd_next_s = ns
628
+ o = self._tw_hd_origin.clone(); o[:, env_ids] = self.q[0:2, env_ids].detach(); self._tw_hd_origin = o
629
+ ti = self._tw_hd_ti.clone(); ti[env_ids] = 0; self._tw_hd_ti = ti
630
+ if getattr(self, "_tw_fs", None) is not None:
631
+ self._tw_footstep_reset(env_ids)
632
+
633
+ def _tw_advance_heading(self, control_dt):
634
+ """One control step of the command, BEFORE the reward and the observation read it (as v_tgt is advanced)."""
635
+ if not self._tw_heading_on:
636
+ return
637
+ with torch.no_grad():
638
+ self._tw_hd_t = self._tw_hd_t + control_dt
639
+ if getattr(self, "_tw_fs", None) is not None:
640
+ pass # the footstep plan walks the heading once per step
641
+ else:
642
+ due = self._tw_hd_t >= self._tw_hd_next - 1e-6
643
+ n = due.shape[0]
644
+ step = self._tw_hd_sigma * torch.randn(n, device=self.device, generator=self.rng)
645
+ sharp = torch.rand(n, device=self.device, generator=self.rng) < self._tw_hd_sharp_p
646
+ turn = (2.0 * torch.rand(n, device=self.device, generator=self.rng) - 1.0) * torch.pi
647
+ delta = torch.where(sharp, turn, step)
648
+ self._tw_heading = torch.where(due, self._tw_heading + delta, self._tw_heading)
649
+ self._tw_hd_next = torch.where(due, self._tw_hd_next + self._tw_hd_dt, self._tw_hd_next)
650
+ self.taskwalk.heading_cmd = self._tw_heading
651
+
652
+ def _tw_target_world(self):
653
+ """(2, n) the current waypoint in the world (target mode): the episode's local waypoint rotated by its start heading."""
654
+ c0, s0 = torch.cos(self._tw_hd_yaw0), torch.sin(self._tw_hd_yaw0)
655
+ tl = self._tw_hd_targets[:, self._tw_hd_ti]
656
+ return self._tw_hd_origin + torch.stack([c0 * tl[0] - s0 * tl[1], s0 * tl[0] + c0 * tl[1]])
657
+
658
+ def _tw_footstep_reset(self, env_ids):
659
+ """A provisional ResetStepPlan for restarting envs, from the reset pose, so the task state exists before the first
660
+ observation; the plan is rebuilt at the first foot strike from the foot that landed (FootstepPlan.switch), because a guess
661
+ from the pose can be a step out of phase. The guessed stance is the loaded foot; in double support the one further along
662
+ the heading (it struck last); with neither loaded the lower one (DeepLoco reads it off the reference's phase). Random mode
663
+ starts the plan along the body's own heading (DeepLoco's character starts facing its heading 0); target mode toward the
664
+ waypoint from the ROOT, as ResetStepPlan does. DeepLoco also re-centres the stance foot laterally at +-width / 2 in random
665
+ mode (its character starts at the origin); we keep the real foot. The speed is the command the env last held (it is
666
+ advanced at the next reward call); the first switch re-reads it."""
667
+ P = self._tw_fs
668
+ m = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device); m[env_ids] = True
669
+ q = self.q.detach()
670
+ pos, _, _ = self._monitor.body_poses_subset(q, self._tw_feet, False)
671
+ feet = (pos[self._tw_feet[0]][0:2], pos[self._tw_feet[1]][0:2])
672
+ fr_, fl_ = self._tw_foot_fz()
673
+ on_r, on_l = fr_ > self._tw_fs_strike_n, fl_ > self._tw_fs_strike_n
674
+ off = (fr_ < self._tw_fs_arm_n, fl_ < self._tw_fs_arm_n) if P.arm else None
675
+ fz = (pos[self._tw_feet[0]][2], pos[self._tw_feet[1]][2])
676
+ c, s_ = torch.cos(self._tw_heading), torch.sin(self._tw_heading)
677
+ ahead_l = (c * (feet[1][0] - feet[0][0]) + s_ * (feet[1][1] - feet[0][1])) > 0.0
678
+ stance_left = torch.where(on_r & on_l, ahead_l, torch.where(on_r ^ on_l, on_l, fz[1] < fz[0]))
679
+ t0 = None
680
+ if P.clock > 0.0 and self._tw_reset_lib: # TASKWALK_RESET_STEPLIB: the reset draw's stance and time
681
+ stance_left, t0 = self._tw_rl_stance_left, self._tw_rl_t0
682
+ # ResetStepPlan's random mode re-centres the stance foot laterally at +-W/2 (its character starts on the line); here
683
+ # from the root's line in the body's heading frame, the foot's forward place kept
684
+ from diffneusim.rl.footstep_plan import step_geometry
685
+ _, W = step_geometry(P.fit, torch.as_tensor(self.taskwalk.v_tgt, device=self.device, dtype=feet[0].dtype).expand(self.num_envs))
686
+ yaw = self._tw_root_yaw(q)
687
+ cy, sy = torch.cos(yaw), torch.sin(yaw)
688
+ st = torch.where(stance_left[None], feet[1], feet[0])
689
+ fwd = cy * (st[0] - q[0]) + sy * (st[1] - q[1])
690
+ lat = torch.where(stance_left, 0.5 * W, -0.5 * W) # the left foot on the left (+y), the right on the right
691
+ stance_xy = torch.stack([q[0] + cy * fwd - sy * lat, q[1] + sy * fwd + cy * lat]) # the plan's only (the feet stay real)
692
+ elif P.clock > 0.0: # DeepLoco: the stance and the time off the reset phase
693
+ stance_left, t0 = self._tw_clock_reset_phase()
694
+ if not (P.clock > 0.0 and self._tw_reset_lib):
695
+ stance_xy = torch.where(stance_left[None], feet[1], feet[0])
696
+ v = torch.as_tensor(self.taskwalk.v_tgt, device=self.device, dtype=feet[0].dtype).expand(self.num_envs)
697
+ P.reset(m, stance_left, stance_xy, self._tw_heading, v, (on_r, on_l),
698
+ body_yaw=self._tw_root_yaw(q), off=off, t0=t0)
699
+ if P.clock > 0.0 and getattr(self, "mirror", None) is not None: # the mirror frame is the clock's stance (setup)
700
+ self.mirror.flipped = torch.where(m, P.stance_left, self.mirror.flipped) # replaced, never mutated (BPTT)
701
+ self._tw_heading = torch.where(m, P.heading, self._tw_heading) # the command follows the (bounded) plan from the start
702
+ if getattr(self, "_tw_steplib", None) is not None:
703
+ self._tw_steplib_select(m, feet, v)
704
+ self._tw_fs_obs = torch.where(m[:, None], P.obs(feet, self._tw_root_yaw(q)).to(self._tw_fs_obs.dtype), self._tw_fs_obs)
705
+ self._tw_fs_fail = self._tw_fs_fail & ~m
706
+
707
+ def _tw_clock_reset_phase(self):
708
+ """Under DeepLoco's clock, (stance_left, t0) per env from the reset clip's phase (self.phase, which the RSI sets): DeepLoco's
709
+ kinematic character runs on from the sampled state's time, so the first step is the rest of the step the reset pose is in.
710
+ The reset clip's right and left strikes are each heel's most forward point ahead of the root along the clip's travel (Zeni
711
+ et al. 2008, the rule of the tracking arm's heel anchor and of leg_reach), found once; a right stance runs from the right
712
+ strike to the left one, and t0 is the share of it already walked times the clock's step."""
713
+ P = self._tw_fs
714
+ if self._tw_clk_strikes is None:
715
+ assert getattr(self, "_tw_track", False) and self.imitation_task is not None, \
716
+ "the clock reads the reset clip's phase, which the RSI sets only with TASKWALK_TRACK_POSE=1"
717
+ with torch.no_grad():
718
+ rq = self.imitation_task.ref_q.t().contiguous() # (nq, frames): the reset clip's loop
719
+ pos, _, _ = self._monitor.body_poses_subset(rq, list(self._tw_feet), False)
720
+ u = rq[0:2, -1] - rq[0:2, 0]
721
+ u = u / u.norm()
722
+ phs = []
723
+ for b in self._tw_feet:
724
+ fwd = ((pos[b][0:2] - rq[0:2]) * u[:, None]).sum(0)
725
+ phs.append(float(int(fwd.argmax())) / fwd.shape[0])
726
+ self._tw_clk_strikes = tuple(phs)
727
+ print(f"[taskwalk] DEEPLOCO CLOCK: the reset clip's strikes at phase {phs[0]:.3f} (right) / {phs[1]:.3f} (left)", flush=True)
728
+ phi_r, phi_l = self._tw_clk_strikes
729
+ f_r = (phi_l - phi_r) % 1.0 # the right stance's share of the cycle
730
+ assert 0.3 < f_r < 0.7, f"the reset clip's strikes are not a step apart: right {phi_r}, left {phi_l}"
731
+ a = (self.phase - phi_r) % 1.0
732
+ left = a >= f_r
733
+ frac = torch.where(left, (a - f_r) / (1.0 - f_r), a / f_r)
734
+ return left, (frac * P.clock).clamp(0.0, 0.999 * P.clock)
735
+
736
+ def _tw_reset_from_steplib(self, env_ids):
737
+ """TASKWALK_RESET_STEPLIB (SAMPLE_INIT_STATES): (q0, qd0) for the restarting envs from the step library's first clip at a
738
+ cycle time u ~ U(0, 1) x the cycle (2 clock steps; CalcRandKinResetTime draws over cycle_dur): a right stance for u < 1/2
739
+ (BipedStepController3D::GetStance), clip 0, else its mirrored copy (clip n, MocapStepController's ShouldMirrorPose); the
740
+ step's elapsed time t0 = the draw's place in its step, the clip's phase t0 / its play time, its velocities warped from clip
741
+ seconds to the play time (as the LLC reward reads them). No reset noise (SyncCharacters copies the kinematic state). Sets
742
+ _tw_rl_stance_left / _tw_rl_t0 for the plan's reset (_tw_footstep_reset). The clip's own root place and heading are kept."""
743
+ P, Lb = self._tw_fs, getattr(self, "_tw_steplib", None)
744
+ assert Lb is not None, "TASKWALK_RESET_STEPLIB needs TASKWALK_STEP_LIBRARY"
745
+ n = len(env_ids)
746
+ with torch.no_grad():
747
+ u = torch.rand(n, generator=self.rng, device=self.device)
748
+ left = u >= 0.5
749
+ t0 = ((u * 2.0) % 1.0) * P.clock
750
+ t0 = t0.clamp(0.0, 0.999 * P.clock)
751
+ T = torch.full((n,), P.clock, device=self.device) # every clip plays over the clock's step
752
+ cid = torch.where(left, torch.full_like(env_ids, Lb.n), torch.zeros_like(env_ids)).to(Lb.task.clip_id.dtype)
753
+ tk = Lb.task
754
+ saved = tk.clip_id
755
+ if saved.numel() != self.num_envs:
756
+ saved = torch.zeros(self.num_envs, dtype=torch.long, device=self.device)
757
+ tk.clip_id = cid # ref_at reads one clip per entry of the phase
758
+ q0, qd0 = tk.ref_at((t0 / T).clamp(0.0, 0.999))
759
+ tk.clip_id = saved
760
+ warp = (tk.clip_T[cid] - 1).to(t0.dtype) * tk.ref_dt / T # clip seconds per second of play
761
+ qd0 = qd0 * warp[None].to(qd0.dtype)
762
+ sl = getattr(self, "_tw_rl_stance_left", None)
763
+ if sl is None:
764
+ sl = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device)
765
+ self._tw_rl_t0 = torch.zeros(self.num_envs, device=self.device)
766
+ self._tw_rl_stance_left = sl.clone(); self._tw_rl_stance_left[env_ids] = left
767
+ t = self._tw_rl_t0.clone(); t[env_ids] = t0.to(t.dtype); self._tw_rl_t0 = t
768
+ return q0.clone(), qd0.clone()
769
+
770
+ def _tw_fs_obs_out(self):
771
+ """The footstep inputs: by role (n, 4) as cached, or TASKWALK_FOOTSTEP_OBS_SIDES's per-foot slots (n, 8) = (right p0, left
772
+ p0, right p1, left p1), each (forward, left), zeros in the two slots of the other role (BuildTaskState)."""
773
+ o = self._tw_fs_obs
774
+ if not self._tw_fs_sides:
775
+ return o
776
+ sl = self._tw_fs.stance_left[:, None] # a left stance: the right foot swings
777
+ z = torch.zeros_like(o[:, 0:2])
778
+ p0, p1 = o[:, 0:2], o[:, 2:4]
779
+ return torch.cat([torch.where(sl, p0, z), torch.where(sl, z, p0), torch.where(sl, z, p1), torch.where(sl, p1, z)], 1)
780
+
781
+ def _tw_contact_flags(self):
782
+ """TASKWALK_CONTACT_OBS: (n, 2) = (right, left) 1.0 while the leg's summed vertical contact force exceeds the latch's level."""
783
+ fr, fl = self._tw_foot_fz()
784
+ return torch.stack([(fr > self.MIRROR_F_ON), (fl > self.MIRROR_F_ON)], 1).to(self.q.dtype)
785
+
786
+ def set_exc_noise(self, sd, seed=None):
787
+ """TASKWALK_EXC_NOISE_SD (opt-in; the design brief, 11-12: "if we perturb from training on, the fast cadence might go
788
+ away"): N(0, sd^2) added to every action dimension after the policy's own sample, then clamped to [-1, 1], the operations of
789
+ tools/d16_taskwalk/xeval_cpu.py's --action-noise in its order (the action + sd eps, the clamp, then the env's step), so training
790
+ and that test perturb alike. sd = 0 (the default) leaves _step_a's path untouched (bitwise today's).
791
+ The draw is a counter-based hash, pure tensor arithmetic with no generator (_exc_normal): eps[i, j] at a world's k-th draw is a
792
+ function of (the seed, the world i, the dimension j, k). So
793
+ - a captured window replays fresh draws: the per-world draw count _exc_k is TASKWALK_STATE (sapo_capture), an explicit input
794
+ and output of each slot, and _step_a advances it out of place;
795
+ - each world's sequence is reproducible from the seed and independent of the other worlds' resets;
796
+ - the policy's own sampling stream (the default generator) and the env's rng are not drawn from.
797
+ Detached (the noise carries no gradient); the action's gradient passes the clamp where it does not bind.
798
+ The eval tools call this themselves (their --exc-noise, default 0), independent of the run's environment.
799
+ seed None: the env's rng seed + 104729."""
800
+ sd = float(sd)
801
+ assert sd >= 0.0 and math.isfinite(sd), sd
802
+ self.exc_noise_sd = sd
803
+ if sd == 0.0:
804
+ self._exc_k = None
805
+ return
806
+ self._exc_seed = int(self.rng.initial_seed()) + 104729 if seed is None else int(seed)
807
+ assert 0 <= self._exc_seed < 2 ** 32, self._exc_seed
808
+ i = torch.arange(self.num_envs, dtype=torch.int64, device=self.device)
809
+ self._exc_world = _fmix32(_fmix32(i) ^ (self._exc_seed & _M32))[:, None] # (n, 1)
810
+ self._exc_dim = None # (1, na) per stream, built at the first draw from the action's width
811
+ if getattr(self, "_exc_k", None) is None:
812
+ self._exc_k = torch.zeros(self.num_envs, dtype=torch.int64, device=self.device)
813
+ print(f"[taskwalk] EXC NOISE: N(0, {sd}^2) on every action dimension, clamped to [-1, 1], seed {self._exc_seed}", flush=True)
814
+
815
+ def _exc_normal(self, k, na):
816
+ """(n, na) standard normals for the worlds' draw counts k (n,): one murmur3 finalizer per stream over (world, k) and the dimension,
817
+ 24-bit uniforms in (0, 1), Box-Muller. Deterministic arithmetic, the same on the CPU and the GPU up to the float32 log / cos."""
818
+ if self._exc_dim is None: # built once, at the first draw (a constant the captures read)
819
+ j = torch.arange(na, dtype=torch.int64, device=self.device)
820
+ self._exc_dim = (_fmix32(j * 2 + 0x51ED27)[None, :], _fmix32(j * 2 + 1 + 0x51ED27)[None, :]) # two streams, (1, na)
821
+ assert self._exc_dim[0].shape[1] == na, (tuple(self._exc_dim[0].shape), na)
822
+ hk = _fmix32(self._exc_world ^ (k[:, None] & _M32)) # (n, 1)
823
+ h1, h2 = _fmix32(hk ^ self._exc_dim[0]), _fmix32(hk ^ self._exc_dim[1])
824
+ u1 = ((h1 >> 8).to(torch.float32) + 0.5) * (2.0 ** -24)
825
+ u2 = ((h2 >> 8).to(torch.float32) + 0.5) * (2.0 ** -24)
826
+ return torch.sqrt(-2.0 * torch.log(u1)) * torch.cos((2.0 * math.pi) * u2)
827
+
828
+ def _tw_exc_noise(self, actions):
829
+ """_step_a's first operation when exc_noise_sd > 0: (actions + sd eps).clamp(-1, 1), eps from _exc_normal at the draw count, the
830
+ count advanced (out of place: a captured slot returns it)"""
831
+ eps = self._exc_normal(self._exc_k, actions.shape[1]).to(actions.dtype)
832
+ assert eps.shape == actions.shape, (tuple(eps.shape), tuple(actions.shape))
833
+ self._exc_k = self._exc_k + 1
834
+ return (actions + self.exc_noise_sd * eps).clamp(-1.0, 1.0)
835
+
836
+ def _tw_explore_tau_setup(self, spec):
837
+ """TASKWALK_EXPLORE_TAU (opt-in, plan B of docs-dev/deeploco/20261028_2330_dlrepro2/next/PLAN.md): DeepLoco's exploration
838
+ perturbation as an exogenous joint torque. DeepLoco adds Gaussian noise to its PD targets on epsilon-greedy steps
839
+ (exp_noise 0.1 of the output scale, epsilon 1 -> 0.2 over its first 1M iterations), so its body takes a torque kick whenever
840
+ the noise is on; our independent per-muscle excitation noise mostly cancels at the joints (19-77x smaller at the hip, knee
841
+ and ankle, next/A_torque_noise). `spec` "hip=S,knee=S,ankle=S": the |tau| std in N.m per joint and side (the ball hip's
842
+ split evenly over its three axes), held over the control step, independent per env and per step, on the steps a
843
+ Bernoulli(epsilon) draw switches on (_tw_explore_eps). Training only (eval_mode draws nothing), detached, not observed;
844
+ its own generator, so the resets and the plans draw as they do without it. "" leaves it off. TASKWALK_EXPLORE_SERVO is
845
+ the phase-faithful form (next/B_sizing): this held torque cannot be sized for swing and stance at once."""
846
+ self._tw_xtau = None
847
+ if not spec:
848
+ return
849
+ sig = {k: float(v) for k, v in (kv.split("=") for kv in spec.split(","))}
850
+ assert sig and set(sig) <= {"hip", "knee", "ankle"} and all(v > 0.0 for v in sig.values()), spec
851
+ by = {b.get("joint_name"): b for b in _load_dnmodel(self.model)["bodies"]}
852
+ idx, std = [], []
853
+ for j, s in sig.items():
854
+ for side in ("r", "l"):
855
+ b = by[{"hip": "hip_flexion", "knee": "knee_angle", "ankle": "ankle_angle"}[j] + "_" + side]
856
+ assert b["joint"] in ("ball", "revolute"), (j, b["joint"])
857
+ n = 3 if b["joint"] == "ball" else 1
858
+ idx += [int(b["vadr"]) + k for k in range(n)]
859
+ std += [s / math.sqrt(n)] * n
860
+ self._tw_xtau = dict(idx=torch.tensor(idx, device=self.device), std=torch.tensor(std, device=self.device)[:, None],
861
+ gen=self._tw_explore_gen())
862
+ print(f"[taskwalk] EXPLORE TAU: |tau| std {sig} N.m on {len(idx)} dofs, epsilon {self._tw_xeps} (training only)")
863
+
864
+ def _tw_explore_gen(self):
865
+ """The exploration kicks' own generator and the epsilon schedule they share: TASKWALK_EXPLORE_EPS0 -> _EPS1 linearly over
866
+ _EPS_STEPS control steps (0: _EPS1 throughout), DeepLoco's epsilon-greedy (1 -> 0.2 over its first 1M of ~6M iterations)."""
867
+ e0 = 1.0
868
+ e1 = 0.2
869
+ ns = 0
870
+ self._tw_xeps = (e0, e1, ns)
871
+ gen = torch.Generator(device=self.device)
872
+ gen.manual_seed(int(self.rng.initial_seed()) + 7919)
873
+ return gen
874
+
875
+ def _tw_explore_on(self, gen):
876
+ """(n,) this control step's Bernoulli(epsilon) draw, epsilon on the shared schedule."""
877
+ e0, e1, ns = self._tw_xeps
878
+ eps = e1 if ns == 0 else e0 + (e1 - e0) * min(1.0, self._train_steps / ns)
879
+ return torch.rand(self.num_envs, generator=gen, device=self.device) < eps
880
+
881
+ def _tw_explore_tau(self):
882
+ """TASKWALK_EXPLORE_TAU: this control step's (nv, n) joint-torque kick, or None (off, or eval)."""
883
+ X = self._tw_xtau
884
+ if X is None or self.eval_mode:
885
+ return None
886
+ n = self.num_envs
887
+ on = self._tw_explore_on(X["gen"]).to(X["std"].dtype)
888
+ z = torch.randn(len(X["idx"]), n, generator=X["gen"], device=self.device) * X["std"] * on[None]
889
+ return torch.zeros(self.nv, n, device=self.device).index_copy_(0, X["idx"], z)
890
+
891
+ def _tw_explore_servo_setup(self, spec):
892
+ """TASKWALK_EXPLORE_SERVO (opt-in, plan B's phase-faithful form, next/B_sizing): DeepLoco's exploration as its own mechanism.
893
+ On a Bernoulli(epsilon) step (the shared schedule) each listed joint gets a noisy target offset dtheta ~ N(0, sigma) for the
894
+ control step, and a virtual servo tau = kp (dtheta - (q - q_0)), q_0 the joint at the step's start, recomputed every
895
+ substep from q and capped, so the torque decays when the segment is free (swing) and holds when the body resists (stance),
896
+ as DeepLoco's PD target noise does. No damping term (it would damp the gait); no torque on an env whose draw is off.
897
+ `spec` "hip=KP:SIGMA:CAP,knee=...,ankle=..." (N.m/rad, rad, N.m; both sides). The ball hip takes an isotropic offset
898
+ vector with |dtheta| rms SIGMA and caps |tau|. Training only, detached, not observed, the kicks' own generator."""
899
+ self._tw_xsrv = None
900
+ if not spec:
901
+ return
902
+ par = {k: tuple(float(x) for x in v.split(":")) for k, v in (kv.split("=") for kv in spec.split(","))}
903
+ assert par and set(par) <= {"hip", "knee", "ankle"} and all(len(v) == 3 and min(v) > 0.0 for v in par.values()), spec
904
+ by = {b.get("joint_name"): b for b in _load_dnmodel(self.model)["bodies"]}
905
+ hq, hv, hk, hs, hc, bq, bv, bk, bs, bc = [], [], [], [], [], [], [], [], [], []
906
+ for j, (kp, sg, cap) in par.items():
907
+ for side in ("r", "l"):
908
+ b = by[{"hip": "hip_flexion", "knee": "knee_angle", "ankle": "ankle_angle"}[j] + "_" + side]
909
+ if b["joint"] == "revolute":
910
+ hq.append(int(b["qadr"])); hv.append(int(b["vadr"])); hk.append(kp); hs.append(sg); hc.append(cap)
911
+ else:
912
+ assert b["joint"] == "ball", (j, b["joint"])
913
+ bq.append(int(b["qadr"])); bv.append(int(b["vadr"])); bk.append(kp); bs.append(sg); bc.append(cap)
914
+ T = lambda x, dt=torch.float32: torch.tensor(x, device=self.device, dtype=dt) # noqa: E731
915
+ self._tw_xsrv = dict(hq=T(hq, torch.long), hv=T(hv, torch.long), hk=T(hk)[:, None], hs=T(hs)[:, None], hc=T(hc)[:, None],
916
+ bq=T(bq, torch.long), bv=T(bv, torch.long), bk=T(bk)[:, None], bs=T(bs)[:, None], bc=T(bc)[:, None],
917
+ gen=self._tw_explore_gen())
918
+ print(f"[taskwalk] EXPLORE SERVO: kp:sigma:cap {par} on {len(hq)} hinges + {len(bq)} ball joints, epsilon {self._tw_xeps} "
919
+ f"(training only)")
920
+
921
+ def _tw_explore_servo_begin(self):
922
+ """TASKWALK_EXPLORE_SERVO: this control step's draw (the on mask, the offsets, q_0), or None (off, or eval)."""
923
+ X = self._tw_xsrv
924
+ if X is None or self.eval_mode:
925
+ return None
926
+ n, g = self.num_envs, X["gen"]
927
+ on = self._tw_explore_on(g).to(torch.float32)
928
+ q = self.q.detach()
929
+ dh = torch.randn(len(X["hq"]), n, generator=g, device=self.device) * X["hs"]
930
+ db = torch.randn(len(X["bq"]), 3, n, generator=g, device=self.device) * (X["bs"] / math.sqrt(3.0))[:, :, None]
931
+ return dict(on=on, dh=dh, db=db, h0=q[X["hq"]].clone(),
932
+ b0=torch.stack([q[int(a):int(a) + 4] for a in X["bq"].tolist()]).clone() if len(X["bq"]) else None)
933
+
934
+ def _tw_explore_servo_tau(self, st):
935
+ """(nv, n) the virtual servo's torque at the current q for the draw `st` (zero where the draw is off)."""
936
+ X, q = self._tw_xsrv, self.q.detach()
937
+ tau = torch.zeros(self.nv, self.num_envs, device=self.device)
938
+ if len(X["hq"]):
939
+ th = (X["hk"] * (st["dh"] - (q[X["hq"]] - st["h0"]).to(torch.float32))).clamp(-X["hc"], X["hc"])
940
+ tau.index_copy_(0, X["hv"], th * st["on"][None])
941
+ for i, a in enumerate(X["bq"].tolist()):
942
+ q0, q1 = st["b0"][i], q[a:a + 4]
943
+ w = q0[0] * q1[0] + (q0[1:] * q1[1:]).sum(0) # conj(q0) x q1, scalar part
944
+ v = q0[0] * q1[1:] - q1[0] * q0[1:] - torch.linalg.cross(q0[1:], q1[1:], dim=0) # its vector part, in q0's frame
945
+ sgn = torch.where(w < 0, -1.0, 1.0).to(w.dtype) # the shorter way round
946
+ w, v = w * sgn, v * sgn
947
+ s = v.norm(dim=0)
948
+ rel = v * torch.where(s > 1e-9, 2.0 * torch.atan2(s, w) / s.clamp_min(1e-9), 2.0 / w.clamp_min(1e-9))[None]
949
+ tb = X["bk"][i] * (st["db"][i] - rel.to(torch.float32))
950
+ tb = tb * (X["bc"][i] / tb.norm(dim=0).clamp_min(1e-12)).clamp(max=1.0)[None]
951
+ vb = int(X["bv"][i])
952
+ tau[vb:vb + 3] = tb * st["on"][None]
953
+ return tau
954
+
955
+ def _tw_cycle_phase_obs(self):
956
+ """TASKWALK_CYCLE_PHASE_BINS=K: (n, 1 + K) = the clock's cycle phase (right stance in [0, 0.5), left in [0.5, 1)) and its
957
+ K-bin one-hot (bin = floor(phase K)), detached (the clock is exogenous)."""
958
+ P, K = self._tw_fs, self._tw_cyc_bins
959
+ with torch.no_grad():
960
+ ph = 0.5 * (P.stance_left.to(P.t.dtype) + (P.t / P.clock).clamp(0.0, 1.0 - 1e-6))
961
+ b = (ph * K).floor().long().clamp(0, K - 1)
962
+ oh = torch.nn.functional.one_hot(b, K).to(self.q.dtype)
963
+ return torch.cat([ph[:, None].to(self.q.dtype), oh], 1)
964
+
965
+ def _tw_step_ee_err(self, feet_xy, feet_z=None):
966
+ """DeepLoco's end-effector error over the feet (CalcRewardStep): each foot's position relative to the root in the root's
967
+ heading frame against the chosen step's, squared, x 2 / n_end_effs (= 1 for two feet); in the step's second half the swing
968
+ foot's horizontal reference error is dropped (DeepLoco keeps only its height there, and the footstep error takes over).
969
+ feet_z (2, n) adds the vertical part (TASKWALK_STEP_EE_H): each foot's height above the lower foot against the step's, in
970
+ both halves and for both feet, plus the late swing foot's once more (DeepLoco's footstep error puts its target at the
971
+ reference foot's height). In the graph through the feet and the root (position and yaw); the reference is fixed."""
972
+ P, Lb = self._tw_fs, self._tw_steplib
973
+ ph = (P.t / self._tw_sl_T).clamp(0.0, 0.999)
974
+ ref = Lb.ee_ref(ph) # (2 feet, 2, n)
975
+ yaw = self._tw_root_yaw(self.q)
976
+ c, s_ = torch.cos(yaw), torch.sin(yaw)
977
+ err = []
978
+ for k in (0, 1):
979
+ d = feet_xy[k] - self.q[0:2]
980
+ rel = torch.stack([c * d[0] + s_ * d[1], -s_ * d[0] + c * d[1]])
981
+ err.append(((rel - ref[k].to(rel.dtype)) ** 2).sum(0))
982
+ late = ((P.t / P.T) > 0.5) & ~P.pending
983
+ swing_is_r = P.stance_left # the swing foot is the right when the left stands
984
+ e_r = torch.where(late & swing_is_r, torch.zeros_like(err[0]), err[0])
985
+ e_l = torch.where(late & ~swing_is_r, torch.zeros_like(err[1]), err[1])
986
+ out = (e_r + e_l) * (2.0 / 2.0)
987
+ if feet_z is not None:
988
+ h = feet_z - torch.minimum(feet_z[0], feet_z[1])[None]
989
+ dh = (h - Lb.ee_h_ref(ph).to(h.dtype)) ** 2 # (2, n)
990
+ out = out + (dh[0] + dh[1]) * (2.0 / 2.0) + late.to(dh.dtype) * torch.where(swing_is_r, dh[0], dh[1])
991
+ return out
992
+
993
+ def _tw_llc_reward(self, k_ee, foot_pos, fail, quat):
994
+ """TASKWALK_LLC: DeepLoco's low-level-controller reward (diffneusim/rl/llc_reward.py) x TASKWALK_LLC_SCALE, 0 on a
995
+ fallen or step-failed step. The reference is the plan step's library clip, its velocities time-warped to the clip's play
996
+ time; until the first plan exists, the reset clip played in real time from its reset phase. In the graph through q, qd,
997
+ the feet and the walker's coupled COM rate; every reference is detached."""
998
+ from diffneusim.rl import llc_reward as LLC
999
+ L, P, Lb = self._tw_llc, self._tw_fs, self._tw_steplib
1000
+ pend = P.pending
1001
+ ph = (P.t / self._tw_sl_T).clamp(0.0, 0.999)
1002
+ q_lib, qd_lib = Lb.task.ref_at(ph)
1003
+ warp = (Lb.task.clip_T[Lb.task.clip_id] - 1).to(ph.dtype) * Lb.task.ref_dt / self._tw_sl_T # clip seconds per second
1004
+ ph0 = (self.phase + P.t / self.imitation_task.ref_secs) % 1.0
1005
+ q_0, qd_0 = self.imitation_task.ref_at(ph0)
1006
+ h_lib, v_lib, t_lib = L["lib"].at(ph)
1007
+ h_0, v_0, t_0 = L["init"].at(ph0)
1008
+ q_ref = torch.where(pend[None], q_0, q_lib).detach()
1009
+ qd_ref = torch.where(pend[None], qd_0, qd_lib * warp[None]).detach()
1010
+ h_ref = torch.where(pend, h_0, h_lib).detach()
1011
+ v_ref = torch.where(pend[None], v_0, v_lib * warp[None]).detach()
1012
+ t_ref = torch.where(pend[None], t_0, t_lib).detach()
1013
+ t_sim = LLC.qmul(LLC.qconj(self.q[3:7]), quat[L["torso"]]) # the torso against the root, in the graph
1014
+ arms = None
1015
+ if L["arms"]: # the humerus against the torso, in the graph; the reference detached
1016
+ a_lib, a_0 = L["lib"].arms_at(ph), L["init"].arms_at(ph0)
1017
+ arms = {k: (LLC.qmul(LLC.qconj(quat[pa]), quat[ch]), torch.where(pend[None], a_0[k], a_lib[k]).detach().to(t_sim.dtype))
1018
+ for k, (ch, pa) in L["arms"].items()}
1019
+ # TASKWALK_LLC_GROUP_TERMS=1 (probes, with the term log): the pose and rate kernels split per joint group below
1020
+ by_group = self.taskwalk.log_terms and False
1021
+ out = LLC.pose_vel_errors(self.q, self.qd, q_ref, qd_ref, L["groups"],
1022
+ torso=(t_sim, t_ref.to(t_sim.dtype), L["torso_scale"]), arms=arms, per_group=by_group)
1023
+ e_pose, e_vel = out[:2]
1024
+ h = LLC.root_height_above_feet(self.q[2], torch.stack([foot_pos[0][2], foot_pos[1][2]]))
1025
+ e_root = (h - h_ref.to(h.dtype)) ** 2
1026
+ yaw = self._tw_root_yaw(self.q)
1027
+ c, s = torch.cos(yaw), torch.sin(yaw)
1028
+ v = self.taskwalk.last_v_com
1029
+ v_loc = torch.stack([c * v[0] + s * v[1], -s * v[0] + c * v[1], v[2]])
1030
+ dv = (v_loc - v_ref.to(v_loc.dtype)) * self.taskwalk.last_v_com_valid.to(v_loc.dtype)[None] # 0 just after a reset
1031
+ head = torch.remainder(P.heading.to(yaw.dtype) - yaw + math.pi, 2.0 * math.pi) - math.pi
1032
+ r, terms = LLC.llc_reward(e_pose, e_vel, k_ee.to(e_pose.dtype), e_root, dv, head)
1033
+ fell = self.taskwalk.last_fall.to(r.dtype)
1034
+ r = L["scale"] * r * (1.0 - fell) * (1.0 - fail.to(r.dtype))
1035
+ if self.taskwalk.log_terms:
1036
+ for k_, t_ in terms.items():
1037
+ self.taskwalk.last_terms_t["llc_" + k_] = t_.detach()
1038
+ # for probes (actor_grad_attribution): each term's PAID share of r, in the graph; they sum to r exactly
1039
+ gate = L["scale"] * (1.0 - fell) * (1.0 - fail.to(r.dtype)) / sum(LLC.TERM_W.values())
1040
+ self._tw_llc_terms_t = {k_: gate * LLC.TERM_W[k_] * t_ for k_, t_ in terms.items()}
1041
+ if by_group:
1042
+ # 'pose' and 'vel' replaced by one source per joint group (llc_reward.split_exp_term): the values still sum to
1043
+ # r and the gradients to its gradient; the unweighted pose errors kept for the probe's features
1044
+ for k_, pieces in (("pose", out[2]), ("vel", out[3])):
1045
+ del self._tw_llc_terms_t[k_]
1046
+ for j, s_ in LLC.split_exp_term(terms[k_], LLC.TERM_SCALE[k_], pieces).items():
1047
+ self._tw_llc_terms_t[f"{k_}:{j}"] = gate * LLC.TERM_W[k_] * s_
1048
+ self._tw_llc_group_err = out[4]
1049
+ return r
1050
+
1051
+ def _tw_steplib_select(self, mask, feet, v):
1052
+ """DeepLoco's SelectNewMotion for the envs in `mask` (a new plan step): the nearest library step to the body's state, its
1053
+ mirrored copy for a left stance, played over the plan's nominal step time L / v (step_library.StepLibrary)."""
1054
+ from diffneusim.rl.footstep_plan import step_geometry
1055
+ P, Lb = self._tw_fs, self._tw_steplib
1056
+ q = self.q.detach()
1057
+ stance = torch.where(P.stance_left[None], feet[1], feet[0])
1058
+ swing = torch.where(P.stance_left[None], feet[0], feet[1])
1059
+ f = Lb.features(P.stance_left, stance, swing, P.p0, P.heading, q[0:2], self._tw_root_yaw(q))
1060
+ k = Lb.select(f, P.stance_left)
1061
+ Lb.task.clip_id = torch.where(mask, k, Lb.task.clip_id)
1062
+ L, _ = step_geometry(P.fit, v)
1063
+ T = torch.full_like(L, P.clock) if P.clock > 0.0 else L / v # DeepLoco warps every clip to the clock's step
1064
+ self._tw_sl_T = torch.where(mask, T.to(self._tw_sl_T.dtype), self._tw_sl_T)
1065
+
1066
+ def _tw_footstep_update(self, foot_pos, control_dt):
1067
+ """DeepLoco's UpdateStepPlan once per control step (footstep_plan.FootstepPlan): switch where the swing foot struck (the
1068
+ per-foot vertical force above TASKWALK_FOOTSTEP_STRIKE_N, _tw_foot_on, from the env's step), set the heading command to the
1069
+ plan's, cache the task state."""
1070
+ P = self._tw_fs
1071
+ feet_xy = (foot_pos[0][0:2], foot_pos[1][0:2]) # calcn_r, calcn_l world (x, y), IN THE GRAPH
1072
+ feet_d = (feet_xy[0].detach(), feet_xy[1].detach())
1073
+ v = torch.as_tensor(self.taskwalk.v_tgt, device=self.device, dtype=feet_d[0].dtype).expand(self.num_envs)
1074
+ target = None
1075
+ sched = None # this step's scheduled heading, the plan's next
1076
+ sw = P.switch(self._tw_foot_on, feet_d, v, control_dt, target, sched, body_yaw=self._tw_root_yaw(self.q.detach()),
1077
+ off=self._tw_foot_off if P.arm else None)
1078
+ if P.clock > 0.0 and getattr(self, "mirror", None) is not None: # the mirror frame is the clock's stance (setup); this
1079
+ self.mirror.flipped = P.stance_left.clone() # runs after the latch's update and before the obs
1080
+ if getattr(self, "_tw_steplib", None) is not None:
1081
+ self._tw_steplib_select(sw | P.rebuilt, feet_d, v)
1082
+ self._tw_fs_fail = P.fail.clone()
1083
+ self._tw_heading = P.heading.clone()
1084
+ self.taskwalk.heading_cmd = self._tw_heading
1085
+ self._tw_fs_obs = P.obs(feet_xy, self._tw_root_yaw(self.q)) # in the graph: the feet and the root yaw
1086
+ return feet_xy
1087
+
1088
+ def _tw_heading_obs(self):
1089
+ """(n, 2) (sin, cos) of the heading error, command minus the root's yaw: what the policy needs, in its own frame. Under
1090
+ the sagittal mirror the error negates, so sin flips and cos does not (MirrorSymmetry's "heading" block).
1091
+
1092
+ TASKWALK_HEADING_OBS_COUPLED=1 keeps the root yaw in the graph, as every other observation is (qobs, qd, lce): the
1093
+ critic's bootstrap at the window end, and the actor's own input at the next steps, then see that turning the body
1094
+ changes the error. 0 (the default, the line until 2026-10-22) reads the yaw from a DETACHED q, which cuts that path:
1095
+ MEASURED (docs-dev/deeploco/20261022_1030_lrw_steer, tools/steer/critic_heading_curve.py, heading_grad_probe.py) the
1096
+ critic values a smaller |e| at +490 to +800 per rad on 90-99% of the policy's states, yet its bootstrap gradient on the
1097
+ actor's heading columns (600x the heading term's) does not turn the body, while the heading term's does."""
1098
+ q = self.q.detach()
1099
+ e = self._tw_heading - self._tw_root_yaw(q)
1100
+ return torch.stack([torch.sin(e), torch.cos(e)], 1).to(self.q.dtype)
1101
+
1102
+ def _tw_calibrate(self):
1103
+ """The head's up axis from the STANDING KEYFRAME (`_tw_q_stand`, set by the env), as calibrate_head_up documents.
1104
+
1105
+ FIXED 2026-10-09: this read `self.q` after the first reset(), i.e. env 0's reset state. Under TASKWALK_INIT_REF
1106
+ (reference-state init) that is a random walking frame, so the 'upright' head axis differed with the seed and the
1107
+ env count: the replay of one expert record read a head-upright factor of 0.997 alone and 0.988 inside a 32-record
1108
+ batch (speed_track 9.766 vs 9.674 / step), the size of the IOC LP's margins."""
1109
+ with torch.no_grad():
1110
+ q_stand = getattr(self, "_tw_q_stand", None)
1111
+ assert q_stand is not None and q_stand.dim() == 1 and q_stand.shape[0] == self.nq, (
1112
+ "the env must set _tw_q_stand (its standing keyframe, (nq,)) before _tw_calibrate()")
1113
+ _, _qk, _ = self._monitor.body_poses_subset(q_stand.unsqueeze(1).contiguous(), self._tw_bodies, True)
1114
+ self.taskwalk.calibrate_head_up(_qk[self.taskwalk.i_head])
1115
+ if self.taskwalk.i_up_body is not None: # TASKWALK_UP_BODY=thorax: the up term's axis, same keyframe
1116
+ self.taskwalk.calibrate_up_body(_qk[self.taskwalk.i_up_body])
1117
+
1118
+ # ---------------------------------------------------------------- reset
1119
+
1120
+ def _tw_draw(self, env_ids):
1121
+ """First half of the taskwalk reset: clear the rate terms, redraw the command and the slope.
1122
+
1123
+ SPLIT from the grounding on purpose. Both this and the corpus state sampler (`imitation_task.rsi`)
1124
+ consume `self.rng`, so their ORDER is part of the run's identity -- fold them together the wrong
1125
+ way round and every seeded run silently changes. Callers must do: _tw_draw -> rsi -> ground.
1126
+ """
1127
+ # Without the clear, the first post-reset step differences across a teleport and injects a
1128
+ # spurious COM velocity into r_speed_track on exactly the step the policy cannot explain.
1129
+ self.taskwalk.reset(env_ids)
1130
+ # A reset breaks the lce continuity the coupled gradient path assumes; flag these envs so the
1131
+ # next reward step skips the correction for them (the value path is already handled by
1132
+ # _lce_prev, which the vec env re-baselines on reset).
1133
+ if not hasattr(self, "_tw_lce_fresh"):
1134
+ self._tw_lce_couple = bool(int(os.environ.get("TASKWALK_LCE_DOT_COUPLED", "0")))
1135
+ self._tw_lce_prev_graph = None
1136
+ self._tw_lce_fresh = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device)
1137
+ self._tw_lce_fresh[env_ids] = True
1138
+ if getattr(self, "_tw_diag_midknee_w", 0.0) > 0.0:
1139
+ self._tw_mk_t[:, env_ids] = 0.0
1140
+ self._tw_mk_on[:, env_ids] = False
1141
+ if self.taskwalk.v_tgt is None or self.taskwalk.v_tgt.shape[0] != self.num_envs:
1142
+ self.taskwalk.v_tgt = self._tw_command_speed()
1143
+ else: # redraw ONLY the restarting envs
1144
+ v = self.taskwalk.v_tgt.clone()
1145
+ drawn = self._tw_command_speed(env_ids).to(v.dtype)
1146
+ v[env_ids] = drawn
1147
+ self.taskwalk.v_tgt = v
1148
+ self._tw_draw_height(env_ids)
1149
+ self._tw_draw_slopes(env_ids)
1150
+
1151
+ def _tw_sterm_log(self):
1152
+ """M4's line (TASKWALK_SPEED_TERM_FRAC > 0): the shortfall terminations so far and since the last line, at the start of windows 1,
1153
+ 1 + N, ... with N = TASKWALK_LOG_VTGT_EVERY (10 when that is 0); initialize_trajectory, outside any captured graph, one host sync."""
1154
+ st = self._tw_sterm_logged
1155
+ st["w"] += 1
1156
+ every = self._tw_log_vtgt_every if self._tw_log_vtgt_every > 0 else 10
1157
+ if (st["w"] - 1) % every != 0:
1158
+ return
1159
+ n = int(self._tw_sterm_n)
1160
+ print(f"[taskwalk] M4 shortfall terminations: window {st['w']} (step {int(getattr(self, '_train_steps', 0))}): {n} so far, "
1161
+ f"{n - st['n']} since the last line", flush=True)
1162
+ st["n"] = n
1163
+
1164
+ def _tw_term_accumulate(self, done, bad_height, toppled, diverged, timeout, rew):
1165
+ """TASKWALK_LOG_TERMINALS: this step's terminal census into the device buffers (inside the captured window; detached)."""
1166
+ with torch.no_grad():
1167
+ T, f64 = self._tw_tlog, torch.float64
1168
+ d = done.detach()
1169
+ to = d & timeout
1170
+ fall = d & bad_height & ~timeout
1171
+ top = d & toppled & ~timeout & ~bad_height
1172
+ div = d & diverged & ~timeout & ~bad_height & ~toppled
1173
+ oth = d & ~(to | fall | top | div)
1174
+ T["c"] += torch.stack([x.sum() for x in (d, to, fall, top, div, oth)]).to(f64)
1175
+ w, x, y, z = (self.q[3 + i].detach().to(f64) for i in range(4)) # root quaternion, w-first
1176
+ ux, uz = 2 * (x * z + w * y), 1 - 2 * (x * x + y * y) # the root's up axis: forward lean + when ux > 0
1177
+ pitch = torch.rad2deg(torch.atan2(ux, uz))
1178
+ vb = self.qd[3:6].detach().to(f64) # linear velocity, root frame
1179
+ vx = (1 - 2 * (y * y + z * z)) * vb[0] + 2 * (x * y - w * z) * vb[1] + 2 * (x * z + w * y) * vb[2]
1180
+ nt = (d & ~timeout).to(f64)
1181
+ T["s"] += torch.stack([(nt * torch.nan_to_num(pitch)).sum(), (nt * torch.nan_to_num(vx)).sum(), nt.sum(),
1182
+ (d.to(f64) * self.progress.to(f64)).sum()])
1183
+ T["h"].index_add_(0, (self.progress // 25).clamp(0, 40).long(), d.to(f64))
1184
+ tw = self.taskwalk
1185
+ T["r"] += torch.stack([tw._last_rst.to(f64).sum(), tw.last_effort_t.detach().to(f64).sum(), tw._last_rsm.to(f64).sum(),
1186
+ torch.nan_to_num(rew.detach().to(f64)).sum(), T["one"]])
1187
+
1188
+ def _tw_term_log(self):
1189
+ """TASKWALK_LOG_TERMINALS' line at the start of windows 1 + N, 1 + 2N, ... (initialize_trajectory, outside any captured graph): the
1190
+ census of the previous N windows, then cleared. Kill-rule fields (the review, PAPER-METHOD-B): topple_share, eplen_median."""
1191
+ T = self._tw_tlog
1192
+ T["w"] += 1
1193
+ every = self._tw_log_vtgt_every if self._tw_log_vtgt_every > 0 else 10
1194
+ if (T["w"] - 1) % every != 0 or T["w"] == 1:
1195
+ return
1196
+ c, s, h, r = (T[k].tolist() for k in ("c", "s", "h", "r"))
1197
+ n = c[0]
1198
+ cum, med = 0.0, None
1199
+ for i, v in enumerate(h):
1200
+ cum += v
1201
+ if med is None and n > 0 and cum >= n / 2:
1202
+ med = 25 * i + 12.5
1203
+ k = max(r[4], 1.0)
1204
+ print(f"[taskwalk] terminals: windows {T['w'] - every}-{T['w'] - 1} (step {int(getattr(self, '_train_steps', 0))}): done {n:.0f} = "
1205
+ f"timeout {c[1]:.0f} height {c[2]:.0f} topple {c[3]:.0f} diverged {c[4]:.0f} other {c[5]:.0f}; topple_share "
1206
+ f"{(c[3] / n if n else 0.0):.3f}; at non-timeout terminals pitch {(s[0] / s[2] if s[2] else float('nan')):.1f} deg "
1207
+ f"v_x {(s[1] / s[2] if s[2] else float('nan')):.2f} m/s; eplen_mean {(s[3] / n if n else float('nan')):.1f} eplen_median "
1208
+ f"{med if med is not None else float('nan')}; per env-step w_r_track {r[0] / k:.3f} E {r[1] / k:.3f} lambda_v {r[2] / k:.3f} "
1209
+ f"total {r[3] / k:.3f}; lambda {float(self.taskwalk.w_speed_max):.3f}", flush=True)
1210
+ for key in ("c", "s", "h", "r"):
1211
+ T[key].zero_()
1212
+
1213
+ def _tw_log_vtgt(self):
1214
+ """TASKWALK_LOG_VTGT_EVERY's line, at the start of windows 1, 1 + N, 1 + 2N, ... (initialize_trajectory, outside any captured graph)."""
1215
+ st = self._tw_log_vtgt_state
1216
+ st["n"] += 1
1217
+ if (st["n"] - 1) % self._tw_log_vtgt_every != 0:
1218
+ return
1219
+ v = self.taskwalk.v_tgt
1220
+ head = (f"[taskwalk] v_tgt window {st['n']} (step {int(getattr(self, '_train_steps', 0))}): scheduled V_LO {self.TW_V_LO:.4f} "
1221
+ f"V_HI {self.TW_V_HI:.4f} V_FIXED {self.TW_V_FIXED}")
1222
+ if v is None:
1223
+ print(f"{head}; no command drawn yet", flush=True)
1224
+ return
1225
+ with torch.no_grad():
1226
+ vd = v.detach().double()
1227
+ lo, mean, hi = float(vd.min()), float(vd.mean()), float(vd.max())
1228
+ print(f"{head}; drawn per world min {lo:.4f} mean {mean:.4f} max {hi:.4f} ({vd.numel()} worlds)", flush=True)
1229
+
1230
+ def _tw_advance_v_hi(self):
1231
+ """Widen the commanded-speed ceiling toward TASKWALK_V_HI_END. No-op unless _END is set.
1232
+
1233
+ Only the CEILING moves; the per-episode draw stays U(V_LO, V_HI) so every batch keeps the whole
1234
+ range it currently has (the reason TASKWALK_V_CYCLIC is off -- see _tw_command_speed).
1235
+ """
1236
+ if self._tw_v_hi_end is None:
1237
+ return
1238
+ frac = min(1.0, max(0.0, float(self._train_steps - self._tw_v_hi_after)) / float(self._tw_v_hi_steps))
1239
+ self.TW_V_HI = self._tw_v_hi_start + (self._tw_v_hi_end - self._tw_v_hi_start) * frac
1240
+
1241
+ def _tw_w_live(self, name):
1242
+ """The largest magnitude this weight will EVER take -- its current value or either end of its
1243
+ schedule. Used by the input gates, which must arm a term before its ramp lifts off zero."""
1244
+ w = abs(getattr(self.taskwalk, name))
1245
+ for n, w0, w1, _st, _af in list(self._tw_w_sched) + list(getattr(self, "_tw_w_sched2", [])):
1246
+ if n == name:
1247
+ w = max(w, abs(w0), abs(w1))
1248
+ return w
1249
+
1250
+ def _asat_gate_update(self):
1251
+ """TASKWALK_ACTIVE_SAT_GATE's step, once per window (initialize_trajectory, outside any captured graph). THE SIGNAL is the trainer's
1252
+ own eplen column (rl_algorithm_suite: the mean over worlds of env.progress, at the same boundary) with the STANDING worlds zeroed:
1253
+ a world that survived the whole window (progress >= S) and whose root x advanced less than V_MIN m/s over it counts 0, every
1254
+ other world its episode age. With nobody standing the signal IS the logged eplen, so THETA derived from the logged eplen rows
1255
+ (m67) applies as derived; a standing policy cannot open the gate (its only non-zero worlds are younger than S, so the signal stays
1256
+ below S < THETA). Falling worlds need no speed test: they move forward as fast as walkers until they fall (m68), and a world
1257
+ that falls inside the window restarts its age. Integer sum, so deterministic given the trajectory. THE RULE: Schumacher et al.
1258
+ Algorithm 1 with s_mean read as c_mean and lambda = 1 (the reward's __init__ has the source and the departures); the branch
1259
+ reads the previous window's c (the box updates c_mean after the branch)."""
1260
+ G = self._asat_gate; t = int(self._train_steps); x = self.q[0].detach().clone()
1261
+ if G["t_prev"] is None or t == G["t_prev"]: # the first boundary (or a repeated call): nothing measured yet
1262
+ G.update(x_prev=x, t_prev=t); return
1263
+ S = t - G["t_prev"]; dtc = self.SUBSTEPS * self.dt
1264
+ assert G["theta"] > S, f"THETA {G['theta']} <= the window {S}: a standing policy's young worlds alone could open the gate"
1265
+ stand = (self.progress >= S) & ((x - G["x_prev"]) / (S * dtc) < G["vmin"])
1266
+ sig = int((self.progress * (~stand).to(self.progress.dtype)).sum()) / self.progress.numel()
1267
+ G["r"] = G["beta"] * G["r"] + (1.0 - G["beta"]) * sig; high = G["r"] > G["theta"]
1268
+ w0 = float(getattr(self.taskwalk, G["target"])); forced = G["force"] is not None and t >= G["force"]
1269
+ if forced or (high and G["c"] > 0.5):
1270
+ w = min(w0 + G["dw"], G["wmax"])
1271
+ elif not high:
1272
+ w = max(w0 - G["dw"], 0.0)
1273
+ else:
1274
+ w = w0
1275
+ G["c"] = G["beta"] * G["c"] + (1.0 - G["beta"]) * float(high)
1276
+ self.taskwalk.set_weight(G["target"], w)
1277
+ n = G["n"] + 1; G.update(x_prev=x, t_prev=t, n=n, s=sig)
1278
+ nstand = int(stand.sum()); tag = (" (FORCED, test only)" if forced else "") + ("" if G["target"] == "w_active_sat" else f" [{G['target']}]")
1279
+ ev = None # a change of regime: one line each (23 reads the weight trace from these)
1280
+ if w0 == 0.0 and w > 0.0:
1281
+ ev = "OPENS"
1282
+ elif w == G["wmax"] and w0 < G["wmax"]:
1283
+ ev = "REACHES w_max"
1284
+ elif w < w0 and G["dir"] >= 0:
1285
+ ev = "FALLS BACK"
1286
+ elif w > w0 and G["dir"] < 0:
1287
+ ev = "RISES AGAIN"
1288
+ if w == 0.0 and w0 > 0.0:
1289
+ ev = "CLOSES (w back to 0)"
1290
+ if w != w0:
1291
+ G["dir"] = 1 if w > w0 else -1
1292
+ if ev is not None:
1293
+ print(f"[taskwalk] active-sat gate {ev}: epoch {n} (step {t}): signal {sig:.1f}, r {G['r']:.1f}, c {G['c']:.2f}, w {w0:.4g} -> {w:.4g}{tag}", flush=True)
1294
+ if n % 40 == 0 or n == 1:
1295
+ print(f"[taskwalk] active-sat gate: epoch {n} (step {t}): signal {sig:.1f} (standing worlds zeroed: {nstand}), r {G['r']:.1f} "
1296
+ f"(theta {G['theta']:g}), c {G['c']:.2f}, w {w:.4g}{tag}", flush=True)
1297
+
1298
+ def _tw_advance_w_sched(self):
1299
+ """Walk each scheduled TASKWALK_W_* weight from its start value to its _END. No-op with none set.
1300
+
1301
+ Writes onto `self.taskwalk` exactly as `_tw_advance_fall_h` writes `fall_h`, so a term reads its
1302
+ weight the same way whether or not it is scheduled -- nothing in the reward needs to know.
1303
+ """
1304
+ for name, w0, w1, steps, after in self._tw_w_sched:
1305
+ frac = min(1.0, max(0.0, self._train_steps - after) / float(steps))
1306
+ self.taskwalk.set_weight(name, w0 + (w1 - w0) * frac) # (set_weight: the float, and its tensor under TW1 S2a)
1307
+ for name, w1, w2, steps, after in getattr(self, "_tw_w_sched2", []): # the second segment, once it has begun
1308
+ if self._train_steps >= after:
1309
+ frac = min(1.0, (self._train_steps - after) / float(steps))
1310
+ self.taskwalk.set_weight(name, w1 + (w2 - w1) * frac)
1311
+
1312
+ def _tw_advance_v_lo(self):
1313
+ """Raise the commanded-speed FLOOR toward TASKWALK_V_LO_END. No-op unless _END is set.
1314
+
1315
+ Paired with `_tw_advance_v_hi`: run both to the same end value and the per-episode draw
1316
+ U(V_LO, V_HI) collapses to that value. See the declaration for why the curriculum needs it."""
1317
+ if self._tw_v_lo_end is None:
1318
+ return
1319
+ frac = min(1.0, max(0.0, float(self._train_steps - self._tw_v_lo_after)) / float(self._tw_v_lo_steps))
1320
+ self.TW_V_LO = self._tw_v_lo_start + (self._tw_v_lo_end - self._tw_v_lo_start) * frac
1321
+ assert self.TW_V_LO <= self.TW_V_HI + 1e-6, (
1322
+ f"the commanded-speed floor {self.TW_V_LO:.3f} passed the ceiling {self.TW_V_HI:.3f}; the "
1323
+ f"two schedules must share their window and end value")
1324
+
1325
+ def _tw_advance_rsi_mix(self):
1326
+ """Move the RSI draw from the starting pool to the final one. No-op unless a mix is configured.
1327
+
1328
+ Written onto the task rather than passed through `rsi()` so the RNG-stream contract in `_tw_draw`
1329
+ (draw -> rsi -> ground) is untouched."""
1330
+ return
1331
+ s = getattr(self, "_train_steps", 0) - self._tw_rsi_mix_after
1332
+ p = 0.0 if s <= 0 else min(1.0, s / float(self._tw_rsi_mix_steps))
1333
+ self.imitation_task.clip_mix = (self._tw_n_start_clips, p)
1334
+
1335
+ def _tw_advance_fall_h(self):
1336
+ """Walk the fall gate from its start value to TASKWALK_FALL_H_END. No-op unless _END is set."""
1337
+ if self._tw_fall_h_end is None:
1338
+ return
1339
+ frac = min(1.0, max(0.0, self._train_steps - self._tw_fall_h_after) / float(self._tw_fall_h_steps))
1340
+ self.taskwalk.fall_h = self._tw_fall_h_start + (self._tw_fall_h_end - self._tw_fall_h_start) * frac
1341
+
1342
+ def _tw_ramp_begin(self, env_ids):
1343
+ """Seed the command ramp from the body's ACTUAL forward speed. Call AFTER the reset state is in
1344
+ `self.q`/`self.qd` -- that is the whole point, see the note in `_tw_draw`.
1345
+
1346
+ qvel's free base is [angular(3), linear(3)], so 3:6 is the linear block -- but that block is in the
1347
+ ROOT's frame, while the reward scores WORLD COM x (task_walk_reward.py:333). The two agree only at
1348
+ zero heading, which is why 07_01_loop (yaw 0.0 +-1.6 deg) could not tell them apart; 91_35_loop, at
1349
+ yaw -168.8 deg, travels +0.89 m/s world while its qd[3] reads -0.80. Rotate into world so the ramp
1350
+ starts from the number the reward will actually measure.
1351
+ """
1352
+ return
1353
+ if not bool(self._tw_ramp_pending[env_ids].any()):
1354
+ return
1355
+ with torch.no_grad():
1356
+ qq = self.q[3:7, env_ids].detach() # root quaternion, w-first
1357
+ w, x, y, z = qq[0], qq[1], qq[2], qq[3]
1358
+ vb = self.qd[3:6, env_ids].detach() # linear velocity, root frame
1359
+ v_world_x = ((1 - 2 * (y * y + z * z)) * vb[0] # row 0 of R(quat) . vb
1360
+ + 2 * (x * y - w * z) * vb[1]
1361
+ + 2 * (x * z + w * y) * vb[2])
1362
+ v = self.taskwalk.v_tgt.clone()
1363
+ self._tw_v_start[env_ids] = v_world_x.to(v.dtype)
1364
+ v[env_ids] = self._tw_v_start[env_ids]
1365
+ self.taskwalk.v_tgt = v
1366
+ self._tw_ramp_pending[env_ids] = False
1367
+
1368
+ def _tw_advance_v_fixed_schedule(self, control_dt):
1369
+ """TASKWALK_V_FIXED_SCHEDULE (eval only): the command at each world's time since its reset (progress x control_dt). No-op unless set."""
1370
+ if getattr(self, "_tw_vfs", None) is None:
1371
+ return
1372
+ assert self.eval_mode, "TASKWALK_V_FIXED_SCHEDULE is EVAL ONLY (the env is not in eval_mode)"
1373
+ with torch.no_grad():
1374
+ ts, vs = (x.to(self.device) for x in self._tw_vfs)
1375
+ i = torch.searchsorted(ts, self.progress.to(torch.float64) * float(control_dt), right=True) - 1
1376
+ self.taskwalk.v_tgt = vs[i].to(self.taskwalk.v_tgt.dtype)
1377
+
1378
+ def _tw_advance_v_ramp(self):
1379
+ """Close v_tgt on the command by one control step. No-op unless TASKWALK_V_RAMP_STEPS > 0."""
1380
+ return
1381
+ with torch.no_grad():
1382
+ self._tw_v_left.clamp_(min=0.0)
1383
+ frac = self._tw_v_left / float(self.TW_V_RAMP) # 1 at reset -> 0 when done
1384
+ self.taskwalk.v_tgt = self._tw_v_cmd + (self._tw_v_start - self._tw_v_cmd) * frac
1385
+ self._tw_v_left.sub_(1.0).clamp_(min=0.0)
1386
+
1387
+ # ---------------------------------------------------------------- reward
1388
+
1389
+ def _tw_reward(self, a_mean, control_dt):
1390
+ # BEFORE anything reads v_tgt this step. Called here rather than in the env's step() so the reward
1391
+ # and the observation (which is built after the reward) see the SAME v_tgt for this step.
1392
+ self._tw_advance_v_ramp()
1393
+ self._tw_advance_v_fixed_schedule(control_dt)
1394
+ self._tw_advance_heading(control_dt) # the command the reward reads and the observation then shows
1395
+ self._tw_advance_v_hi()
1396
+ self._tw_advance_v_lo() # AFTER the ceiling, so the floor's assert sees this step's value
1397
+ self._tw_advance_fall_h()
1398
+ self._tw_advance_w_sched()
1399
+ self._tw_advance_rsi_mix()
1400
+ if not hasattr(self, "_tw_com_prev"):
1401
+ self._tw_com_prev = None
1402
+ if not hasattr(self, "_tw_lce_fresh"):
1403
+ self._tw_lce_couple = bool(int(os.environ.get("TASKWALK_LCE_DOT_COUPLED", "0")))
1404
+ self._tw_lce_prev_graph = None
1405
+ self._tw_lce_fresh = torch.zeros(self.num_envs, dtype=torch.bool, device=self.device)
1406
+ fk = getattr(self, "_tw_fk_pre", None) # TW1 K2: the same call, made before the latch (_post_physics)
1407
+ if fk is not None:
1408
+ pos, quat, com = fk
1409
+ self._tw_fk_pre = None
1410
+ else:
1411
+ pos, quat, com = self._monitor.body_poses_subset(
1412
+ self.q, self._tw_bodies, True) # need_com: r_speed_track is COM-based
1413
+ foot_pos = [pos[b] for b in self._tw_feet] # the fall test is COM height ABOVE the feet
1414
+ if self._tw_bolt_on: # R17 (see _tw_setup): Bolt's lane terminations, OR-ed into _tw_fell below; no gradient path
1415
+ with torch.no_grad():
1416
+ bt = torch.zeros_like(self.q[0], dtype=torch.bool)
1417
+ if self._tw_bolt_lane_w > 0.0:
1418
+ tr, tl = self._tw_bolt_toes
1419
+ bt = bt | (pos[tr][1].abs() > self._tw_bolt_lane_w) | (pos[tl][1].abs() > self._tw_bolt_lane_w)
1420
+ if self._tw_bolt_head > 0.0:
1421
+ w_, x_, y_, z_ = self.q[3], self.q[4], self.q[5], self.q[6]
1422
+ bt = bt | (torch.atan2(2.0 * (x_ * y_ + w_ * z_), 1.0 - 2.0 * (y_ * y_ + z_ * z_)).abs() > self._tw_bolt_head)
1423
+ self._tw_bolt_term = bt
1424
+ # Opt-in: hand the reward the LOWEST POINT OF THE FOOT'S CONTACT SPHERES instead of the calcaneus
1425
+ # origins, so the gate measures COM above the ground rather than above a body frame. Same maths as
1426
+ # the grounding in _tw_ground, restricted to the foot spheres. See _tw_setup for why.
1427
+ fall_z = None
1428
+ foot_h2 = None
1429
+ if self._tw_fall_foot_geom:
1430
+ idx = self._tw_foot_sph
1431
+ bodies = self._tw_foot_sph_bodies # (setup's list; no per-step int() sync)
1432
+ P = torch.stack([pos[b] for b in bodies]) # (nfoot, 3, n)
1433
+ Q = torch.stack([quat[b] for b in bodies]) # (nfoot, 4, n)
1434
+ W = P + _quat_rotate_batched(Q, self._tw_c_centre[idx].unsqueeze(-1).to(P.dtype))
1435
+ fall_z = (W[:, 2, :] - self._tw_c_radius[idx, None].to(P.dtype)).min(0).values
1436
+ _wl = self._tw_w_live if self._tw_w_sched else (lambda n: abs(getattr(self.taskwalk, n)))
1437
+ if _wl("w_stance_knee_prox") != 0.0 or self._tw_skp_gated: # TASKWALK_W_STANCE_KNEE_PROX: each foot's lowest sphere bottom, in the graph
1438
+ zb = W[:, 2, :] - self._tw_c_radius[idx, None].to(P.dtype)
1439
+ foot_h2 = torch.stack([zb.index_select(0, self._tw_foot_sph_lr[0]).min(0).values,
1440
+ zb.index_select(0, self._tw_foot_sph_lr[1]).min(0).values]) # (2, n) [right, left]
1441
+
1442
+ # ONE gate for every ground-reaction consumer. It used to name two terms; a new term that reads
1443
+ # `foot_grf` and is not added here gets None and trips its own assert at the first step, which
1444
+ # is the intended failure -- but the gate is the thing to update, not the assert.
1445
+ tw = self.taskwalk
1446
+ # A SCHEDULED weight starts at one value and walks to another, so the gate must arm a term's
1447
+ # inputs if the weight is non-zero ANYWHERE on that ramp. Gating on the CURRENT weight hands the
1448
+ # term None for the whole ramp-in and then trips its own assert the instant the weight leaves
1449
+ # zero -- which is the shape a schedule is most useful in (no penalty while the gait is found).
1450
+ _live = self._tw_w_live if self._tw_w_sched else (lambda n: abs(getattr(tw, n)))
1451
+ # `_tw_foot_grf` is a DETACHED per-leg sensor reading, so it is only for the two terms that use
1452
+ # it as a STANCE GATE. `w_grf_rate` and `w_grf_peak` used to be here too and were therefore
1453
+ # `requires_grad=False`; since 2026-09-09 they derive the ground reaction from `com` inside the
1454
+ # reward, which is in the graph, and they no longer cost an engine evaluation here.
1455
+ _want_grf = (_live("w_stance_knee_angle") != 0.0 or _live("w_knee_load") != 0.0
1456
+ or _live("w_touchdown") != 0.0 or _live("w_touchdown_knee") != 0.0 or _live("w_step_width") != 0.0
1457
+ or getattr(self, "_tw_track_phase", "clock") == "heel")
1458
+ # ONE contact_force call even when both components are wanted: it is a full engine evaluation,
1459
+ # and calling it twice per control step to slice a different row of the same tensor is pure loss.
1460
+ _axes = (2,) if _want_grf else ()
1461
+ _g = self._tw_foot_grf(_axes) if _axes else None
1462
+ foot_grf = _g[0] if _g is not None else None
1463
+ if getattr(self, "_tw_track_phase", "clock") == "heel":
1464
+ self._tw_trk_grf = foot_grf.detach() # the tracking phase's heel-strike detector reads it at the next step
1465
+ head_pos = pos[tw.i_head] if _live("w_head_accel") != 0.0 else None
1466
+ # IN-GRAPH per-foot fore-aft GRF, for the per-foot braking price. Not `_tw_foot_grf`, which is detached.
1467
+ foot_grf_x = self._tw_foot_grf_fwd_graph() if _live("w_brake") != 0.0 else None
1468
+ # IN-GRAPH per-foot 3-D GRF (BW), for the positive COM work per limb (world axes; F . v_COM needs no tangent frame)
1469
+ foot_grf3 = (self._tw_foot_grf3_graph() if (_live("w_com_pos_work") != 0.0 or _live("w_state_prior") != 0.0
1470
+ or _live("w_phase_prior") != 0.0)
1471
+ else None)
1472
+ if getattr(self, "OBS_REF", False):
1473
+ # The reference's RL policy observes what its body FEELS about contact and placement
1474
+ # (Walk-RL wrapper/H2190RampVelocityWrapper._get_obs_3d): feet relative to the pelvis, per-leg
1475
+ # GRF in bodyweights, COM velocity. Cached here because _reward runs BEFORE _obs in the same
1476
+ # step, so the observation is same-step, not stale.
1477
+ pelvis = self.q[:3] # free-base origin (pelvis)
1478
+ feet_rel = torch.cat([fp.detach() - pelvis.detach() for fp in foot_pos], dim=0) # (6,n)
1479
+ # per-leg VERTICAL GRF in bodyweights, from the same contact_force call the mirror phase
1480
+ # detector uses -- NOT _tw_knee_load, which needs the MTU tension side channel enabled.
1481
+ import torch as _t
1482
+ with _t.no_grad():
1483
+ _, _cf = self.sim.contact_force(self.q.detach(), self.qd.detach(), self.z.detach())
1484
+ _fz = _cf.reshape(self.ncontact, 3, -1)[:, 2, :]
1485
+ _w = float(self._monitor.total_mass) * 9.81 if hasattr(self._monitor, "total_mass") else 819.0
1486
+ g = _t.stack([_fz[self._mir_r if hasattr(self, "_mir_r") else self._right_contact].sum(0),
1487
+ _fz[self._mir_l if hasattr(self, "_mir_l") else self._left_contact].sum(0)]) / _w
1488
+ com_v = ((com.detach() - self._tw_com_prev) / control_dt if self._tw_com_prev is not None
1489
+ else torch.zeros_like(com.detach()))
1490
+ self._tw_com_prev = com.detach()
1491
+ # DETACHED, like OBS_AUG's contact force: these are sensor readings, and leaving them attached
1492
+ # makes the observation a second path into a graph SAPO frees at every window boundary
1493
+ # (measured: "backward through the graph a second time" on the first update).
1494
+ self._tw_obs_ref = torch.cat([feet_rel, g, com_v], dim=0).t().contiguous().detach() # (n,11)
1495
+ lce_dot = None
1496
+ if (self.taskwalk.w_metabolic_rate != 0.0 or self.taskwalk.w_metabolic_sq != 0.0
1497
+ or self.taskwalk.w_knee_load != 0.0):
1498
+ # Same finite difference OBS_AUG uses (gpu_myoleg26_vec_env.py:542): _lce_prev is detached,
1499
+ # so the rate stays in-graph through the CURRENT lce, which is what carries the gradient.
1500
+ # The force is derived from this and lce inside the reward, NOT taken from the detached
1501
+ # side channel -- that is what made the four-term gradient point the wrong way.
1502
+ lce_dot = (self.lce - self._lce_prev) / control_dt
1503
+ # THE DETACH IS ONE-SIDED, AND MEASURED TO DOMINATE THIS TERM'S GRADIENT. With `_lce_prev`
1504
+ # detached the graph keeps d(v)/d(lce_t) = +1/control_dt = 100 and DROPS the matching
1505
+ # -1/control_dt * d(lce_{t-1})/d(.). The policy moves consecutive fibre lengths together, so
1506
+ # those two largely cancel; keeping one leaves a spurious 1/dt-sized gradient. Measured
1507
+ # 2026-09-03 on real rollouts: the mechanical pair is 7% of the metabolic reward's VALUE and
1508
+ # 90% of its d/d(lce); restoring the second path drops that to 9%, i.e. to its value share.
1509
+ # The detach itself is correct for the OBSERVATION it was copied from -- not for a reward.
1510
+ #
1511
+ # The correction is VALUE-FREE by construction: `x - x.detach()` is exactly 0 in the forward
1512
+ # pass and carries d/dx = 1, so `lce_dot` stays bit-identical and only the gradient changes.
1513
+ # That keeps every existing metabolic cell reproducible with the flag off AND on.
1514
+ if self._tw_lce_couple and self._tw_lce_prev_graph is not None:
1515
+ corr = (self._tw_lce_prev_graph - self._tw_lce_prev_graph.detach()) / control_dt
1516
+ # An env that reset last step has a previous lce from a DIFFERENT trajectory; the
1517
+ # value path already zeroes there via _lce_prev, so zero the gradient path too.
1518
+ # Unconditional (TW1, 11-10): the `.any()` guard was a host sync every control step; with no reset env the
1519
+ # mask is all False and masked_fill returns the same values (its backward the same gradient).
1520
+ corr = corr.masked_fill(self._tw_lce_fresh.unsqueeze(0), 0.0)
1521
+ lce_dot = lce_dot - corr
1522
+ self._tw_lce_prev_graph = self.lce
1523
+ self._tw_lce_fresh = torch.zeros_like(self._tw_lce_fresh)
1524
+ feet_xy = None
1525
+ if getattr(self, "_tw_fs", None) is not None:
1526
+ feet_xy = self._tw_footstep_update(foot_pos, control_dt) # before the tracking error: it picks the step's clip
1527
+ track_err = None
1528
+ if getattr(self, "_tw_track", False):
1529
+ from diffneusim.rl.task_walk_reward import track_pose_error
1530
+ if getattr(self, "_tw_steplib", None) is not None:
1531
+ ph = (self._tw_fs.t / self._tw_sl_T).clamp(0.0, 0.999) # the step's clip over its play time, then held
1532
+ q_ref, _ = self._tw_steplib.task.ref_at(ph)
1533
+ track_err = track_pose_error(self.q, q_ref.detach(), self._tw_track_scalar, self._tw_track_quats)
1534
+ # a provisional plan pays nothing (as the footstep term): its clip was chosen from a guess
1535
+ track_err = torch.where(self._tw_fs.pending, torch.full_like(track_err, 1e3), track_err)
1536
+ self._tw_sl_err = track_err.detach() # for tools/steer/footstep_probe.py
1537
+ else:
1538
+ q_ref, _ = self.imitation_task.ref_at(self.phase)
1539
+ track_err = track_pose_error(self.q, q_ref.detach(), self._tw_track_scalar, self._tw_track_quats)
1540
+ r = self.taskwalk(self.q, self.qd, a_mean, self._tw_last_u, com, quat, control_dt, foot_pos,
1541
+ fall_z=fall_z, lce=self.lce, lce_dot=lce_dot, foot_grf=foot_grf, track_err=track_err,
1542
+ head_pos=head_pos, foot_grf_x=foot_grf_x, foot_grf3=foot_grf3, foot_h2=foot_h2)
1543
+ if feet_xy is not None:
1544
+ # the footstep term is the env's (it reads the plan's state); in the graph through the swing foot's position. A STEP
1545
+ # FAIL is priced as a fall, as DeepLoco makes them one (HasFallen includes mStepFail; the fallen step pays 0): the
1546
+ # fall penalty, and no footstep payment on that step (it would fall in the new step's first half and pay W)
1547
+ fail = self._tw_fs_fail.to(r.dtype)
1548
+ ee_err = None
1549
+ if getattr(self, "_tw_step_ee", False):
1550
+ fz = torch.stack([foot_pos[0][2], foot_pos[1][2]]) if getattr(self, "_tw_step_ee_h", False) else None
1551
+ ee_err = self._tw_step_ee_err(feet_xy, fz)
1552
+ k_ee = self._tw_fs.reward(feet_xy, self._tw_fs_scale, ee_err)
1553
+ r_fs = self._tw_fs_w * k_ee * (1.0 - fail)
1554
+ r = r + r_fs - self.taskwalk.w_fall_penalty * fail
1555
+ self._tw_fs_last_r = r_fs.detach()
1556
+ if getattr(self, "_tw_llc", None) is not None:
1557
+ # TASKWALK_LLC: DeepLoco's CalcRewardStep in place of everything above (the walker's terms, its fall penalty,
1558
+ # the footstep weight); k_ee is its end-effector kernel
1559
+ r = self._tw_llc_reward(k_ee, foot_pos, fail, quat).to(r.dtype)
1560
+ if self._tw_llc["effort"]:
1561
+ # TASKWALK_LLC_EFFORT: minus the walker's muscle price (its activation and metabolic terms at their weights);
1562
+ # DeepLoco's torque-driven biped has none to port (docs-dev/deeploco/20261026_1000_llc_effort)
1563
+ tw = self.taskwalk
1564
+ assert tw.w_activation != 0.0 or tw.w_metabolic_rate != 0.0 or tw.w_metabolic_sq != 0.0, (
1565
+ "TASKWALK_LLC_EFFORT=1 with every effort weight 0 prices nothing")
1566
+ r = r - tw.last_effort_t.to(r.dtype)
1567
+ if tw.log_terms:
1568
+ self._tw_llc_terms_t["effort"] = -tw.last_effort_t.to(r.dtype) # its signed share: the shares still sum to r
1569
+ if self._tw_diag_midknee_w > 0.0:
1570
+ # DIAGNOSTIC ONLY (TASKWALK_DIAG_MIDKNEE_W, default 0 = bit-identical): a posture CONSTRAINT for the H_obj / H_opt test of
1571
+ # the bent mid-stance knee (2026-10-08). Caps the knee flexion of a loaded leg (foot > _GATE_BW) in the window _T0.._T1 s
1572
+ # after that foot's load onset; the defaults (12 deg, 0.25-0.45 s) are the human's own maximum over 25-45% of a ~1.0 s
1573
+ # stride (Fukuchi 2018, 1.3 m/s: 11.7 -> 3.2 -> 3.4 deg), so the human curve passes it. Per rad beyond the cap, in the
1574
+ # graph; the cap descends from _MAX0 to _MAX over _STEPS control steps after _AFTER. Never in a result cell.
1575
+ with torch.no_grad():
1576
+ cf = _bridge.contact_force_gpu(self.q.detach(), self.qd.detach(), self.z.detach(), self.sim.path)
1577
+ fz = cf.reshape(self._tw_ncon, 3, -1)[:, 2, :]
1578
+ bw = (self._tw_mass_kg() * 9.81)
1579
+ on = torch.stack([fz[i].sum(0) for i in self._tw_mk_idx]) / bw > self._tw_mk_gate # (2, n)
1580
+ onset = on & ~self._tw_mk_on
1581
+ self._tw_mk_t = torch.where(onset, torch.zeros_like(self._tw_mk_t), self._tw_mk_t + control_dt)
1582
+ self._tw_mk_on = on
1583
+ win = on & (self._tw_mk_t >= self._tw_mk_t0) & (self._tw_mk_t <= self._tw_mk_t1)
1584
+ fr = min(max((self._train_steps - self._tw_mk_after) / max(self._tw_mk_steps, 1), 0.0), 1.0)
1585
+ cap = self._tw_mk_max0 + (self._tw_mk_max - self._tw_mk_max0) * fr
1586
+ flex = tw.knee_sign * torch.stack([self.q[tw.i_knee_r], self.q[tw.i_knee_l]]) # (2, n), + = flexed
1587
+ over = ((flex - cap).clamp_min(0.0) * win.to(flex.dtype)).sum(0).to(r.dtype)
1588
+ if self.taskwalk.log_terms:
1589
+ self.taskwalk.last_terms_t["diag_midknee"] = over.detach()
1590
+ r = r - self._tw_diag_midknee_w * over
1591
+ # The authors' fall is `int(terminated)` -- ONE-TIME, at termination. Recording the flag here and
1592
+ # terminating on it makes ours one-time by construction; left as a per-step test it fired every
1593
+ # step of a collapsed episode and the -250 weight swamped everything else.
1594
+ self._tw_fell = self.taskwalk.last_fall.bool()
1595
+ if self._tw_bolt_on: # R17: Bolt's lane terminations end the episode as his do (no fall penalty for them)
1596
+ self._tw_fell = self._tw_fell | self._tw_bolt_term
1597
+ if self._tw_sterm_frac > 0.0 and not self.eval_mode:
1598
+ # M4 (see _tw_setup): the trailing COM speed against f x the command; a shortfall ends the episode as a fall and pays its penalty
1599
+ with torch.no_grad():
1600
+ vc = torch.broadcast_to(torch.as_tensor(self.taskwalk.v_tgt, device=com.device), com[0].shape)
1601
+ short = speed_shortfall_step(self._tw_sterm_buf, self.progress, com[0].detach(), vc, self._tw_sterm_frac,
1602
+ self._tw_sterm_g, control_dt) & ~self._tw_fell
1603
+ self._tw_sterm_n += short.sum()
1604
+ r = r - self.taskwalk.w_fall_penalty * short.to(r.dtype)
1605
+ self._tw_fell = self._tw_fell | short
1606
+ return r
1607
+
1608
+ # ---------------------------------------------------------------- helpers
1609
+
1610
+ def _tw_foot_grf(self, axes=(2,)):
1611
+ """[(2,n), ...] per-foot ground reaction in bodyweights, [right, left], one entry per requested
1612
+ world axis. No muscle tension.
1613
+
1614
+ `axes` picks the world components: 2 = VERTICAL (what every existing caller wants), 0 = FORE-AFT,
1615
+ 1 = LATERAL. World is z-up, x forward on both models this runs on. Several axes in ONE call
1616
+ because `contact_force` is a full engine evaluation, not a lookup.
1617
+
1618
+ Split out of `_tw_knee_load` because a stance GATE and a knee LOAD are different quantities:
1619
+ the load adds the knee-spanning muscles' tension, which is large in swing whenever those
1620
+ muscles are active, so gating stance on it would call a swinging leg loaded. It also needs the
1621
+ MTU side channel, which is only armed for W_KNEE. This needs neither.
1622
+ """
1623
+ with torch.no_grad():
1624
+ _, cf = self.sim.contact_force(self.q.detach(), self.qd.detach(), self.z.detach())
1625
+ # contact_force returns f64 while the selector is f32: match explicitly rather than relying on
1626
+ # promotion, which torch does NOT do for matmul (it raises).
1627
+ f3 = cf.reshape(self._tw_ncon, 3, -1).to(self._tw_grf_sel.dtype)
1628
+ bw = (self._tw_mass_kg() * 9.81)
1629
+ return [(self._tw_grf_sel @ f3[:, a, :]) / bw for a in axes]
1630
+
1631
+ def _tw_foot_grf_graph(self, axis):
1632
+ """(2,n) per-foot ground reaction along world `axis` in bodyweights, [right, left], IN THE GRAPH.
1633
+
1634
+ The same force `_tw_foot_grf` reads (mtu_contact_force at the post-step (q, qd, z)), through
1635
+ gpu_bridge.contact_force_gpu, whose backward is the engine's contact-force VJP (mtu_contact_force_bwd;
1636
+ FD-gated on real rollouts by tools/contact_force_vjp_gate.py, both the stick and the kinetic branch).
1637
+ The gradient reaches q, qd AND z -- z through the step's stiction-anchor recurrence."""
1638
+ cf = gpu_bridge.contact_force_gpu(self.q, self.qd, self.z, self.sim.path)
1639
+ f3 = cf.reshape(self._tw_ncon, 3, -1).to(self._tw_grf_sel.dtype)
1640
+ bw = (self._tw_mass_kg() * 9.81)
1641
+ return (self._tw_grf_sel @ f3[:, axis, :]) / bw
1642
+
1643
+ def _tw_foot_grf_fwd_graph(self):
1644
+ """(2,n) per-foot FORE-AFT ground reaction in bodyweights, IN THE GRAPH, along each env's GROUND TANGENT in the
1645
+ walking direction. The slope curriculum tilts the plane about y (normal n = (-sin a, 0, cos a)), so the
1646
+ tangent is t = (cos a, 0, sin a) = (n_z, 0, -n_x) and F.t = n_z F_x - n_x F_z. Reading world +x instead (the
1647
+ term's first form, 2026-09-29) put the tilted normal force itself on the axis: sin(10 deg) = 0.17 BW on a 10-deg
1648
+ slope, half the 0.35 threshold, so uphill steps read as braking. On flat ground (slopes off) this is world +x,
1649
+ the same tensor as before, bit-identical."""
1650
+ if getattr(self, "_tw_heading_on", False):
1651
+ # Along the COMMANDED heading on flat ground (TASKWALK_HEADING asserts the slopes off): F . (cos h, sin h, 0).
1652
+ cf = gpu_bridge.contact_force_gpu(self.q, self.qd, self.z, self.sim.path)
1653
+ f3 = cf.reshape(self._tw_ncon, 3, -1).to(self._tw_grf_sel.dtype)
1654
+ h = self._tw_heading.detach().to(f3.dtype)
1655
+ f_fwd = torch.cos(h)[None, :] * f3[:, 0, :] + torch.sin(h)[None, :] * f3[:, 1, :]
1656
+ bw = (self._tw_mass_kg() * 9.81)
1657
+ return (self._tw_grf_sel @ f_fwd) / bw
1658
+ if not getattr(self, "_tw_slopes_live", False):
1659
+ return self._tw_foot_grf_graph(0)
1660
+ cf = gpu_bridge.contact_force_gpu(self.q, self.qd, self.z, self.sim.path)
1661
+ f3 = cf.reshape(self._tw_ncon, 3, -1).to(self._tw_grf_sel.dtype)
1662
+ # A COPY, not the buffer: `_tw_draw_slopes` rewrites `_tw_normals` IN PLACE for every restarting env, and the
1663
+ # multiply below saves its operand for the backward -- using the buffer itself crashed the first BPTT update
1664
+ # after the braking weight left 0 ("modified by an inplace operation", slope10_bt_s1 at ep200).
1665
+ n = self._tw_normals.detach().clone().to(f3.dtype) # (3, n_env), unit
1666
+ f_fwd = n[2][None, :] * f3[:, 0, :] - n[0][None, :] * f3[:, 2, :] # (ncon, n_env)
1667
+ bw = (self._tw_mass_kg() * 9.81)
1668
+ return (self._tw_grf_sel @ f_fwd) / bw
1669
+
1670
+ def _tw_foot_grf3_graph(self):
1671
+ """(3, 2, n) per-foot ground reaction in bodyweights, world axes, [right, left], IN THE GRAPH (the engine contact
1672
+ force's VJP): the input of the positive COM work per limb (TASKWALK_W_COM_POS_WORK)."""
1673
+ cf = gpu_bridge.contact_force_gpu(self.q, self.qd, self.z, self.sim.path)
1674
+ f3 = cf.reshape(self._tw_ncon, 3, -1).to(self._tw_grf_sel.dtype)
1675
+ bw = (self._tw_mass_kg() * 9.81)
1676
+ return torch.stack([self._tw_grf_sel @ f3[:, ax, :] for ax in range(3)], 0) / bw
1677
+
1678
+ def _tw_mass_kg(self):
1679
+ if getattr(self, "_tw_mass_cache", None) is None:
1680
+ self._tw_mass_cache = float(sum(float(b.get("mass", 0.0)) for b in self._monitor.bodies))
1681
+ assert self._tw_mass_cache > 1.0, f"model mass {self._tw_mass_cache} kg looks wrong"
1682
+ return self._tw_mass_cache
1683
+
1684
+ def _tw_ground_pose(self, q0, env_ids):
1685
+ """Place a pose ON the ground: shift the root along each env's plane normal until the lowest
1686
+ contact sphere just touches.
1687
+
1688
+ Without this the task-walk reset is a CATAPULT. The imitation path never needed it because RSI
1689
+ overwrites q0 with a reference pose that reground_loop already grounded; the keyframe alone, minus
1690
+ the env's drop, buries the feet 90 mm, and at k=1e5 that is an initial vertical GRF of 89.6 kN =
1691
+ 108 body weights. Every episode ended in ~6 steps with the pelvis 60 cm in the air, and it read as
1692
+ `toppled` rather than anything contact-shaped.
1693
+
1694
+ Done per env along ITS OWN normal, because under the slope curriculum "lowest" is not "smallest z".
1695
+ """
1696
+ n = q0.shape[1]
1697
+ # INDEX BY env_ids, not [:, :n]. q0 holds the RESTARTING envs, whose ids are arbitrary; slicing the
1698
+ # first n columns grounded env 7 onto env 0's plane. Silent on flat ground and wrong on every slope.
1699
+ nrm = (self._tw_normals[:, env_ids] if getattr(self, "_tw_slopes_live", False)
1700
+ else torch.tensor([0.0, 0.0, 1.0], device=q0.device)[:, None].expand(3, n))
1701
+ with torch.no_grad():
1702
+ # SUBSET FK over the contact-carrying bodies, then ONE batched rotate over all spheres. The
1703
+ # obvious per-sphere Python loop is launch-bound to the point of absurdity: ten spheres x ~30
1704
+ # elementwise ops on a 15-column tensor is ~300 kernels of pure launch overhead, measured at
1705
+ # 6.74 ms -- 76% of the whole reset, and independent of how many envs restart.
1706
+ pos, quat, _ = self._monitor.body_poses_subset(q0, self._tw_contact_bodies, False)
1707
+ P = torch.stack([pos[b] for b in self._tw_c_body]) # (ncon, 3, n)
1708
+ Q = torch.stack([quat[b] for b in self._tw_c_body]) # (ncon, 4, n)
1709
+ W = P + _quat_rotate_batched(Q, self._tw_c_centre.unsqueeze(-1).to(q0.dtype))
1710
+ gap = ((W * nrm.unsqueeze(0)).sum(1) - self._tw_c_radius[:, None].to(q0.dtype)).min(0).values
1711
+ q0 = q0.clone()
1712
+ # the shift is a WORLD vector; map it into the root joint's own translation ordering
1713
+ shift = self._tw_root_from_world.to(q0.dtype) @ (nrm * gap[None, :])
1714
+ q0[:3] -= shift # translate along the normal so min gap == 0
1715
+ return q0
1716
+
1717
+ def _tw_draw_height(self, env_ids):
1718
+ """Draw the per-env commanded COM height, the same way the commanded SPEED is drawn.
1719
+
1720
+ No-op unless TASKWALK_W_PELVIS_HEIGHT or TASKWALK_FALL_MARGIN is set, so every earlier run is unchanged.
1721
+ Uniform over [h_lo, h_hi]; the range defaults to the measured reachable span (see the reward's
1722
+ note). Uses self.rng like the speed draw, so it takes its place in the run's identity -- and it is
1723
+ called BEFORE _tw_draw_slopes so the order is fixed for seeded reproducibility.
1724
+ """
1725
+ tw = self.taskwalk
1726
+ if tw.w_pelvis_height == 0.0 and tw.fall_margin == 0.0:
1727
+ return
1728
+ lo, hi = tw.h_lo, tw.h_hi
1729
+ if tw.h_tgt is None or tw.h_tgt.shape[0] != self.num_envs:
1730
+ tw.h_tgt = torch.rand(self.num_envs, generator=self.rng, device=self.device,
1731
+ dtype=self.q.dtype) * (hi - lo) + lo
1732
+ else:
1733
+ h = tw.h_tgt.clone()
1734
+ h[env_ids] = torch.rand(len(env_ids), generator=self.rng, device=self.device,
1735
+ dtype=h.dtype) * (hi - lo) + lo
1736
+ tw.h_tgt = h
1737
+
1738
+ def _tw_draw_slopes(self, env_ids):
1739
+ """Sample a slope per RESTARTING env from the difficulty-weighted categorical, and write its unit
1740
+ normal into the (3, n_env) buffer, then re-upload it (_tw_upload_normals). A ramp of `a` degrees about the
1741
+ world y axis has normal (-sin a, 0, cos a), which is +z exactly at a = 0."""
1742
+ if not getattr(self, "_tw_slopes_live", False):
1743
+ return
1744
+ k = torch.multinomial(self._tw_slope_score, len(env_ids), replacement=True)
1745
+ self._tw_env_slope[env_ids] = k
1746
+ a = torch.deg2rad(self._tw_slope_deg[k])
1747
+ self._tw_normals[0, env_ids] = -torch.sin(a)
1748
+ self._tw_normals[1, env_ids] = 0.0
1749
+ self._tw_normals[2, env_ids] = torch.cos(a)
1750
+ self._tw_upload_normals()
1751
+
1752
+ def _tw_upload_normals(self):
1753
+ """Hand the engine the normals just written. Without this, only the ContactParams copy whose dtype
1754
+ matches this tensor saw the new slopes; the other kept the flat normals of the setup upload (see
1755
+ mtu_gpu.refresh_ground_normals for the measured consequence)."""
1756
+ _mtu_gpu.refresh_ground_normals(self._tw_normals, self.model)
1757
+
1758
+ def _tw_slope_feedback(self, env_ids, fell):
1759
+ """Difficulty update: a fall on a slope raises its score (revisit it), a completion lowers it,
1760
+ bounded below so easy terrain is still sampled and the policy does not forget flat ground."""
1761
+ if not getattr(self, "_tw_slopes_live", False) or len(env_ids) == 0:
1762
+ return
1763
+ k = self._tw_env_slope[env_ids]
1764
+ d = torch.where(fell, torch.full_like(k, 1, dtype=self._tw_slope_score.dtype) * self.TW_SLOPE_UP,
1765
+ torch.full_like(k, 1, dtype=self._tw_slope_score.dtype) * -self.TW_SLOPE_DN)
1766
+ self._tw_slope_score.index_add_(0, k, d)
1767
+ self._tw_slope_score.clamp_(min=self.TW_SLOPE_MIN)
1768
+
1769
+ def _tw_command_speed(self, env_ids=None):
1770
+ """Commanded speed per env.
1771
+
1772
+ PER-ENV UNIFORM by default, NOT the authors' global cyclic schedule, and the reason is the
1773
+ algorithm rather than taste. Their schedule steps one global target 0.7 -> 1.6 -> 0.7 and works
1774
+ because SAC replays from a 3M buffer, so every gradient step still sees the whole speed range.
1775
+ SAPO is on-policy pathwise with no buffer: one global target means every update in that window
1776
+ sees ONE speed, the conditioning input is constant across the batch and carries no signal, and the
1777
+ final policy is biased to whatever the schedule ended on (with period 400 over 6000 epochs, exactly
1778
+ 0.7). Drawing per env keeps their intent -- cover 0.7-1.6 -- under an algorithm that needs the
1779
+ range inside each batch. TASKWALK_V_CYCLIC=1 restores the literal global schedule.
1780
+ """
1781
+ n = self.num_envs if env_ids is None else len(env_ids)
1782
+ if self.TW_V_FIXED is not None:
1783
+ # EVAL knob: pin the command so a rollout answers "what does this policy do when ASKED for
1784
+ # 0.7 vs 1.6 m/s". With the training-time random draw you cannot separate the conditioning
1785
+ # from the spread of starts, which is the whole question a speed-conditioned policy has to
1786
+ # answer. Training leaves it None.
1787
+ return torch.full((n,), self.TW_V_FIXED, device=self.device)
1788
+ if self.TW_V_CYCLIC:
1789
+ ph = (float(self._train_steps) / max(self.TW_V_PERIOD, 1)) % 1.0
1790
+ tri = 2.0 * ph if ph < 0.5 else 2.0 * (1.0 - ph)
1791
+ return torch.full((n,), self.TW_V_LO + (self.TW_V_HI - self.TW_V_LO) * tri, device=self.device)
1792
+ return (self.TW_V_LO + (self.TW_V_HI - self.TW_V_LO)
1793
+ * torch.rand(n, device=self.device, generator=self.rng))