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,2027 @@
1
+ """Model-agnostic DeepMimic imitation (Peng et al. 2018) for the muscle vec-envs.
2
+
3
+ Composition, not inheritance. An env owns:
4
+ * a `Morphology` -- model facts as DATA, mostly derived from the dnmodel (quaternion DoF spans,
5
+ per-body mass/COM, the tracked-pose index set). The two facts that CANNOT be safely auto-derived
6
+ stay explicit: the end-effector bodies (a full humanoid tracks hands, which never contact the
7
+ ground, so contact-based derivation is wrong) and the root fwd/height/lat q-layout.
8
+ * an optional `ImitationTask` -- the DeepMimic logic. It is STATELESS w.r.t. per-step state: the
9
+ ENV owns every mutable value (phase, prev_phase, h_prev, eval_mode) and the shared RNG and threads
10
+ them through the task's pure methods. This keeps the RNG stream and the autograd graph byte-for-byte
11
+ identical to the pre-refactor inline/mixin code (verified max|delta|=0, gradients included), and
12
+ lets a new model (e.g. full-body) drop in by supplying only its Morphology.
13
+
14
+ Gated by DN_IMITATION at the env level; when off the env uses its own reward (bit-parity).
15
+
16
+ The math here mirrors the pre-refactor mixin op-for-op (float addition order, left-fold reductions,
17
+ and the dnmodel-body iteration order of the quaternion blocks are load-bearing under fp32).
18
+ """
19
+ import dataclasses
20
+ import json
21
+ import math
22
+ import os
23
+ import pathlib
24
+ import re
25
+ from typing import List, Optional, Tuple
26
+
27
+ import numpy as np
28
+ import torch
29
+
30
+ from diffneusim.rl.imitation_reward_v2 import GROUPS, GroupedAdaptiveReward, _fd_authority
31
+ from diffneusim.rl.imitation_reward_v3 import GROUPS as GROUPS3, JacobianAbsoluteReward, build_component_weights
32
+ from diffneusim.rl import mvae_recon as _R
33
+
34
+ # "hinge" is the primitive spelling inside a compound `joints` array; "revolute" is the body-level one.
35
+ _JOINT_WIDTH = {"free": (7, 6), "freejoint": (7, 6), "ball": (4, 3), "revolute": (1, 1),
36
+ "hinge": (1, 1), "slide": (1, 1), "fixed": (0, 0)}
37
+ from diffneusim._paths import ROOT as _ROOT # (3a) the repo root
38
+
39
+
40
+ def _resolve_ref_paths(ref_path):
41
+ """One reference, several comma-separated ones, or a .txt listing one per line -> a list of paths.
42
+
43
+ A LIST FILE rather than a very long env var: the multi-clip corpus is ~170 entries, and a run's identity
44
+ is its env vars (docs), so a 12 kB DN_REF would make run_config.json unreadable. The file is named in
45
+ the env var, so the run still records exactly which set it used.
46
+ """
47
+ raw = str(ref_path)
48
+ if raw.endswith(".txt"):
49
+ lines = [ln.strip() for ln in pathlib.Path(raw).read_text().splitlines()]
50
+ out = [ln for ln in lines if ln and not ln.startswith("#")]
51
+ assert out, f"{raw}: no clip paths in the list file"
52
+ else:
53
+ out = [x.strip() for x in raw.split(",") if x.strip()]
54
+ for o in out:
55
+ assert pathlib.Path(o).exists(), f"reference not found: {o}"
56
+ return out
57
+
58
+
59
+ def _owned_dof_layout(jm):
60
+ """[(body_idx, qadr, vadr, wq, wv)] for owned (non-fixed, non-coupled) bodies + running (nq, nv).
61
+ Mirrors the engine's DOF counter (fixed & coupled bodies do not advance it).
62
+
63
+ A COMPOUND body carries an ordered `joints` array instead of a scalar `joint`, and each primitive
64
+ in it advances the counter. Without this branch myoleg26_3d_compound reports nq=13 against a real
65
+ 19 -- silently, since every downstream slice stays in range. It is the reason `adapt_reference`
66
+ appeared to run on the compound model while writing into the wrong columns."""
67
+ q = v = 0
68
+ out = []
69
+ for i, b in enumerate(jm["bodies"]):
70
+ if "coupled" in b:
71
+ continue
72
+ if b.get("joints"):
73
+ assert "joint" not in b, f"body {b.get('name')} declares both `joint` and `joints`"
74
+ wq = wv = 0
75
+ for prim in b["joints"]:
76
+ pq, pv = _JOINT_WIDTH[prim["type"]]
77
+ wq += pq
78
+ wv += pv
79
+ elif b.get("joint", "fixed") != "fixed":
80
+ wq, wv = _JOINT_WIDTH[b["joint"]]
81
+ else:
82
+ continue
83
+ out.append((i, q, v, wq, wv))
84
+ q += wq
85
+ v += wv
86
+ return out, q, v
87
+
88
+
89
+ def _find_ref_source_jm(ref_nq):
90
+ """The committed full-body model whose OWNED nq == ref_nq -- the model a mismatched reference was
91
+ retargeted for. Every full-body variant shares one 156-body skeleton (reductions only weld/couple
92
+ joints, never delete bodies), so a richer parent ref can be column-selected onto any reduction."""
93
+ # myoleg26* too, not just fullbody*: `data/reference/cmu/*_myoleg26_ref.npz` is retargeted to the
94
+ # Ball-hip myoleg26_3d, and a myoleg26 VARIANT (compound hip) has no fullbody parent to source from.
95
+ cand = sorted((_ROOT / "models").glob("fullbody*.dnmodel")) + sorted((_ROOT / "models").glob("myoleg26*.dnmodel"))
96
+ hit = []
97
+ for p in cand:
98
+ jm = json.loads(re.sub(r"^\s*//.*$", "", p.read_text(), flags=re.M))
99
+ if _owned_dof_layout(jm)[1] == ref_nq:
100
+ hit.append((p, jm))
101
+ assert hit, f"no models/{{fullbody,myoleg26}}*.dnmodel with owned nq={ref_nq} to source the reference from"
102
+ # Ambiguity must not be resolved by glob order -- two skeletons can share an nq and differ in LAYOUT.
103
+ names = {tuple((b["name"], b.get("joint", "fixed")) for b in jm["bodies"]) for _, jm in hit}
104
+ assert len(names) == 1, f"nq={ref_nq} matches incompatible sources: {[p.name for p, _ in hit]}"
105
+ return hit[0][1]
106
+
107
+
108
+ def _time_derivative(x, dt, loop):
109
+ """d/dt along axis 0 of a per-frame reference array, by central difference.
110
+
111
+ A LOOP reference is periodic, so the difference wraps (frame T-1 is followed by frame 0). A WHOLE clip
112
+ (`loop=False` in its npz) and an OPEN clip (a single step of the step library, ImitationTask cyclic=False) are
113
+ not: the last frame jumps back to a different pose, so a wrap there puts a spurious velocity spike on both end
114
+ frames (the CMU steps on 14t: Ball-hip |omega| 53 rad/s at the ends against 2.4 inside). Those two use
115
+ one-sided differences instead (numpy's first-order edge rule); every interior frame gets the same central
116
+ difference either way."""
117
+ if loop:
118
+ return (np.roll(x, -1, axis=0) - np.roll(x, 1, axis=0)) / (2.0 * dt)
119
+ assert x.shape[0] >= 2, f"a whole or open clip needs >= 2 frames to difference, got {x.shape[0]}"
120
+ return np.gradient(x, dt, axis=0, edge_order=1)
121
+
122
+
123
+ def _qmul(a, b):
124
+ w1, x1, y1, z1 = a
125
+ w2, x2, y2, z2 = b
126
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
127
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
128
+
129
+
130
+ def _tq_conj(q):
131
+ """Conjugate of quaternions (4, ...) (torch, wxyz)."""
132
+ return torch.cat([q[:1], -q[1:]], 0)
133
+
134
+
135
+ def _tq_log(q):
136
+ """Rotation vector of unit quaternions (4, ...) -> (3, ...), shortest arc; finite value and gradient at identity."""
137
+ q = torch.where(q[:1] < 0.0, -q, q)
138
+ nv = (q[1:] ** 2).sum(0, keepdim=True).clamp_min(1e-24).sqrt()
139
+ return q[1:] * (2.0 * torch.atan2(nv, q[:1]) / nv)
140
+
141
+
142
+ def _tq_angle(a, b):
143
+ """Geodesic angle between unit quaternions (4, n) -> (n,), from the relative quaternion (exact near 0)."""
144
+ w = (a * b).sum(0)
145
+ c = torch.stack([a[0] * b[1] - a[1] * b[0] - a[2] * b[3] + a[3] * b[2],
146
+ a[0] * b[2] + a[1] * b[3] - a[2] * b[0] - a[3] * b[1],
147
+ a[0] * b[3] - a[1] * b[2] + a[2] * b[1] - a[3] * b[0]], 0) # vec part of conj(a) (x) b
148
+ return 2.0 * torch.atan2((c ** 2).sum(0).clamp_min(1e-24).sqrt(), w.abs())
149
+
150
+
151
+ def _axis_angle_quat(axis, ang):
152
+ axis = np.asarray(axis, float)
153
+ n = np.linalg.norm(axis)
154
+ if n < 1e-12:
155
+ return np.array([1.0, 0.0, 0.0, 0.0])
156
+ axis = axis / n
157
+ return np.concatenate([[np.cos(ang / 2.0)], np.sin(ang / 2.0) * axis])
158
+
159
+
160
+ def _coincident_revolute_stack(jm, head):
161
+ """[head, followers...] -- the coincident (pos~0) revolute chain a Ball joint replaced (the euler
162
+ stack). FK-verified that composing these axes' angles reproduces the Ball orientation exactly."""
163
+ B = jm["bodies"]
164
+ ch = {}
165
+ for i, b in enumerate(B):
166
+ ch.setdefault(b.get("parent", -1), []).append(i)
167
+ chain = [head]
168
+ while True:
169
+ kids = [c for c in ch.get(chain[-1], []) if B[c].get("joint") == "revolute" and "coupled" not in B[c]
170
+ and max(abs(float(x)) for x in B[c].get("pos", [0, 0, 0])) < 1e-9]
171
+ if len(kids) == 1:
172
+ chain.append(kids[0])
173
+ else:
174
+ break
175
+ return chain
176
+
177
+
178
+ def _ball_to_stack(quat, axes, ref_dt, loop=True):
179
+ """Ball quaternion trajectory -> the angles of an ordered scalar-hinge stack about `axes`, plus rates.
180
+
181
+ The INVERSE of the euler->Ball compose below. Needed because myoleg26_3d_compound carries its hip as
182
+ an ordered `joints` stack while every committed reference is retargeted to the Ball-hip model, and
183
+ without this the compound cell has to run reference-free -- which is not a fair comparison against a
184
+ cell that has one.
185
+
186
+ Exactness: an n=3 stack spans SO(3), so this is a decomposition and the round-trip is machine-exact.
187
+ That is ASSERTED here, not assumed: this repo has already produced 'flexion -178 deg' from a hip
188
+ chart with the wrong order, and an assert is cheaper than finding that again in a gait.
189
+ """
190
+ from scipy.spatial.transform import Rotation
191
+ assert len(axes) == 3, f"only a 3-hinge stack spans SO(3); got {len(axes)}"
192
+ seq, sign = "", []
193
+ for a in axes:
194
+ a = [float(x) for x in a]
195
+ nz = [k for k in range(3) if abs(a[k]) > 1e-9]
196
+ assert len(nz) == 1 and abs(abs(a[nz[0]]) - 1.0) < 1e-9, f"stack axis {a} is not a signed unit axis"
197
+ seq += "XYZ"[nz[0]]
198
+ sign.append(1.0 if a[nz[0]] > 0 else -1.0)
199
+ # Consecutive axes must differ or the stack is rank-deficient and cannot represent a general
200
+ # rotation. scipy raises a ValueError here; assert first so the message names the MODEL fault.
201
+ assert seq[0] != seq[1] and seq[1] != seq[2], \
202
+ f"stack axes {seq} repeat consecutively -- this hinge stack does not span SO(3)"
203
+ # scipy spells INTRINSIC in UPPERCASE (lowercase is extrinsic), and intrinsic Z-X-Y is the matrix
204
+ # product Rz . Rx . Ry -- the compose order used below. Lowercase here fails the round-trip by only
205
+ # ~1e-2, because at frame 0 the hip angles are small and the two orders agree to first order; the
206
+ # gate below is what separates "wrong convention" from "small angles" at all.
207
+ ang = Rotation.from_quat(np.column_stack([quat[:, 1], quat[:, 2], quat[:, 3], quat[:, 0]])).as_euler(seq)
208
+ ang = ang * np.array(sign)[None, :]
209
+ # ROUND-TRIP GATE: recompose with the same primitive the forward path uses and demand the original back.
210
+ for t in range(0, len(quat), max(1, len(quat) // 16)):
211
+ q = _axis_angle_quat(axes[0], ang[t, 0])
212
+ q = _qmul(q, _axis_angle_quat(axes[1], ang[t, 1]))
213
+ q = _qmul(q, _axis_angle_quat(axes[2], ang[t, 2]))
214
+ d = min(np.abs(q - quat[t]).max(), np.abs(q + quat[t]).max()) # q and -q are the same rotation
215
+ # 1e-6, not 1e-9: the references are stored f32 (|q|-1 measures 1.2e-7), so the round-trip
216
+ # floors at ~2e-8 and a tighter bar only fails on the data's own precision. The WRONG axis
217
+ # order measured 1.0e-2 on this same clip, so this leaves four orders of margin.
218
+ assert d < 1e-6, f"ball->stack round-trip off by {d:.3e} at frame {t}; axis order {seq} is wrong"
219
+ rate = _time_derivative(ang, ref_dt, loop) # wraps only on a periodic (loop) reference
220
+ return ang, rate
221
+
222
+
223
+ def adapt_reference(ref_q, ref_qd, model_jm, ref_dt=None, loop=True):
224
+ """Adapt a reference (retargeted for a richer parent model, e.g. coupled nq=100) onto `model_jm` (a
225
+ reduction of the SAME skeleton) BY BODY, so ONE committed clip serves every reduction with no per-model
226
+ ref file. Two per-body cases: (1) same joint width -> COLUMN-COPY (armless/fused reductions); (2) dst
227
+ body is a native Ball where src was a 3-revolute euler stack (ballified hip) -> COMPOSE the 3 src euler
228
+ columns into the Ball quaternion (FK-exact) + body-frame angular velocity via central FD of that
229
+ quaternion trajectory (a loop ref is periodic -> wrap; a whole or open clip, `loop=False`, takes one-sided
230
+ differences at its two ends, see _time_derivative). dst-owned bodies must ⊆ src-owned bodies."""
231
+ src_jm = _find_ref_source_jm(ref_q.shape[1])
232
+ assert len(src_jm["bodies"]) == len(model_jm["bodies"]), \
233
+ "reference-source and model do not share the body list (not the same skeleton)"
234
+ src, snq, snv = _owned_dof_layout(src_jm)
235
+ dst, dnq, dnv = _owned_dof_layout(model_jm)
236
+ assert ref_q.shape[1] == snq and ref_qd.shape[1] == snv, (ref_q.shape, snq, ref_qd.shape, snv)
237
+ srcmap = {i: (qa, va, wq, wv) for (i, qa, va, wq, wv) in src}
238
+ T = ref_q.shape[0]
239
+ out_q = np.zeros((T, dnq), dtype=np.float64)
240
+ out_qd = np.zeros((T, dnv), dtype=np.float64)
241
+ for (i, qa, va, wq, wv) in dst:
242
+ assert i in srcmap, f"model body {i} is a DOF but is welded/absent in the reference-source model"
243
+ sqa, sva, swq, swv = srcmap[i]
244
+ if model_jm["bodies"][i].get("joints") and src_jm["bodies"][i].get("joint") == "ball":
245
+ # the reverse of the ballified-hip case: src is a native Ball, dst an ordered scalar stack
246
+ # (myoleg26_3d_compound's hip). Decompose the quaternion onto the dst's declared axes.
247
+ prim = model_jm["bodies"][i]["joints"]
248
+ assert (wq, wv) == (len(prim), len(prim)), (i, wq, wv, len(prim))
249
+ assert ref_dt is not None, "compound-hip reference needs ref_dt for the angle-rate FD"
250
+ ang, rate = _ball_to_stack(ref_q[:, sqa:sqa + 4], [p["axis"] for p in prim], ref_dt, loop)
251
+ out_q[:, qa:qa + wq] = ang
252
+ out_qd[:, va:va + wv] = rate
253
+ elif model_jm["bodies"][i].get("joint") == "ball" and src_jm["bodies"][i].get("joint") == "revolute":
254
+ # ballified hip: compose the src 3-revolute euler columns -> Ball quaternion (+ body omega)
255
+ stack = _coincident_revolute_stack(src_jm, i)
256
+ assert len(stack) == 3 and wq == 4 and wv == 3, (i, len(stack), wq, wv)
257
+ axes = [src_jm["bodies"][b]["axis"] for b in stack]
258
+ eq = [srcmap[b][0] for b in stack]
259
+ quat = np.empty((T, 4))
260
+ for t in range(T):
261
+ q = _axis_angle_quat(axes[0], ref_q[t, eq[0]])
262
+ q = _qmul(q, _axis_angle_quat(axes[1], ref_q[t, eq[1]]))
263
+ q = _qmul(q, _axis_angle_quat(axes[2], ref_q[t, eq[2]]))
264
+ quat[t] = q
265
+ out_q[:, qa:qa + 4] = quat
266
+ assert ref_dt is not None, "ball-hip reference needs ref_dt for the angular-velocity FD"
267
+ qdot = _time_derivative(quat, ref_dt, loop)
268
+ for t in range(T):
269
+ cq = quat[t] * np.array([1.0, -1.0, -1.0, -1.0]) # conjugate (unit quat)
270
+ out_qd[t, va:va + 3] = (2.0 * _qmul(cq, qdot[t]))[1:4] # body-frame right-triv omega
271
+ elif (rr := _reread_girdle_source(model_jm, src_jm, i)) is not None:
272
+ # a shoulder-girdle master re-read as the topmost girdle joint (decisions/0027): theta = c_top * the
273
+ # source's shoulder elevation, which is the coordinate the source's rhythm follows. The reference
274
+ # carries shoulder_elv (the retarget swings the arm) and leaves the girdle joints at 0, so copying the
275
+ # master's own column would drop the elevation. Same rule as build_fullbody._reduce_keyframe.
276
+ assert (wq, wv) == (1, 1), (i, wq, wv)
277
+ (eqa, eva), coef = rr
278
+ out_q[:, qa] = ref_q[:, eqa] / coef
279
+ out_qd[:, va] = ref_qd[:, eva] / coef
280
+ else:
281
+ assert (wq, wv) == (swq, swv), (i, (wq, wv), (swq, swv))
282
+ out_q[:, qa:qa + wq] = ref_q[:, sqa:sqa + swq]
283
+ out_qd[:, va:va + wv] = ref_qd[:, sva:sva + swv]
284
+ return out_q, out_qd
285
+
286
+
287
+ def _reread_girdle_source(model_jm, src_jm, i):
288
+ """((src qadr, src vadr) of shoulder_elv, its coupling coefficient) if model body i is a girdle master that
289
+ drives a coupled `shoulder_elv*` which the reference-source model owns as its own coordinate, else None."""
290
+ B = model_jm["bodies"]
291
+ if "coupled" in B[i] or B[i].get("joint") != "revolute":
292
+ return None
293
+ deps = [j for j, b in enumerate(B) if "coupled" in b and int(b["coupled"]["master_qadr"]) == int(B[i]["qadr"])
294
+ and b.get("joint_name", "").startswith("shoulder_elv")]
295
+ if not deps:
296
+ return None
297
+ assert len(deps) == 1, (i, deps)
298
+ j = deps[0]
299
+ sb = src_jm["bodies"][j]
300
+ assert "coupled" not in sb and sb.get("joint") == "revolute", (j, sb.get("joint_name"))
301
+ c = [float(v) for v in B[j]["coupled"]["coef"]]
302
+ assert c[0] == 0.0 and all(v == 0.0 for v in c[2:]) and c[1] != 0.0, (j, c)
303
+ return (int(sb["qadr"]), int(sb["vadr"])), c[1]
304
+
305
+
306
+ @dataclasses.dataclass
307
+ class Morphology:
308
+ """Per-model kinematic facts consumed by ImitationTask. Built once from the dnmodel + a few explicit
309
+ (non-derivable) declarations. No per-model CODE lives here -- only data."""
310
+ nq: int
311
+ nv: int
312
+ nbody: int
313
+ root_fwd: int # q index of forward (world-x) translation (excluded from pose)
314
+ root_height: int # q index of vertical (world-up) translation (height ET + anti-sink)
315
+ root_lat: Optional[int] # q index of lateral translation, or None (planar model)
316
+ root_body: int # body index used as root for root-relative end-effectors
317
+ feet: List[int] # end-effector body indices (feet [+ hands for a full humanoid])
318
+ quat_blocks: List[Tuple[int, int]] # (start, len=4) quat spans in dnmodel body order (empty => planar)
319
+ body_mass: torch.Tensor # (nbody,) fp32
320
+ body_com: torch.Tensor # (nbody,3) fp32, body-frame COM offset
321
+ mass_tot: float
322
+ pose_scalar_idx: torch.Tensor # (k,) long: scalar q-dims tracked in the pose term
323
+ root_quat: Optional[Tuple[int, int]] = None # (start,4) span of the FREE-joint (root/pelvis) quat, or None
324
+ q_joint: Optional[List[str]] = None # (nq,) owning joint NAME per q index -- lets a reward config name a
325
+ # DOF ("knee_angle_r") instead of an index that rots on a model change
326
+
327
+ @staticmethod
328
+ def build(jm, *, nq, nv, root_fwd, root_height, root_lat, root_body, feet, device):
329
+ # Quaternion spans, iterated in dnmodel body order -- identical to the pre-refactor _quat_blocks so
330
+ # the pose-error quat sum keeps its float op-order. Free -> root quat at qadr+3; Ball -> qadr.
331
+ quat_blocks = []
332
+ root_quat = None
333
+ for b in jm["bodies"]:
334
+ qa = int(b["qadr"]); j = b.get("joint")
335
+ if j == "free":
336
+ quat_blocks.append((qa + 3, 4))
337
+ root_quat = (qa + 3, 4) # the pelvis/root orientation span (for the separable root term)
338
+ elif j == "ball":
339
+ quat_blocks.append((qa, 4))
340
+ body_mass = torch.tensor([float(b.get("mass", 0.0)) for b in jm["bodies"]],
341
+ dtype=torch.float32, device=device)
342
+ body_com = torch.tensor([list(b.get("com", [0.0, 0.0, 0.0])) for b in jm["bodies"]],
343
+ dtype=torch.float32, device=device) # (nbody,3)
344
+ mass_tot = float(body_mass.sum()) + 1e-9
345
+ quat_dims = {i for (s, L) in quat_blocks for i in range(s, s + L)}
346
+ excl = quat_dims | {root_fwd} | ({root_lat} if root_lat is not None else set())
347
+ pose_scalar_idx = torch.tensor([i for i in range(nq) if i not in excl],
348
+ dtype=torch.long, device=device)
349
+ # Owning joint name per q index. COUPLED bodies are skipped: their qadr ALIASES the driving joint's
350
+ # (an aliased spine dof shares the Ball hip's quat span in the armless_ball model), so including them
351
+ # would mislabel real dofs. Widths mirror the engine's q layout, not the velocity layout.
352
+ q_width = {"free": 7, "ball": 4, "revolute": 1, "slide": 1, "fixed": 0}
353
+ q_joint: List[Optional[str]] = [None] * nq
354
+ for b in jm["bodies"]:
355
+ # A COMPOUND body carries `joints: [...]` (an ordered scalar stack) and NO `joint` key, so
356
+ # `b.get("joint", "fixed")` read it as fixed, gave it width 0, and left its q slots
357
+ # unlabelled -- `unlabelled q dims: [7, 8, 9, 13, 14, 15]` on myoleg26_3d_compound, which is
358
+ # exactly the two 3-hinge hips. bug-grad-audits.md:33 lists the python plumbing for the
359
+ # compound conversion as done; this path was not in that list.
360
+ stack = b.get("joints")
361
+ if stack:
362
+ qa = b["qadr"]
363
+ name = b.get("joint_name") or b["name"]
364
+ for k, prim in enumerate(stack):
365
+ w = q_width[prim["type"] if prim["type"] != "hinge" else "revolute"]
366
+ assert w == 1, f"{name}: compound primitive {prim['type']!r} is not scalar"
367
+ assert q_joint[qa + k] is None, (
368
+ f"q[{qa + k}] claimed by both {q_joint[qa + k]!r} and {name!r} -- aliased qadr")
369
+ q_joint[qa + k] = name
370
+ continue
371
+ jt = b.get("joint", "fixed")
372
+ if jt == "fixed" or "coupled" in b:
373
+ continue
374
+ w = q_width[jt]
375
+ name = b.get("joint_name") or b["name"]
376
+ qa = int(b["qadr"])
377
+ for k in range(w):
378
+ assert q_joint[qa + k] is None, (
379
+ f"q[{qa + k}] claimed by both {q_joint[qa + k]!r} and {name!r} -- aliased qadr")
380
+ q_joint[qa + k] = name
381
+ assert all(x is not None for x in q_joint), (
382
+ "unlabelled q dims: " + str([i for i, x in enumerate(q_joint) if x is None]))
383
+ return Morphology(nq, nv, len(jm["bodies"]), root_fwd, root_height, root_lat, root_body,
384
+ list(feet), quat_blocks, body_mass, body_com, mass_tot, pose_scalar_idx,
385
+ root_quat=root_quat, q_joint=q_joint)
386
+
387
+
388
+ def clip_frame_idx(phase, start, T, cyclic):
389
+ """(i0, i1, wf) GLOBAL frame indices bracketing `phase` in each env's clip (starting at global frame `start`, T frames long),
390
+ plus the blend toward i1. A CYCLIC clip (a closed loop: frame T would be frame 0) maps phase [0, 1) onto its T intervals,
391
+ the last one blending frame T-1 into frame 0. An OPEN clip (a single step) maps phase [0, 1] onto its T-1 intervals from the
392
+ first frame to the last and holds the last one at phase 1: the cyclic map would blend a step's last frame 90-96% back into its
393
+ first at the phase the step library clamps to (0.999), i.e. ask the swing leg to return to where the step began."""
394
+ if cyclic:
395
+ f = (phase % 1.0) * T.to(phase.dtype)
396
+ k = torch.floor(f).long()
397
+ return start + (k % T), start + ((k + 1) % T), f - torch.floor(f)
398
+ assert bool((T >= 2).all()), "an open clip needs two frames to interpolate"
399
+ f = phase.clamp(0.0, 1.0) * (T - 1).to(phase.dtype)
400
+ k = torch.minimum(torch.floor(f).long(), T - 2)
401
+ return start + k, start + k + 1, f - k.to(phase.dtype)
402
+
403
+
404
+ class ImitationTask:
405
+ """Stateless DeepMimic tracking. Holds immutable config (reference clip, weights, FK monitor,
406
+ morphology) only; the env passes mutable state (q, qd, phase, ...) in and gets updated values back.
407
+ Every method mirrors the pre-refactor mixin op-for-op so the refactor is bit-parity (fwd + grad)."""
408
+
409
+ def __init__(self, morph: Morphology, ref_path: str, monitor, device, model_jm=None, cyclic=True):
410
+ # cyclic=True: every clip is a closed loop (the _loop_ references), phase [0, 1) spans T frame intervals and the last
411
+ # interval blends frame T-1 into frame 0. cyclic=False: open clips (the step library's single steps), phase [0, 1]
412
+ # spans the T-1 intervals between the first and the last frame, which is held at phase 1 (clip_frame_idx).
413
+ self.cyclic = bool(cyclic)
414
+ self.m = morph
415
+ self.monitor = monitor
416
+ self.device = device
417
+ self.m_jm = model_jm # kept for the variance floor: joint ranges are a MODEL fact, not a clip one
418
+ # SEPARABLE foot-ORIENTATION term (opt-in anti-tiptoe): track each foot body's FK world quat vs the ref
419
+ # clip's foot quat (geodesic), reusing the WTORSO machinery. The EE term is position-only + single-site
420
+ # per foot so a TIPTOE satisfies it; foot orientation is the only DIRECT anti-plantarflexion signal, and
421
+ # its gradient is clean (foot quat is smooth in ankle/shank -> bypasses the discontinuous contact force).
422
+ # The reference (heel-strike/foot-flat) IMPORTS the correct contact orientation with no hand-tuned target.
423
+ # FOOT_BODIES = comma list of body idx (fullbody calcn "137,151"). Read here so the ref foot quats cache
424
+ # in the same batched ref-FK below. Default empty => OFF => byte-identical.
425
+ self.IM_FOOT_BODIES = []
426
+ self.IM_WFOOT = 0.0
427
+ # SEPARABLE horizontal-COM term (opt-in anti-lean): track (COM_xy - root_xy) vs the ref. The COM Jacobian
428
+ # d(COM)/dq_j = (M_subtree/M)*(axis x (COM_sub - p_j)) auto-weights each joint by its mass-MOMENT (its
429
+ # mechanical leverage on whole-body balance) -- the balance signal the equal-weighted pose term dilutes.
430
+ # root-RELATIVE xy: penalizes the lean (mass ahead of base) but NOT global forward drift (locomotion).
431
+ # Read here so the ref COM_rel_xy caches in the ref-FK below. Default 0 => OFF => byte-identical.
432
+ self.IM_WCOM_XY = 0.0
433
+ # v2 (#44) is read HERE, with the other flags that decide what the one-shot reference FK caches:
434
+ # its pos group always reads the horizontal COM, and its ang group reads the torso/foot quats
435
+ # whenever those bodies are declared -- independently of the v1 weights that used to gate them.
436
+ self.IM_V2 = False
437
+ # v3 (docs/training/concepts/imitation-reward.md): jacobian-mapped joint error, ABSOLUTE exponents, split
438
+ # value/gradient. Separate switch from v2 on purpose -- v2 holds the best full-body result on record
439
+ # (fb_v9_imv2 ep3600: 5/5 x 1000 steps, 14.288 m) and stays reproducible as the baseline.
440
+ self.IM_V3 = False
441
+ # MULTI-CLIP. `ref_path` may name several clips (comma-separated, or a .txt with one path per line).
442
+ # They are CONCATENATED along the time axis rather than padded to a common length: clip lengths are
443
+ # ragged (107-187 frames across the CMU walk set) and padding would either waste memory or need a
444
+ # mask on every gather. With a concatenation plus per-clip (start, T), the frame index becomes
445
+ # `clip_start[c] + (floor(phase*T[c]) % T[c])`, which is a GLOBAL index -- so every existing
446
+ # `A[..., i0]` gather over the per-frame precomputes keeps working untouched, for one clip or a
447
+ # hundred. A single path therefore takes exactly the old path with n_clips == 1.
448
+ paths = _resolve_ref_paths(ref_path)
449
+ self.clip_mix = None # set by the env when TASKWALK_RSI_MIX_STEPS is configured
450
+ self.clip_paths = [str(p) for p in paths]
451
+ self.n_clips = len(paths)
452
+ qs, qds, starts, Ts, dts = [], [], [], [], []
453
+ grfs = []
454
+ ankles = []
455
+ loops = []
456
+ off = 0
457
+ for p in paths:
458
+ _ref = np.load(p)
459
+ # LOOP OR WHOLE CLIP, per clip, from the file itself. Every reference before the LaFAN1 line is a
460
+ # closed loop (tools/reference/make_loopable_ref.py) and carries no `loop` key, so a missing key
461
+ # means a loop and every existing file keeps its behaviour. A whole clip (`loop=False`, e.g. a
462
+ # 240 s LaFAN1 take) jumps from its last frame back to a different first pose, so it must never
463
+ # wrap: frame lookup clamps at the last frame, RSI keeps a margin before the end, and the env ends
464
+ # the episode there as a TRUNCATION (see advance_phase / clip_end, ControlVAE / MuscleVAE convention).
465
+ lp = bool(_ref["loop"]) if "loop" in _ref.files else True
466
+ # loop_start / loop_stop name a loop's window inside its SOURCE frames (make_loopable_ref.py). On a
467
+ # file that also says loop=False the two facts contradict each other; refuse rather than pick one.
468
+ assert lp or not ({"loop_start", "loop_stop"} & set(_ref.files)), (
469
+ f"{p}: loop=False but the file carries a loop_start/loop_stop window")
470
+ # A RE-FRAMED MODEL TAKES ONLY A RE-FRAMED CLIP. tools/reframe_zup.py moved the myoLeg26 family to a
471
+ # z-up root (2026-09-23) and stamped `_frame` on the model and `frame` on every converted clip. The
472
+ # clip's shape does not change, so without this an old y-up file would load and train silently:
473
+ # its height slot read as lateral, its pelvis orientation 90 deg off.
474
+ if model_jm is not None and "_frame" in model_jm:
475
+ _want = model_jm["_frame"]["convention"]
476
+ _got = str(_ref["frame"]) if "frame" in _ref.files else None
477
+ assert _got == _want, (
478
+ f"{p}: reference frame {_got!r} but the model is {_want!r}. Convert it with "
479
+ f"`tools/reframe_zup.py convert-refs {p}`")
480
+ d = float(_ref["dt"]) if "dt" in _ref.files else 1.0 / 120.0
481
+ rq, rqd = np.asarray(_ref["q"]), np.asarray(_ref["qd"])
482
+ if rq.shape[1] != morph.nq or rqd.shape[1] != morph.nv:
483
+ # A richer parent clip (e.g. the coupled nq=100 walk) adapted onto THIS reduction BY BODY --
484
+ # one committed ref serves every reduction, no per-model file (column-copy, or euler->Ball
485
+ # compose for a ballified hip). ref_dt feeds the Ball angular-velocity FD.
486
+ assert model_jm is not None, (
487
+ f"{p}: reference nq={rq.shape[1]}/nv={rqd.shape[1]} != model nq={morph.nq}/nv={morph.nv} "
488
+ f"and no model_jm passed to adapt from")
489
+ rq, rqd = adapt_reference(rq, rqd, model_jm, d, loop=lp and self.cyclic) # a whole clip and an open step clip never wrap
490
+ assert rq.shape[1] == morph.nq and rqd.shape[1] == morph.nv, (
491
+ f"{p}: reference {rq.shape}/{rqd.shape} != model nq={morph.nq}/nv={morph.nv}")
492
+ qs.append(rq); qds.append(rqd); starts.append(off); Ts.append(rq.shape[0]); dts.append(d)
493
+ loops.append(lp)
494
+ off += rq.shape[0]
495
+ assert len(set(dts)) == 1, (
496
+ "clips must share a frame rate -- phase advances at dt/clip_secs and a per-clip dt would make "
497
+ f"the same phase mean different things: {dict(zip(self.clip_paths, dts))}")
498
+ ref_dt = dts[0]
499
+ self.ref_q = torch.tensor(np.concatenate(qs, 0), dtype=torch.float32, device=device) # (sum_T, nq)
500
+ # GROUND-REACTION TRACKING (DN_IM_WGRF, default 0 = off and bit-identical): the per-foot VERTICAL ground
501
+ # reaction against the clip's measured force plates, in body weights. 2026-10-08: the kinematic imitation of a
502
+ # kinematic reference reproduced the human knee angles on this body with a flat 0.74-0.85 BW vertical force
503
+ # (the human's per-foot curve: 1.06 / 0.71 / 1.03), so the force gets its own term when the reference carries one.
504
+ # Scale: A = 1 / (2 sigma^2) with sigma = 0.071 BW, the median between-subject SD of the per-foot vertical GRF over
505
+ # stance at 1.3 m/s (Fukuchi 2018, data/reference/human/fukuchi2018_grf_moments_1p3.npz, grf_vert_bw_r_sd): a
506
+ # one-SD error on both feet gives exp(-1). The weight is a design choice, stated in the cell, not a sourced value.
507
+ self.IM_WGRF = 0.0
508
+ self.IM_AGRF = 1.0 / (2.0 * 0.071 ** 2)
509
+ # ANKLE-MOMENT TRACKING (DN_IM_WANK, default 0 = off and bit-identical): the per-foot ankle moment the ground
510
+ # reaction demands (the in-graph GRF moment about the talus origin, N.m/kg, + = plantarflexion) against the subject's
511
+ # own inverse dynamics. 2026-10-09: every imitation of the RRA walk held the centre of pressure ~2 cm ahead of the ankle
512
+ # from 10 to 30% of the stride (the subject rolls it 1 -> 70 mm) and so carried no mid-stance plantarflexor moment
513
+ # (subject 11: 0.21 / 0.41 / 0.71 N.m/kg at 10-30%); static optimisation charged the tibialis for it. Scale: A = 1 /
514
+ # (2 sigma^2), sigma = 0.215 N.m/kg, the median between-subject SD of the ankle moment over stance at 1.3 m/s (Fukuchi
515
+ # 2018, data/reference/human/fukuchi2018_moments_1p3_hka.npz, ankle_moment_rl_sd, 0-60%). The weight is a design choice.
516
+ self.IM_WANK = 0.0
517
+ self.IM_AANK = 1.0 / (2.0 * 0.215 ** 2)
518
+ self.ref_qd = torch.tensor(np.concatenate(qds, 0), dtype=torch.float32, device=device) # (sum_T, nv)
519
+ self.clip_start = torch.tensor(starts, dtype=torch.long, device=device)
520
+ self.clip_T = torch.tensor(Ts, dtype=torch.long, device=device)
521
+ self.clip_secs = self.clip_T.float() * ref_dt
522
+ self.ref_dt = ref_dt
523
+ # Per-clip loop flag, and ONE host-side bool that gates every non-loop code path. A corpus of loop
524
+ # references never enters those paths, so its lookups, RNG stream and rewards stay byte-identical to the
525
+ # loop-only code. A MIXED list (loops + whole clips) is supported: each env reads its own clip's flag.
526
+ self.clip_loop = torch.tensor(loops, dtype=torch.bool, device=device)
527
+ self.any_nonloop = not all(loops)
528
+ # Set by the env (set_control_dt) before the first reset; the non-loop RSI range and the clip-end
529
+ # truncation are in CONTROL steps, which the task cannot know on its own.
530
+ self.dt_ctrl = None
531
+ self._rsi_phase_max = None
532
+ # RSI MARGIN for a whole clip, in control steps: a start is drawn so that at least this many steps
533
+ # remain before the clip-end truncation. Default 32 = the full-body SAPO BPTT window (cfg.steps_num in
534
+ # tools/rl_algorithm_suite.py; the env cannot see the trainer's DN_STEPS_NUM). It is an efficiency
535
+ # knob, not a correctness one: an episode that does reach the end inside a window is bootstrapped there
536
+ # like a time limit, it only wastes the rest of that window's credit.
537
+ self.RSI_END_MARGIN = 32
538
+ # DN_RSI_WINDOW="T0,T1,P" (2026-11-20, KICK360-...-PUSHRSI; default UNSET = the original RSI, no extra RNG draw, bit-identical):
539
+ # a fraction P of the RSI starts is drawn uniformly from clip time [T0, T1] s instead of uniform over the clip (one clip only; the
540
+ # window start is capped by the whole-clip RSI end margin). For the 360 kick: half the starts in the plant + push, 1.95-2.40 s.
541
+ self.RSI_WINDOW = None
542
+ if os.environ.get("DN_RSI_WINDOW"):
543
+ w_ = [float(x) for x in os.environ["DN_RSI_WINDOW"].split(",")]
544
+ assert len(w_) == 3 and 0.0 <= w_[0] < w_[1] and 0.0 < w_[2] <= 1.0, w_
545
+ self.RSI_WINDOW = tuple(w_)
546
+ # Single-clip aliases. Everything that predates multi-clip reads these; with n_clips == 1 they are
547
+ # the same numbers as before, and with more they describe clip 0 and are only used where a scalar
548
+ # genuinely is wanted (the authority FD sweep's frame cap, the banner).
549
+ self.ref_T = int(Ts[0])
550
+ self.ref_secs = float(Ts[0] * ref_dt)
551
+ self.ref_T_total = int(off)
552
+ # TASK CONDITIONING (v_fwd, cadence), one row per clip, MEASURED FROM THE REFERENCE ITSELF rather
553
+ # than read from catalog.csv -- the catalog was computed on the myoleg26 retarget, and what the policy
554
+ # must reproduce is the clip as THIS model sees it.
555
+ # v_fwd NET DISPLACEMENT / duration, not the mean of the body-frame qd[3]. Measured over the v9
556
+ # corpus, the two disagree: 132_54 has qd[3] = -0.962 m/s against a net +0.996 (same
557
+ # magnitude, opposite sign -- its pelvis is yawed ~180 deg against its travel) and 35_22
558
+ # reads +5.237 against +3.571. Net displacement is heading-free by construction, is what a
559
+ # user would actually specify as a target speed, and cannot be fooled by a yawed pelvis.
560
+ # cadence steps/s. A loop reference is exactly ONE gait cycle = two steps, so 2 / clip_secs.
561
+ # NOT stride: speed = cadence * step_length holds to a median 0.0% relative error over the corpus, so
562
+ # stride is algebraically determined by these two and adds a third input carrying no new information.
563
+ # NOT v_lat either: every clip walks essentially straight, so it would be a constant ~0 input. Making
564
+ # it non-zero needs motions where the body faces one way and travels another, which cannot be
565
+ # manufactured by rotating a forward walk -- that rotates heading and travel together.
566
+ vf, cad = [], []
567
+ for c in range(self.n_clips):
568
+ s0, T = starts[c], Ts[c]
569
+ d = self.ref_q[s0 + T - 1, :2] - self.ref_q[s0, :2] # net travel in the horizontal plane
570
+ vf.append(float(d.norm()) / (T * ref_dt))
571
+ cad.append(2.0 / (T * ref_dt))
572
+ self.clip_vfwd = torch.tensor(vf, dtype=torch.float32, device=device)
573
+ self.clip_cadence = torch.tensor(cad, dtype=torch.float32, device=device)
574
+ # Normalised for the network: zero-mean/unit-scale over the corpus it will actually see. Constants
575
+ # are recorded so an eval can ask for a speed in m/s and get the same encoding.
576
+ self.cond_mean = torch.stack([self.clip_vfwd.mean(), self.clip_cadence.mean()])
577
+ self.cond_std = torch.stack([self.clip_vfwd.std(unbiased=False).clamp_min(1e-3),
578
+ self.clip_cadence.std(unbiased=False).clamp_min(1e-3)])
579
+ self.COND_OBS = False
580
+ self._clip_only = None
581
+ # DN_CLIP_DRAW: how rsi() picks the clip. "clip" (the default) gives every clip the same probability,
582
+ # so a 3 s clip gets as many starts as a 60 s one. "frame" draws clip c in proportion to the frames a start
583
+ # can land on (_rsi_start_frames), which, with the phase uniform inside the clip, makes every start-able
584
+ # frame of the corpus equally likely. That is the start rule of MuscleVAE and ControlVAE
585
+ # (index_counter.random_select over the concatenated dataset's feasible frames). Their default also
586
+ # reweights it by "balance" (p ~ 1 / the frame's running return), which is NOT ported here.
587
+ self.CLIP_DRAW = "clip"
588
+ # Which clip each env is tracking. Assigned in rsi(); until then everything is clip 0, which keeps
589
+ # a bare ref_at(phase) call (tests, tools) working exactly as it did.
590
+ self.clip_id = torch.zeros(1, dtype=torch.long, device=device)
591
+ if self.n_clips > 1:
592
+ print(f"[imitation] multi-clip: {self.n_clips} clips, {off} frames total "
593
+ f"({min(Ts)}-{max(Ts)} per clip, dt={ref_dt:.5g})", flush=True)
594
+ # Precompute the reference FK-derived reward targets per clip frame ONCE (the ref clip is fixed).
595
+ # The hot reward path otherwise ran a SECOND per-control-step 156-body monitor FK on q_ref
596
+ # (body_poses is a Python per-body loop) -- measured ~30% of full-body imitation training cost. Here
597
+ # body_poses is batched over the frame axis, so all T frames are done in ONE call at init; the reward
598
+ # then just gathers+lerps these constants by phase (no grad needed -- the ref is a target). This
599
+ # interpolates world poses (vs interp-q-then-FK) -- a negligible, principled change for a soft target.
600
+ # DN_IM_RECON=mvae: MuscleVAE's reconstruction objective is the whole reward (mvae_recon.py, `_recon_reward`);
601
+ # unset, every path below is unchanged.
602
+ self.IM_RECON = ""
603
+ assert self.IM_RECON in ("", "mvae"), f"DN_IM_RECON is '' or 'mvae', got {self.IM_RECON!r}"
604
+ with torch.no_grad():
605
+ from diffneusim.model.monitor import _quat_rotate
606
+ pos_r, quat_r = self.monitor.body_poses(self.ref_q.t().contiguous()) # lists of (3,T)/(4,T)
607
+ root_r = pos_r[morph.root_body] # (3,T)
608
+ self._ref_root = root_r.contiguous()
609
+ self._ref_ee = [(pos_r[b] - root_r).contiguous() for b in morph.feet] # per foot, root-relative (3,T)
610
+ com_r = sum(morph.body_mass[b] * (pos_r[b] + _quat_rotate(
611
+ quat_r[b], morph.body_com[b][:, None].expand(3, self.ref_T_total)))
612
+ for b in range(morph.nbody)) / morph.mass_tot # (3,T)
613
+ self._ref_com_z = com_r[2].contiguous() # (T,)
614
+ # rel-site tracking targets (opt-in): mass-bearing bodies' ROOT-RELATIVE positions across ref
615
+ # frames, from replaying the ref through OUR model's FK (self-consistent target, not mocap sites).
616
+ # Cartesian POSITION only -> forgiving of axial rotations the muscle model may not hit (forearm
617
+ # pronation etc.), so a hard rotation does not false-trigger the ET. Precomputed in-memory at init
618
+ # (NOT a file), like _ref_ee; the reward reuses its OWN body_poses(q) for the current sites so
619
+ # there is no extra per-step FK.
620
+ self.sites = [b for b in range(morph.nbody) if float(morph.body_mass[b]) > 1e-6]
621
+ if self.IM_RECON: # MuscleVAE's bodies on ours: COM positions (B,3,T) and body quaternions (B,4,T) per frame
622
+ self._rc_idx, self._rc_com = _R.body_layout(self.monitor.jm, device)
623
+ P, Q = _R.com_poses(pos_r, quat_r, self._rc_idx, self._rc_com)
624
+ self._ref_rc_P, self._ref_rc_Q = P.contiguous(), Q.contiguous()
625
+ self._rc_sum, self._rc_n = None, 0
626
+ self.PHASE_OBS = False
627
+ # DeepMimic (Peng 2018) reward weights + exp scales (env-tunable; justify changes in METHODS.md)
628
+ self.IM_WP = 0.65 # pose
629
+ self.IM_WV = 0.1 # velocity
630
+ self.IM_WE = 0.15 # end-effector (feet)
631
+ self.IM_WC = 0.1 # com
632
+ self.IM_AP = 2.0
633
+ self.IM_AV = 0.1
634
+ self.IM_AE = 40.0
635
+ self.IM_AC = 10.0
636
+ self.IM_ACT_PEN = -0.001
637
+ # Anneal the effort price in over this many env steps (0 => full strength from step 0). Effort
638
+ # pressure works AGAINST the raised operating point (DN_OUT_BIAS=-0.6 idles every muscle at
639
+ # 0.231, so mean(a^2) has a 0.053 floor the policy can only shed by driving activations back toward
640
+ # ~0.05 -- the regime where the pathwise gradient was measured to be exactly zero). Ramping lets the
641
+ # gait form first and only then charges for it.
642
+ self.IM_ACT_PEN_ANNEAL_STEPS = 0
643
+ # SEPARABLE root/pelvis-orientation term (opt-in, default 0.0 => OFF => byte-identical). The root quat
644
+ # is otherwise ONE (1-|dot|) term diluted among ~100 scalar-joint terms inside the single pose exp, so
645
+ # its gradient is both diluted AND killed by the pose exp's saturation when the joints are off-ref (a
646
+ # 30 deg pelvis tilt adds only ~0.03 to e_pose). Since the pelvis is the global BALANCE frame (not just
647
+ # another limb DoF) and everything is tracked root-RELATIVE (so a root tilt is invisible to the EE/site
648
+ # terms), it deserves its OWN exp term: r += IM_WROOT*exp(-IM_AROOT*(1-|dot(root_quat)|)). When ON, the
649
+ # root quat is ALSO dropped from the lumped pose_error (no double-count). DeepMimic-faithful (Peng 2018
650
+ # separates root); NOT an anti-symptom penalty -- it restores tracking of a signal the ref genuinely
651
+ # carries (the ref pelvis is a clean near-upright walk, ~8.6 deg mean tilt).
652
+ self.IM_WROOT = 0.0 # root-orientation reward weight
653
+ self.IM_AROOT = 2.0 # exp scale on theta^2 (rad^2); 2 = DeepMimic
654
+ # SEPARABLE torso-orientation reward (own exp; needs DN_IM_TORSO_BODY>=0). Tracks the trunk body's
655
+ # world quaternion vs the ref via geodesic angle theta^2 -- the trunk carries the flex/bend + the newly
656
+ # retargeted axial TWIST (lumbar q9), which is otherwise only diluted scalar joints in the pose term.
657
+ # Default IM_WTORSO=0 => byte-identical.
658
+ self.IM_WTORSO = 0.0 # torso-orientation reward weight
659
+ # DECOUPLE the pose term (opt-in, default 0 => byte-identical). The lumped exp-of-sum
660
+ # WP*exp(-AP*Sum_j err_j) has dr/derr_i = -AP*r, so ONE large joint error drives r->0 and zeroes
661
+ # EVERY joint's pathwise gradient (coupling). Replace it with the per-joint sum-of-exp
662
+ # WP*mean_j exp(-A_DEC*err_j): each joint's gradient depends only on its own error. Per-joint err_j
663
+ # is small (single joint), so it needs a LARGER alpha than the aggregate -> IM_AP_DECOUPLE (default
664
+ # 10, tune by ep1 reward scale). Affects the exp VALUE path only (IM_TRACK=exp); the huber/mse
665
+ # straight-through still uses the lumped e_pose gradient.
666
+ self.IM_POSE_DECOUPLE = False
667
+ self.IM_AP_DECOUPLE = 10.0
668
+ # Split tracking-gradient (DiffMimic/DiffMJX-grounded): the pathwise ACTOR gradient can use a
669
+ # non-saturating MSE/Huber tracking signal while the critic/GAE/return accounting keep the bounded
670
+ # EXP reward VALUE (realized by a straight-through swap in reward()). "exp" (default) is byte-identical
671
+ # to the pure DeepMimic reward (bit-parity / FD gate); "huber"/"mse" ONLY change the actor backward
672
+ # signal. Reuses the a_k/w_k knobs; huber caps the far-from-ref gradient at the delta, mse leaves it
673
+ # linear (unbounded, relies on the trainer grad-norm clip). See imitation-appropriate-algorithm memo.
674
+ self.IM_TRACK = "exp"
675
+ self.IM_UPRIGHT_W = 0.0
676
+ self.IM_SINK_W = 0.0
677
+ # LATERAL-drift term (opt-in, default 0 => bit-parity). The pose term EXCLUDES the lateral root DOF
678
+ # (Morphology.build: excl = quat_dims | {root_fwd} | {root_lat}) and the COM_xy term tracks COM
679
+ # RELATIVE TO ROOT, so a root veering sideways in the world is invisible to the whole reward. Measured
680
+ # on the armless_ball ep720 policy: it veers 1.0-2.0 m sideways (always the same sign) against 2.4-3.7 m
681
+ # of forward travel and falls over laterally (roll 45-55 deg) -- while the ref clip is straight to
682
+ # within |y| <= 0.034 m. Unlike absolute HEIGHT (morphology-sensitive => DN_IM_NO_HEIGHT), absolute
683
+ # LATERAL position is morphology-FREE: a straight walk is straight at any leg length. Straight-through
684
+ # like the CART term: bounded exp for the critic, non-saturating MSE gradient for the actor -- a plain
685
+ # exp(-A*e) is already flat by ~0.5 m, i.e. no gradient exactly where the drift needs correcting.
686
+ # (Why not DN_IM_CART_W, which also sees y: its ABSOLUTE world target includes the ref's x, and a
687
+ # _loop_ ref resets x to 0 every 1.52 m/1.075 s while the policy's x keeps growing -- the x error then
688
+ # exceeds the lateral one and grows with episode length, i.e. it penalizes walking longer.)
689
+ self.IM_WLAT = 0.0
690
+ self.IM_TASK_W = 0.0
691
+ self.IM_ET_H = 0.35 # early-term: |root height - ref|
692
+ self.IM_ET_POSE = 0.25 # early-term: tracked-pose dev
693
+ # rel-site (Cartesian, root-relative, MEAN-over-sites) tracking -- opt-in, MIXED with the q-pose terms
694
+ # (added, not replacing). MuscleMimic-grounded: matches marker/site positions (task-relevant, smoother
695
+ # than joint angles). IM_WSITE=0 (default) => off / bit-parity. When IM_ET_SITE>0 the desync ET uses
696
+ # rel-site deviation INSTEAD of q-pose, so a hard-to-imitate axial rotation (position ~unchanged) no
697
+ # longer false-terminates training.
698
+ self.IM_WSITE = 0.0 # rel-site reward weight (mix)
699
+ self.IM_ET_SITE = 0.0 # rel-site desync threshold (0=use q-pose)
700
+ # End-effector desync ET (opt-in, 0=off): terminate on the MAX over end-effectors (morph.feet =
701
+ # feet [+ hands]) of the root-relative Cartesian squared error. MAX (not mean) so a single desynced
702
+ # EE -- e.g. a swing foot when the policy stands still while the ref walks -- terminates, which the
703
+ # mean-over-all-bodies rel-site ET averages away (freeload). This is the DeepMimic end-effector
704
+ # criterion; unlike MuscleMimic (loco_mujoco) which uses root fall/topple ET + reward-only tracking,
705
+ # this ADDS a per-EE tracking gate to catch standing directly. Reuses reward()'s _ref_ee (no extra FK).
706
+ self.IM_ET_EE = 0.0 # max-over-EE desync threshold (0=off)
707
+ # TRUNK-ORIENTATION ET + non-saturating trunk gradient (both opt-in, default 0 => bit-parity).
708
+ # The trunk is otherwise UNCONSTRAINED: the EE term compares feet in ROOT-RELATIVE WORLD axes (not
709
+ # rotated into the root frame, so it is blind to trunk/pelvis rotation), the pose term EXCLUDES all
710
+ # quaternion dims, and with IM_ET_EE set desync_mask returns on the EE branch so pose_desync never
711
+ # even runs. The only trunk signal is IM_WTORSO's exp(-a*theta^2), which is FLAT once theta is large
712
+ # -- i.e. no gradient exactly where the trunk needs pulling back. Measured on the sustained-walk
713
+ # policy (sapo_fb_svd20 ep2000, 10 s / 15.2 m): torso pitch swung -14..+85 deg (99 deg p2p, mean
714
+ # +40) at 0.80 Hz, decoupled from the 1.40 Hz gait = a passive counterweight, while the REFERENCE
715
+ # torso stays within 9.7 deg p2p (mean -6.8). The env fall gate cannot see it either: its
716
+ # _upright() reads the ROOT quaternion (despite the "torso" comment) and needs >60 deg of PELVIS
717
+ # tilt, and its margin never dropped below 0.756 (fires at 0.5) during that 99 deg trunk swing.
718
+ self.IM_ET_TORSO = 0.0 # rad of geodesic trunk-vs-ref deviation; 0 = off
719
+ self.IM_TORSO_ST = False # straight-through trunk gradient (bounded exp value, linear grad)
720
+ # P1 (DiffMimic-grounded): ABSOLUTE (root-inclusive) per-body Cartesian tracking with a NON-SATURATING
721
+ # gradient. The known failure = exp(-a*e) has ~0 gradient far from ref (the flat 0.42 plateau); a
722
+ # Cartesian MSE gradient stays proportional to the position error and back-props through FK to the
723
+ # muscles (coupled chain; sink shows as vertical error). Straight-through keeps the critic/return on a
724
+ # bounded EXP value while the actor gets the MSE gradient (skeptic: don't feed unbounded MSE to the TD
725
+ # critic). IM_CART_W=0 (default) => off / bit-parity. This is the highest-EV escape lever.
726
+ self.IM_CART_W = 0.0 # abs-Cartesian reward weight
727
+ # Dimension-anchored desync ET (opt-in, default OFF => raw-sum threshold / bit-parity). pose_error is
728
+ # a RAW SUM over pose terms, so its scale grows with model DoF: IM_ET_POSE=0.25 (tuned on myoLeg26's
729
+ # ~10 terms) is ~(n_fullbody/n_myoleg ~15x) too TIGHT on the ~109-term full body -> every full-body
730
+ # imitation episode desync-died at ~5 steps (fullbody-imitation-sink-lurch-localmin). When ON, the
731
+ # desync COMPARISON divides pose_error by the pose-term count so IM_ET_POSE is a PER-DIM threshold
732
+ # (transferable across models). The REWARD's e_pose is untouched (raw), so myoLeg26 reward stays
733
+ # bit-identical either way; only the ET gate changes.
734
+ self.IM_ET_NORM = False
735
+ self._n_pose_terms = int(self.m.pose_scalar_idx.numel()) + len(self.m.quat_blocks)
736
+ assert self._n_pose_terms > 0, self._n_pose_terms
737
+ # RUNNING fix (opt-in, default OFF => RSI unchanged / bit-parity): restrict reference-state-init to
738
+ # STANCE phases so envs don't start mid-FLIGHT (aerial), which topple-lunges on a run clip. Stance
739
+ # ~ the lower half of the reference root-height cycle (root is low at contact, high at flight) -- a
740
+ # no-FK proxy for foot-ground contact. Threshold tunable via DN_RSI_STANCE_Q (quantile).
741
+ self.RSI_STANCE = False
742
+ # It draws from stance frames over the WHOLE clip, which on a whole clip includes the end margin that
743
+ # the non-loop RSI range keeps clear. Not ported: refuse rather than start envs at the clip's end.
744
+ assert not (self.RSI_STANCE and self.any_nonloop), (
745
+ "DN_RSI_STANCE samples frames without the whole-clip end margin (DN_RSI_END_MARGIN)")
746
+ if self.RSI_STANCE:
747
+ h = self.ref_q[:, morph.root_height]
748
+ q = 0.5
749
+ self._stance_frames = torch.nonzero(h < torch.quantile(h, q), as_tuple=False).squeeze(-1)
750
+ if self._stance_frames.numel() < 2:
751
+ self._stance_frames = torch.arange(self.ref_T_total, device=device)
752
+ # ET-tolerance curriculum (opt-in, default OFF => fixed thresholds / bit-parity): shrink-then-grow
753
+ # the imitation "tube". Start the desync-ET thresholds TIGHT (any deviation terminates -> the return
754
+ # depends sharply on ref-proximity, injecting a low-variance signal that even score-function PPO can
755
+ # follow) and anneal to the normal IM_ET_* over the first ET_ANNEAL_STEPS env.step() calls. Start not
756
+ # too tight (RSI begins on-ref, but the policy still needs a few surviving steps to learn to correct).
757
+ self.ET_ANNEAL = False
758
+ self.ET_ANNEAL_STEPS = 1500.0
759
+ # EE-tube curriculum: the EE (end-effector) desync ET BYPASSES pose_desync (see desync_mask), so the
760
+ # pose/height anneal above never reaches it. ET_EE_START_FRAC scales the per-EE threshold from
761
+ # START_FRAC*thr (tight) up to the full thr over ET_ANNEAL_STEPS -- start tight (force close
762
+ # ref-tracking so the gait is learned on-ref), release late (episodes then run LONG past the point a
763
+ # fixed ET would clip -> the policy practises SUSTAINED balance, the regime that decides eval
764
+ # survival; a real fall is still caught by the model fall gate + height ET). 1.0 (default) = no EE anneal.
765
+ self.ET_EE_START_FRAC = 1.0
766
+ # --- MuscleMimic's tracking MDP (docs/training/campaigns/fullbody/e0-musclemimic-task.md) -----------
767
+ # DN_IM_MIMIC=1: MuscleMimic's MimicReward on its 17 mimic sites (own return path, no effort term, as its
768
+ # full-body config), its deviation terminations, and its concise lookahead goal as an extra observation.
769
+ # Default off: nothing below runs and every other reward is unchanged.
770
+ self.IM_MIMIC = bool(int(os.environ.get("DN_IM_MIMIC", "0")))
771
+ # FUSED MimicReward (opt-in, DN_MIMIC_COMPILE=1): _mimic_core (the twists, the site quantities, every error
772
+ # and the exp sum) traced once per call signature by torch.compile, on the calls whose output enters the
773
+ # backward, as DnModelMonitor does for the FK and the twists. Eager it is ~1,000 backward and ~900 forward
774
+ # launches per control step, and the step is launch-bound there. Same maths reassociated: equal to roundoff.
775
+ _mc = os.environ.get("DN_MIMIC_COMPILE", "0")
776
+ assert _mc in ("0", "1"), f"DN_MIMIC_COMPILE={_mc!r} must be exactly '0' or '1'"
777
+ self._mm_compile = _mc == "1"
778
+ assert not (self._mm_compile and not self.IM_MIMIC), "DN_MIMIC_COMPILE=1 compiles DN_IM_MIMIC's reward"
779
+ self._mm_compiled = {} # (n_env, dtype, device) -> compiled _mimic_core
780
+ if self.IM_MIMIC:
781
+ self._mimic_build()
782
+ # --- reward-FK plan (throughput; see DnModelMonitor.body_poses_subset) -------------------------
783
+ # reward() only ever reads a HANDFUL of body poses (root, end-effectors, torso, optional sites)
784
+ # plus the whole-body COM. The full 156-body Python FK + the per-body COM sum cost ~29k aten
785
+ # dispatches per control step and dominated training wall-clock; declare exactly what this
786
+ # config needs so the monitor evaluates only the moving frames on those paths. Must be computed
787
+ # AFTER every IM_* weight above (they decide what is read).
788
+ _need = {int(self.m.root_body), *(int(b) for b in self.m.feet)}
789
+ if self.IM_RECON:
790
+ # The recon reward is the WHOLE reward: every other term and every ET input it would not compute is refused, not
791
+ # silently dropped. The EE ET stays (it is computed here from the same FK); the collection protocol replaces it.
792
+ off = {"DN_IM_V2": self.IM_V2, "DN_IM_V3": self.IM_V3, "DN_IM_WGRF": self.IM_WGRF,
793
+ "DN_IM_WANK": self.IM_WANK, "DN_IM_WROOT": self.IM_WROOT, "DN_IM_WTORSO": self.IM_WTORSO,
794
+ "DN_IM_WFOOT": self.IM_WFOOT, "DN_IM_WCOM_XY": self.IM_WCOM_XY, "DN_IM_WSITE": self.IM_WSITE,
795
+ "DN_IM_CART_W": self.IM_CART_W, "DN_IM_UPRIGHT_W": self.IM_UPRIGHT_W, "DN_IM_WLAT": self.IM_WLAT,
796
+ "DN_IM_SINK_W": self.IM_SINK_W, "DN_IM_TASK_W": self.IM_TASK_W, "DN_IM_ET_TORSO": self.IM_ET_TORSO,
797
+ "DN_IM_ET_SITE": self.IM_ET_SITE, "DN_IM_TRACK!=exp": self.IM_TRACK != "exp",
798
+ "DN_IM_POSE_W": False}
799
+ on = [k for k, v in off.items() if v]
800
+ assert not on, f"DN_IM_RECON=mvae replaces the tracking reward; unset {on}"
801
+ _need.update(self._rc_idx)
802
+ if self.IM_MIMIC:
803
+ _need.update(self._mm_body)
804
+ _need.add(self._mm_root_body)
805
+ self._fk_bodies = sorted(_need)
806
+ # COM is read by the height term (only when it is actually weighted) and by the horizontal-COM term
807
+ self._fk_need_com = True # v2/v3 pos group tracks the horizontal COM
808
+ # --- per-joint pose weights (opt-in) ----------------------------------------------------------
809
+ # The pose term weights every tracked dof EQUALLY, so a full-body model spends most of its pose
810
+ # budget on dofs that do not decide the gait: armless_ball tracks 14 terms of which only 4 are
811
+ # knee/ankle, i.e. the joints that produce push-off and ground clearance. `knee:2,ankle:2` doubles
812
+ # their share (4/14 -> 8/18 of the pose reward). Matched by JOINT NAME so it survives a model change.
813
+ # Applies to the REWARD only -- the desync ET and the DiffMimic snap drift keep calling pose_error()
814
+ # unweighted, so their thresholds keep their meaning. Unset => the original code path (bit-parity).
815
+ # Must come after IM_WROOT/IM_POSE_DECOUPLE: they decide the reward's term order.
816
+ self._pose_w = None
817
+ # --- per-dim exponents for the two RAW-SUM tracking terms (opt-in, 0 => byte-identical) ----------
818
+ # `exp(-alpha * sum_i e_i)` scales its exponent with the DOF COUNT, so one alpha means different
819
+ # things on different models and the term can saturate to a flat zero as the model grows. Measured
820
+ # on real rollouts: the velocity term delivers 1.1% of the reward on myoLeg26 (nv=18, e_vel 45) but
821
+ # **0.01%** on armless_ball (nv=23, e_vel 239) -- exp(-0.1*239) = 4e-11, so halving the velocity
822
+ # error buys +1.6e-6 of reward. That is not a weak term, it is an absent one: no value, no gradient.
823
+ # Dividing by the term count revives it and makes alpha mean the same thing on every model, so a
824
+ # value validated on myoLeg26 transfers. Same treatment `IM_ET_NORM` already gives the ET threshold
825
+ # ("dimension-anchored, model-transferable") -- this is that, applied to the reward.
826
+ # NOTE this adds no expressive power: exp(-a*S/n) == exp(-(a/n)*S). It buys transferability and a
827
+ # READABLE alpha (a per-dof tolerance), and an unreadable alpha is one nobody recomputes on a model
828
+ # change -- which is precisely how the reward gets silently re-tuned underneath a run.
829
+ # Must come after IM_POSE_DECOUPLE / IM_WROOT: both decide what this may normalize.
830
+ self.IM_AP_NORM = False
831
+ self.IM_AV_NORM = False
832
+ # Count of terms pose_error ACTUALLY sums. NOT _n_pose_terms: that one counts the root quat, which
833
+ # pose_error skips whenever IM_WROOT gives the root its own term -- so with IM_WROOT>0 the ET's
834
+ # existing per-dim division is off by one term. Left alone (changing it would move every ET threshold
835
+ # on runs that use IM_ET_NORM); this knob uses the count that matches its own sum.
836
+ self._n_pose_terms_reward = (int(self.m.pose_scalar_idx.numel()) + len(self.m.quat_blocks)
837
+ - 0)
838
+ assert self._n_pose_terms_reward > 0, self._n_pose_terms_reward
839
+ self.IM_VARNORM_FLOOR = 0.05
840
+ self._pose_scale = None
841
+ # --- v2: dimension-grouped, authority-weighted, online-adaptive reward (#44) --------------------
842
+ # Replaces the 7 hand-tuned exp terms with 4 dimension groups whose scales adapt during training.
843
+ # Opt-in; 0 keeps every path above byte-identical. See imitation_reward_v2.py for the rationale.
844
+ self._v2 = None # IM_V2/IM_V3 were read before the reference FK precompute
845
+ self._v3 = None
846
+
847
+ # ---------------------------------------------------------------- v2 (#44)
848
+ def _v2_build(self):
849
+ """Lay out the 4 dimension groups, measure the static authority `c`, and open the adaptive state.
850
+
851
+ Runs once. The authority FD sweep is the only expensive part (one batched FK over
852
+ nq*2*n_frames columns) and it is what makes `c` a MEASUREMENT rather than another hand-set weight.
853
+ """
854
+ m = self.m
855
+ jm = self.m_jm or getattr(self.monitor, "jm", None)
856
+ assert jm is not None, (
857
+ "DN_IM_V2 needs a dnmodel to measure joint authority; the task got neither model_jm nor a "
858
+ "monitor carrying .jm")
859
+ layout, _nq_owned, _nv_owned = _owned_dof_layout(jm)
860
+ lam = 1.0
861
+ A = _fd_authority(self.monitor, m, self.ref_q, layout,
862
+ lam=lam, n_frames=8)
863
+ amax = max(A.values()) if A else 1.0
864
+ # Floor at a small fraction of the strongest joint: a dof with ~zero measured authority still has to
865
+ # be tracked (it just must not set the agenda), and c=0 would drop it from the group entirely.
866
+ afloor = 0.01 * amax
867
+
868
+ def auth(qi_or_vi, by_q=True):
869
+ for (bi, qadr, vadr, wq, wv) in layout:
870
+ lo, w = (qadr, wq) if by_q else (vadr, wv)
871
+ if lo <= qi_or_vi < lo + w:
872
+ return max(A.get(bi, 0.0), afloor)
873
+ return afloor
874
+
875
+ names = {g: [] for g in GROUPS}
876
+ cs = {g: [] for g in GROUPS}
877
+ # ANG: scalar joint angles (height moved to pos), then the quat blocks, then the FK orientations.
878
+ self._v2_ang_scalars = torch.tensor(
879
+ [int(i) for i in m.pose_scalar_idx.tolist() if int(i) != m.root_height],
880
+ dtype=torch.long, device=self.device)
881
+ for i in self._v2_ang_scalars.tolist():
882
+ names["ang"].append(m.q_joint[i]); cs["ang"].append(auth(i))
883
+ self._v2_quat_blocks = list(m.quat_blocks)
884
+ for (s, _L) in self._v2_quat_blocks:
885
+ names["ang"].append(f"{m.q_joint[s]}:quat"); cs["ang"].append(auth(s))
886
+ self._v2_feet_q = list(self.IM_FOOT_BODIES)
887
+ for b in self._v2_feet_q:
888
+ names["ang"].append(f"fk:foot{b}_quat"); cs["ang"].append(1.0)
889
+ # POS: end-effectors, horizontal COM, height -- all FK outputs, all c = 1.
890
+ for b in m.feet:
891
+ names["pos"].append(f"fk:ee{b}"); cs["pos"].append(1.0)
892
+ names["pos"].append("fk:com_xy"); cs["pos"].append(1.0)
893
+ names["pos"].append("root_height"); cs["pos"].append(1.0)
894
+ # ANGVEL / LINVEL: split by what the dof actually is. A free joint is [omega(3), v(3)] (the layout
895
+ # free_q_to_qd writes and the engine consumes); ball/revolute are angular; slide is linear.
896
+ ang_v, lin_v = [], []
897
+ for (bi, _qadr, vadr, _wq, wv) in layout:
898
+ jt = jm["bodies"][bi].get("joint")
899
+ if jt in ("free", "freejoint"):
900
+ ang_v += list(range(vadr, vadr + 3)); lin_v += list(range(vadr + 3, vadr + 6))
901
+ elif jt == "slide":
902
+ lin_v += list(range(vadr, vadr + wv))
903
+ else:
904
+ ang_v += list(range(vadr, vadr + wv))
905
+ self._v2_angvel_idx = torch.tensor(ang_v, dtype=torch.long, device=self.device)
906
+ self._v2_linvel_idx = torch.tensor(lin_v, dtype=torch.long, device=self.device)
907
+ for vi in ang_v:
908
+ names["angvel"].append(f"qd{vi}"); cs["angvel"].append(auth(vi, by_q=False))
909
+ for vi in lin_v:
910
+ names["linvel"].append(f"qd{vi}"); cs["linvel"].append(auth(vi, by_q=False))
911
+ self._v2 = GroupedAdaptiveReward(comp_names=names, comp_c=cs, device=self.device)
912
+ self._v2_last_E = None
913
+ print(f"[imitation] IM_V2 on: " + ", ".join(
914
+ f"{g}={len(names[g])}" for g in GROUPS if names[g])
915
+ + f" | W={ {g: round(v, 3) for g, v in self._v2.W.items()} }"
916
+ + f" | authority span {min(A.values()):.4g}..{max(A.values()):.4g} m/rad"
917
+ + f" | s_spread<={self._v2.S_SPREAD:g} s_beta={self._v2.S_BETA:g} a_beta={self._v2.A_BETA:g}"
918
+ + ' | ET=v1', flush=True)
919
+
920
+ # ---------------------------------------------------------------- v3
921
+ def _v3_build(self):
922
+ """Lay out v3's groups and their per-component multipliers. See imitation_reward_v3 for the design.
923
+
924
+ The multiplier is `A_j^2` for a joint (converting rad^2 of joint error into m^2 of contact-point
925
+ displacement) and 1.0 for an FK output already in the group's unit. That single number replaces v2's
926
+ `c_j` and `1/s_j`, which multiplied the same error on one axis.
927
+ """
928
+ m = self.m
929
+ jm = self.m_jm or getattr(self.monitor, "jm", None)
930
+ assert jm is not None, (
931
+ "DN_IM_V3 needs a dnmodel to measure joint authority; the task got neither model_jm nor a "
932
+ "monitor carrying .jm")
933
+ layout, _nq, _nv = _owned_dof_layout(jm)
934
+ lam = 1.0
935
+ # every reference frame by default: measured cost 0.07 s vs 0.02 s for 8 frames, and it removes the
936
+ # sampling question permanently. n_frames is clamped by min(n_frames, T) inside _fd_authority.
937
+ nf = 100000
938
+ A = _fd_authority(self.monitor, m, self.ref_q, layout, lam=lam, n_frames=nf)
939
+ names = {g: [] for g in GROUPS3}
940
+ ws = {g: [] for g in GROUPS3}
941
+ # --- JOINT (m^2): jacobian-mapped joint position error --------------------------------------
942
+ self._v3_pos_scalars = torch.tensor(
943
+ [int(i) for i in m.pose_scalar_idx.tolist() if int(i) != m.root_height],
944
+ dtype=torch.long, device=self.device)
945
+ sq = build_component_weights(A, layout, jm, q_index_of=self._v3_pos_scalars.tolist())
946
+ for i, w in zip(self._v3_pos_scalars.tolist(), sq):
947
+ names["joint"].append(m.q_joint[i]); ws["joint"].append(w)
948
+ # The root quat is a DOF, so it is jacobian-mapped into `joint` -- it must NOT also appear as an
949
+ # FK orientation in `ang`, or the same error is priced twice with two different weights. (v2 had the
950
+ # mirror of this guard: it skipped the root quat from the pose terms when IM_WROOT rewarded it
951
+ # separately. That guard was not carried over and the double count was live until it was audited.)
952
+ self._v3_quat_blocks = list(m.quat_blocks)
953
+ # qadr of the FREE joint's quaternion -- the only absolute-world orientation among the blocks
954
+ _free = [bi for (bi, qa, _v, _wq, _wv) in layout
955
+ if jm["bodies"][bi].get("joint") in ("free", "freejoint")]
956
+ assert len(_free) == 1, ("expected exactly one free joint", _free)
957
+ self._v3_root_quat_adr = next(qa + 3 for (bi, qa, _v, _wq, _wv) in layout if bi == _free[0])
958
+ assert any(s == self._v3_root_quat_adr for (s, _L) in self._v3_quat_blocks), (
959
+ "the free joint's quat is not among quat_blocks", self._v3_root_quat_adr,
960
+ self._v3_quat_blocks)
961
+ qw = build_component_weights(A, layout, jm, q_index_of=[s for (s, _L) in self._v3_quat_blocks])
962
+ for (s, _L), w in zip(self._v3_quat_blocks, qw):
963
+ names["joint"].append(f"{m.q_joint[s]}:quat"); ws["joint"].append(w)
964
+ # --- TASK (m^2): the same displacement MEASURED, not proxied through the diagonal form -------
965
+ for b in m.feet: # FK end-effectors: already m^2
966
+ names["task"].append(f"fk:ee{b}"); ws["task"].append(1.0)
967
+ names["task"].append("fk:com_xy"); ws["task"].append(1.0)
968
+ names["task"].append("root_height"); ws["task"].append(1.0)
969
+ self._v3_feet_q = list(self.IM_FOOT_BODIES)
970
+ for b in self._v3_feet_q:
971
+ names["ang"].append(f"fk:foot{b}_quat"); ws["ang"].append(1.0)
972
+ # (no fk:root_quat here -- see the note above _v3_quat_blocks; posture is carried by the torso and
973
+ # foot orientations, and the root's own orientation is already in `pos` as a mapped dof)
974
+ # --- velocities. Same joint/task split one derivative up: joint rates mapped by A^2 land in
975
+ # `jointvel` (the DIAGONAL form of the EE velocity error), the root's own linear rate and the
976
+ # measured EE velocities land in `taskvel` (the same quantity WITHOUT that approximation), and the
977
+ # root's angular rate keeps its own group because it is the only (rad/s)^2 quantity.
978
+ ang_v, jnt_v, root_lin_v = [], [], []
979
+ for (bi, _qadr, vadr, _wq, wv) in layout:
980
+ jt = jm["bodies"][bi].get("joint")
981
+ if jt in ("free", "freejoint"):
982
+ ang_v += list(range(vadr, vadr + 3))
983
+ root_lin_v += list(range(vadr + 3, vadr + 6)) # [w_body; v_body], see core/dyn/articulated.h
984
+ else:
985
+ jnt_v += list(range(vadr, vadr + wv)) # a joint RATE maps through A -> a linear speed
986
+ self._v3_jointvel_idx = torch.tensor(jnt_v, dtype=torch.long, device=self.device)
987
+ self._v3_rootlin_idx = torch.tensor(root_lin_v, dtype=torch.long, device=self.device)
988
+ self._v3_angvel_idx = torch.tensor(ang_v, dtype=torch.long, device=self.device)
989
+ body_of_v = {}
990
+ for (bi, _q, vadr, _wq, wv) in layout:
991
+ for k in range(wv):
992
+ body_of_v[vadr + k] = bi
993
+ for vi in jnt_v:
994
+ bi = body_of_v.get(vi, -1)
995
+ jt = jm["bodies"][bi].get("joint") if bi >= 0 else None
996
+ a = A.get(bi, 0.0)
997
+ names["jointvel"].append(f"qd{vi}")
998
+ # A SLIDE joint's rate is already m/s; only an angular rate needs the jacobian to become one.
999
+ # Multiplying a slide by A^2 would convert twice. (No slide dofs exist in armless_ball, so this
1000
+ # was a dormant bug rather than a live one.)
1001
+ ws["jointvel"].append(1.0 if jt == "slide" else a * a)
1002
+ # TASKVEL. The EE velocities need d/dt of the FK, which is a forward-mode directional derivative of
1003
+ # body_poses_subset along the q-tangent of qd -- one extra FK-equivalent pass. Opt-out because that
1004
+ # cost is real: the reduced FK is the training bottleneck.
1005
+ # HEADING-FREE task space. Measured: 51% of v3's error signal was expressed in WORLD axes -- the
1006
+ # end-effector offsets, the COM offset, the EE velocities and every FK quaternion -- so the reward
1007
+ # demanded the CLIP'S ABSOLUTE COMPASS DIRECTION. That is fatal for multi-clip (each clip walks a
1008
+ # different way) and it blocks ever asking the policy to walk in a chosen direction. With this on,
1009
+ # every task-space quantity is expressed in the ROOT'S OWN heading frame -- the policy's in its own,
1010
+ # the reference in the reference's -- so rotating either about world z changes nothing.
1011
+ # The observation must agree (DN_YAW_FREE in the env drops the yaw from the root quat there);
1012
+ # one flag drives both so they cannot disagree.
1013
+ self.IM_YAW_FREE = False
1014
+ self.IM_V3_TASKVEL = True
1015
+ if self.IM_V3_TASKVEL:
1016
+ for b in m.feet:
1017
+ names["taskvel"].append(f"fk:eevel{b}"); ws["taskvel"].append(1.0)
1018
+ # ROOTVEL: the root's own linear velocity, its OWN group. It used to ride along in `taskvel`, where
1019
+ # the two foot velocities took 95.9% and the three root dofs 4.1% -- so the root shared an exponent
1020
+ # calibrated almost entirely by the feet. The lateral component in particular was 1.4% of that group
1021
+ # and 34.3% of its own, and the lateral channel is what separates a rollout that falls from one that
1022
+ # does not (AUC 0.995 over 50 rollouts). Same argument as the joint/task split: two scales in one
1023
+ # group means the smaller one is never read at its own scale.
1024
+ for vi in root_lin_v: # already m/s, MEASURED, body frame (fwd, lat, vert)
1025
+ names["rootvel"].append(f"qd{vi}"); ws["rootvel"].append(1.0)
1026
+ for vi in ang_v:
1027
+ names["angvel"].append(f"qd{vi}"); ws["angvel"].append(1.0)
1028
+ self._v3_build_ref_eevel()
1029
+ # PER CLIP, not pooled: the whole point of the clip normalization is that the reference's own
1030
+ # scale varies 1.74-3.09x across clips, and averaging them back together throws that away.
1031
+ scale = [self._v3_reference_scale(names, ws,
1032
+ slice(int(self.clip_start[c]),
1033
+ int(self.clip_start[c]) + int(self.clip_T[c])))
1034
+ for c in range(self.n_clips)]
1035
+ self._v3 = JacobianAbsoluteReward(comp_names=names, comp_w=ws, device=self.device,
1036
+ clip_scale=scale)
1037
+ self._v3_last_E = None
1038
+ self._v3_acc_contrib = {g: None for g in self._v3.active} # running sum of w_j * e_j per component
1039
+ self._v3_acc_E = {g: [] for g in self._v3.active} # E_g batches, for mean/p50/p90
1040
+ self._v3_acc_n = 0
1041
+ # EPOCH accumulation, always on. `_v3_last_E` is one control step's batch out of the ~32 x n_env an
1042
+ # epoch takes, which is a noisy sample to call a time series. These stay on the DEVICE (sum only, no
1043
+ # .item()), so there is no per-step sync; the logger syncs once per logged epoch and resets. E_g's mean
1044
+ # is derived from these because E_g = sum_j w_j e_j is LINEAR in e, so one accumulator per group covers
1045
+ # both the group mean and the per-component breakdown -- and the breakdown is the diagnostic that
1046
+ # matters here, `joint` being 82% the two hip quaternions.
1047
+ self._v3_ep_sum = {g: None for g in self._v3.active}
1048
+ self._v3_ep_n = 0
1049
+ prov = self._v3.alpha_provisional
1050
+ print("[imitation] IM_V3 on: " + ", ".join(f"{g}={len(names[g])}" for g in GROUPS3 if names[g])
1051
+ + f" | alpha={ {g: float(f'{v:.4g}') for g, v in self._v3.alpha.items()} }"
1052
+ + f" | track={self._v3.TRACK} delta={self._v3.DELTA:g}"
1053
+ + f" | taskvel={int(self.IM_V3_TASKVEL)}"
1054
+ + f" | A span {min(A.values()):.4g}..{max(A.values()):.4g} m/rad"
1055
+ + f" | authority frames {min(nf, self.ref_T)}", flush=True)
1056
+ # The clip factors are the one thing here that changes with the reference, so print them next to the
1057
+ # exponents they scaled: reading a run's alpha without them says nothing about what it actually used.
1058
+ print(f"[imitation] IM_V3 clip_norm={int(self._v3.CLIP_NORM)}"
1059
+ + f" | ref_scale={ {g: float(f'{v:.4g}') for g, v in self._v3.clip_scale.items()} }"
1060
+ + f" | factor={ {g: float(f'{v:.3f}') for g, v in self._v3.clip_factor.items()} }"
1061
+ + f" | alpha_base={ {g: float(f'{v:.4g}') for g, v in self._v3.alpha_base.items()} }",
1062
+ flush=True)
1063
+ if prov:
1064
+ print("[imitation] IM_V3 WARNING: alpha is PROVISIONAL for "
1065
+ + ", ".join(f"{g}({self._v3.alpha_src[g]})" for g in prov)
1066
+ + " -- run tools/im_v3_calibrate.py against a known-good checkpoint and set "
1067
+ + " ".join(f"DN_IM_V3_ALPHA_{g.upper()}" for g in prov)
1068
+ + " before reading this run as evidence about the reward's shape.", flush=True)
1069
+
1070
+ def _v3_build_ref_eevel(self):
1071
+ """Reference root-relative END-EFFECTOR VELOCITY per frame, (3,T) per foot.
1072
+
1073
+ Cyclic CENTRAL difference of the already-precomputed reference EE positions: error O(dt^2) and
1074
+ aligned at frame t. This deliberately does NOT reproduce the operator that produced `ref_qd`, which
1075
+ is a FORWARD difference -- fitting `ref_qd[t]` against a central difference centred at t+s gives
1076
+ cos 0.9134 / 0.9553 / 0.9872 / 0.9979 / 0.9872 for s = -1, -0.5, 0, +0.5, +1 on the hinge dofs
1077
+ (identity-mapped, so no convention enters), i.e. `ref_qd[t]` is the velocity at t+0.5, half a frame
1078
+ late and 6.5% off in norm. `jointvel` inherits that bias; `taskvel` does not. Fixing `ref_qd` is a
1079
+ retargeter change and is tracked separately.
1080
+
1081
+ The wrap is exact rather than an approximation because the training references are closed loops, and
1082
+ because the reward already indexes the reference cyclically (`i0 = floor(f) % T`). A WHOLE clip
1083
+ (loop=False) does not wrap: its two end frames take the one-sided difference (see _time_derivative).
1084
+ Open clips (cyclic=False) are indexed first-to-last frame (clip_frame_idx), so their ends are differenced
1085
+ one-sided.
1086
+ """
1087
+ # WRAP WITHIN EACH CLIP. The clips are concatenated along time, so a global (t+-1) would difference
1088
+ # the end of one clip against the start of the next and put a spurious velocity spike at every seam.
1089
+ # An OPEN clip (self.cyclic False, the step library) is differenced one-sided at its two ends instead.
1090
+ dev = self._ref_ee[0].device
1091
+ ip = torch.empty(self.ref_T_total, dtype=torch.long, device=dev)
1092
+ im = torch.empty_like(ip)
1093
+ for c in range(self.n_clips):
1094
+ s0, T = int(self.clip_start[c]), int(self.clip_T[c])
1095
+ t = torch.arange(T, device=dev)
1096
+ if not self.cyclic: # an open clip (the step library): its two ends one-sided
1097
+ ip[s0:s0 + T] = s0 + (t + 1).clamp(max=T - 1)
1098
+ im[s0:s0 + T] = s0 + (t - 1).clamp(min=0)
1099
+ elif bool(self.clip_loop[c]):
1100
+ ip[s0:s0 + T] = s0 + (t + 1) % T
1101
+ im[s0:s0 + T] = s0 + (t - 1) % T
1102
+ else: # clamp at the ends: frames 0 and T-1 difference one step
1103
+ assert T >= 2, (self.clip_paths[c], T)
1104
+ ip[s0:s0 + T] = s0 + (t + 1).clamp(max=T - 1)
1105
+ im[s0:s0 + T] = s0 + (t - 1).clamp(min=0)
1106
+ if not self.cyclic:
1107
+ span = (ip - im).to(self._ref_ee[0].dtype) * self.ref_dt
1108
+ self._ref_ee_vel = [((e[:, ip] - e[:, im]) / span).contiguous() for e in self._ref_ee]
1109
+ return
1110
+ self._ref_ee_vel = [((e[:, ip] - e[:, im]) / (2.0 * self.ref_dt)).contiguous()
1111
+ for e in self._ref_ee]
1112
+ if self.any_nonloop:
1113
+ # The two clamped end frames of a whole clip span ONE frame, not two, so their central-difference
1114
+ # quotient is half the one-sided one: scale those columns by 2 (exact in floating point). Loop frames
1115
+ # and interior frames are multiplied by exactly 1, so they keep the bits of the loop-only code.
1116
+ loop_f = torch.repeat_interleave(self.clip_loop, self.clip_T) # (sum_T,) per-frame flag
1117
+ span = torch.where(loop_f, torch.full_like(ip, 2), ip - im)
1118
+ fix = (2.0 / span.to(self._ref_ee_vel[0].dtype))[None, :]
1119
+ self._ref_ee_vel = [(v * fix).contiguous() for v in self._ref_ee_vel]
1120
+
1121
+ def _v3_build_ref_yawfree(self):
1122
+ """Re-express every REFERENCE task-space target in the REFERENCE's own heading frame, once at init.
1123
+
1124
+ The policy's side is rotated per step by its OWN heading (see _v3_components). Comparing
1125
+ `R_yaw(policy)^T (p_b - root)` against `R_yaw(ref)^T (p_b - root)_ref` is invariant to rotating
1126
+ either about world z, which is what makes one clip usable at any compass heading and what lets
1127
+ clips that walk different ways share a reward.
1128
+ """
1129
+ from diffneusim.model.monitor import DnModelMonitor as _M
1130
+ with torch.no_grad():
1131
+ rq = self.ref_q.t().contiguous() # (nq,T)
1132
+ root_q = rq[3:7] # the reference root's world orientation
1133
+ self._ref_ee_yf = [_M.to_yaw_frame(root_q, e) for e in self._ref_ee]
1134
+ self._ref_ee_vel_yf = [_M.to_yaw_frame(root_q, v) for v in self._ref_ee_vel]
1135
+ com3 = torch.cat([self._ref_com_rel_xy,
1136
+ torch.zeros_like(self._ref_com_rel_xy[:1])], 0) # xy -> a 3-vector to rotate
1137
+ self._ref_com_rel_xy_yf = _M.to_yaw_frame(root_q, com3)[:2].contiguous()
1138
+ self._ref_foot_q_yf = [_M.yaw_free_quat(q) for q in getattr(self, "_ref_foot_q", [])]
1139
+
1140
+ def _v3_reference_scale(self, names, ws, sl=None):
1141
+ """The REFERENCE's own natural scale per group -- what a policy tracking with a fixed RELATIVE error
1142
+ would put into E_g. `alpha` is divided by this (relative to 07_01's) so an exponent means the same
1143
+ thing on a slow clip and a fast one.
1144
+
1145
+ Measured over 18 CMU walk clips (0.92-1.84 m/s): the position groups spread 1.74-1.86x and the
1146
+ velocity groups 2.56-3.09x, the latter roughly with the square of gait speed. Applying 07_01's
1147
+ alpha_taskvel to 08_08 would put alpha*E at 3.09x, i.e. exp(-3.09) = 0.045 -- the saturation this
1148
+ design exists to avoid, arriving from nothing but a change of clip.
1149
+
1150
+ This is NOT the adaptation that was deleted. It reads the REFERENCE, once, at init; it never sees the
1151
+ policy, so the reward cannot become a function of its own history. Same category as the static
1152
+ feasibility check that docs/training/concepts/imitation-reward.md prefers over an adaptive s_j.
1153
+
1154
+ The estimator per group mirrors the reward's own aggregation with the SAME w_j, using a variance (or a
1155
+ mean square, for the rates) in place of the tracking error:
1156
+
1157
+ joint sum_j w_j * var(q_ref,j); quaternion blocks: mean squared geodesic to the mean
1158
+ task var of the root-relative EE positions + COM_xy + height
1159
+ ang mean squared geodesic of each FK orientation to its own mean
1160
+ jointvel sum_j w_j * mean(qd_ref,j^2)
1161
+ taskvel mean|v_ee_ref|^2 per foot + mean(root linear rate^2)
1162
+ angvel mean(root angular rate^2)
1163
+ """
1164
+ with torch.no_grad():
1165
+ # On the HOST deliberately: this runs once at init on a (nq, T) reference, so the device buys
1166
+ # nothing, and mixing a device reference with the host-side `ws` lists is a CUDA-only crash that a
1167
+ # CPU test cannot see (it was one -- caught by the neu smoke run, not by the suite).
1168
+ sl = sl if sl is not None else slice(None)
1169
+ q = self.ref_q.t().contiguous().cpu()[:, sl] # (nq,T) of ONE clip when sl is given
1170
+ qd = self.ref_qd.t().contiguous().cpu()[:, sl] # (nv,T)
1171
+ pos_scalars = self._v3_pos_scalars.cpu()
1172
+ jointvel_idx = self._v3_jointvel_idx.cpu()
1173
+ rootlin_idx = self._v3_rootlin_idx.cpu()
1174
+ angvel_idx = self._v3_angvel_idx.cpu()
1175
+
1176
+ def geo_var(qq): # mean squared geodesic angle to the mean quat
1177
+ mu = qq.mean(dim=1, keepdim=True)
1178
+ mu = mu / mu.norm(dim=0, keepdim=True).clamp_min(1e-12)
1179
+ dot = (qq * mu).sum(0).abs().clamp(max=1.0 - 1e-6)
1180
+ return float(((2.0 * torch.acos(dot)) ** 2).mean())
1181
+
1182
+ wj = {g: torch.tensor(ws[g], dtype=torch.float32) for g in ws if ws[g]}
1183
+ parts = [q[pos_scalars].var(dim=1).float()]
1184
+ parts += [torch.tensor([geo_var(q[s:s + L])]) for (s, L) in self._v3_quat_blocks]
1185
+ sc = {"joint": float((wj["joint"] * torch.cat(parts)).sum())}
1186
+ ee = [e.cpu()[:, sl] for e in self._ref_ee]
1187
+ com_xy = self._ref_com_rel_xy.cpu()[:, sl]
1188
+ task = sum(float((e - e.mean(dim=1, keepdim=True)).pow(2).sum(0).mean()) for e in ee)
1189
+ task += float((com_xy - com_xy.mean(dim=1, keepdim=True)).pow(2).sum(0).mean())
1190
+ task += float(q[self.m.root_height].var())
1191
+ sc["task"] = task
1192
+ ang = [] \
1193
+ + [geo_var(x.cpu()[:, sl]) for x in getattr(self, "_ref_foot_q", [])]
1194
+ sc["ang"] = float(sum(ang))
1195
+ sc["jointvel"] = float((wj["jointvel"]
1196
+ * qd[jointvel_idx].pow(2).mean(dim=1).float()).sum())
1197
+ sc["taskvel"] = sum(float(v.cpu()[:, sl].pow(2).sum(0).mean()) for v in self._ref_ee_vel)
1198
+ sc["rootvel"] = float(qd[rootlin_idx].pow(2).mean(dim=1).sum())
1199
+ sc["angvel"] = float(qd[angvel_idx].pow(2).mean(dim=1).sum())
1200
+ for g in GROUPS3:
1201
+ if names[g]:
1202
+ assert sc[g] > 0.0, (g, sc[g], "a reference with zero excursion in a rewarded group")
1203
+ return sc
1204
+
1205
+ def _v3_fk_with_velocity(self, q, qd):
1206
+ """The reduced FK plus the EXACT instantaneous velocity of the bodies the task terms read.
1207
+
1208
+ `d/dt pos_b = J_b(q) qd`, assembled from the jacobian columns of the chain by
1209
+ `body_velocities_from_poses` -- not a finite difference across control steps, and differentiable in
1210
+ both q and qd, which BPTT needs. Only the root and the feet are asked for; the whole reduced FK is
1211
+ NOT re-evaluated (see that method for the +320% forward-mode measurement that ruled out the
1212
+ torch.func.jvp version).
1213
+ """
1214
+ pos, quat, com = self.monitor.body_poses_subset(q, self._fk_bodies, self._fk_need_com)
1215
+ want = [self.m.root_body] + [int(b) for b in self.m.feet]
1216
+ dpos = self.monitor.body_velocities_from_poses(pos, quat, qd, want)
1217
+ return pos, quat, com, dpos
1218
+
1219
+ def ankle_moment(self, pos, quat, cf):
1220
+ """Per-foot ankle moment the ground reaction demands, N.m/kg, + = plantarflexion, (2, n) [right, left]: sum over the
1221
+ foot's contact spheres of (x_i - x_a) F_z,i - (z_i - z_a) F_x,i, the force applied at the sphere's ground point (centre -
1222
+ radius along the ground normal), x_a / z_a the talus origin. One batched evaluation from the reward's own reduced FK;
1223
+ equals the env's loop reference (GpuFullBodyVecEnv._im_ankle_moment_reference) to float roundoff."""
1224
+ from diffneusim.model.monitor import _quat_rotate_batched
1225
+ P = torch.stack([pos[b] for b in self._ank_body]) # (K, 3, n)
1226
+ Q = torch.stack([quat[b] for b in self._ank_body]) # (K, 4, n)
1227
+ p = P + _quat_rotate_batched(Q, self._ank_cen.to(P.dtype)) # sphere centres, (K, 3, n)
1228
+ pa = torch.stack([pos[t] for t in self._ank_talus])[self._ank_foot] # each sphere's ankle, (K, 3, n)
1229
+ off = self._ank_off.to(P.dtype)
1230
+ rx = p[:, 0] - off[:, 0] - pa[:, 0]
1231
+ rz = p[:, 2] - off[:, 1] - pa[:, 2]
1232
+ F = cf[self._ank_rows].to(P.dtype) # (K, 3, n), the foot rows in sphere order
1233
+ m = rx * F[:, 2] - rz * F[:, 0] # (K, n)
1234
+ return (self._ank_sel.to(P.dtype) @ m) / self._ank_mass
1235
+
1236
+ def _v3_components(self, q, q_ref, qd, qd_ref, pos, quat, com, root, _lerp, i0, i1, wf, dpos):
1237
+ """Per-component RAW errors per group; the group's multiplier turns them into its unit."""
1238
+ m = self.m
1239
+ out = {}
1240
+ # --- JOINT (m^2 after x A^2): the jacobian-mapped proxy -------------------------------------
1241
+ p = [(q[self._v3_pos_scalars] - q_ref[self._v3_pos_scalars]) ** 2] # rad^2 -> x A^2
1242
+ for (s, L) in self._v3_quat_blocks:
1243
+ a, b = q[s:s + L], q_ref[s:s + L]
1244
+ dot = (a * b).sum(0).abs().clamp(max=1.0 - 1e-6)
1245
+ p.append(((2.0 * torch.acos(dot)) ** 2)[None, :])
1246
+ out["joint"] = torch.cat(p, 0)
1247
+ # --- TASK (m^2): the same displacement measured directly ------------------------------------
1248
+ # Under IM_YAW_FREE each side is expressed in its OWN heading frame, so the comparison no longer
1249
+ # asks the policy to face the clip's compass direction (see _v3_build_ref_yawfree).
1250
+ ee_ref, com_ref = self._ref_ee, self._ref_com_rel_xy
1251
+ def _tf(v):
1252
+ return v
1253
+ k_ = [((_tf(pos[b] - root) - _lerp(ee_ref[k])) ** 2).sum(0)[None, :]
1254
+ for k, b in enumerate(m.feet)]
1255
+ com_rel = com[:2] - root[:2]
1256
+ k_.append(((com_rel - _lerp(com_ref)) ** 2).sum(0)[None, :])
1257
+ k_.append(((q[m.root_height] - q_ref[m.root_height]) ** 2)[None, :])
1258
+ out["task"] = torch.cat(k_, 0)
1259
+ a = []
1260
+ fq = [quat[b] for b in self._v3_feet_q]
1261
+ tref, fref = getattr(self, "_ref_torso_q", None), getattr(self, "_ref_foot_q", [])
1262
+ for k in range(len(fq)):
1263
+ a.append(self._v2_geodesic(fq[k], fref[k], i0, i1, wf)[None, :])
1264
+ out["ang"] = torch.cat(a, 0) if a else torch.zeros(0, q.shape[1], device=q.device)
1265
+ dv = (qd - qd_ref) ** 2
1266
+ out["jointvel"] = dv[self._v3_jointvel_idx]
1267
+ tv = []
1268
+ if self.IM_V3_TASKVEL:
1269
+ assert dpos is not None, "IM_V3_TASKVEL needs the forward-mode FK derivative"
1270
+ v_root = dpos[m.root_body]
1271
+ vref = self._ref_ee_vel
1272
+ for k, b in enumerate(m.feet):
1273
+ tv.append(((_tf(dpos[b] - v_root) - _lerp(vref[k])) ** 2).sum(0)[None, :])
1274
+ out["taskvel"] = torch.cat(tv, 0) if tv else torch.zeros(0, q.shape[1], device=q.device)
1275
+ out["rootvel"] = dv[self._v3_rootlin_idx]
1276
+ out["angvel"] = dv[self._v3_angvel_idx]
1277
+ return {g: out[g] for g in GROUPS3 if g in out and out[g].shape[0]}
1278
+
1279
+ def _v3_epoch_errors(self):
1280
+ """Per-component MEAN raw error since the last call, then reset. One host sync, at log time.
1281
+
1282
+ Returns `{group: {component_name: mean_e}}`. The group mean follows as `sum_j w_j * mean(e_j)` because
1283
+ E_g is linear in e -- so the caller gets both from this one read.
1284
+ """
1285
+ if not self._v3_ep_n:
1286
+ return {}
1287
+ n = float(self._v3_ep_n)
1288
+ out = {}
1289
+ for g in self._v3.active:
1290
+ v = (self._v3_ep_sum[g] / n).float().cpu()
1291
+ out[g] = {nm: float(x) for nm, x in zip(self._v3.names[g], v)}
1292
+ self._v3_ep_sum[g] = None
1293
+ self._v3_ep_n = 0
1294
+ return out
1295
+
1296
+ def _v3_accumulate(self, e, E):
1297
+ """Sum each component's CONTRIBUTION (w_j * e_j) and keep every E_g batch, for the calibrator.
1298
+
1299
+ The contribution, not the raw error: `w_j` spans four orders of magnitude, so a share table built
1300
+ from raw `e_j` would rank components by their natural scale instead of by what they actually put into
1301
+ E_g -- which is the mistake v2's `1/var` normalization made in a different costume.
1302
+ """
1303
+ with torch.no_grad():
1304
+ for g in self._v3.active:
1305
+ c = (self._v3.w[g][:, None] * e[g]).sum(1).float().cpu()
1306
+ self._v3_acc_contrib[g] = c if self._v3_acc_contrib[g] is None \
1307
+ else self._v3_acc_contrib[g] + c
1308
+ self._v3_acc_E[g].append(E[g].detach().float().cpu())
1309
+ self._v3_acc_n += int(E[self._v3.active[0]].numel())
1310
+
1311
+ def _v3_reward(self, q, q_ref, qd, qd_ref, pos, quat, com, root, _lerp, i0, i1, wf,
1312
+ a_mean, train_steps, dpos=None):
1313
+ """r = sum_g W_g * exp(-alpha_g * E_g) - effort, with the actor's gradient split off per group."""
1314
+ e = self._v3_components(q, q_ref, qd, qd_ref, pos, quat, com, root, _lerp, i0, i1, wf, dpos)
1315
+ r = None
1316
+ E = {}
1317
+ for g in self._v3.active:
1318
+ E[g] = self._v3.group_error(g, e[g])
1319
+ term = self._v3.group_reward(g, E[g], self._clip_of(E[g]))
1320
+ r = term if r is None else r + term
1321
+ self._v3_last_E = {g: E[g].detach() for g in self._v3.active}
1322
+ with torch.no_grad(): # device-resident, no sync: the logger syncs and resets
1323
+ for g in self._v3.active:
1324
+ s = e[g].detach().sum(1)
1325
+ self._v3_ep_sum[g] = s if self._v3_ep_sum[g] is None else self._v3_ep_sum[g] + s
1326
+ self._v3_ep_n += int(e[self._v3.active[0]].shape[1])
1327
+ return self._effort(r, a_mean, train_steps)
1328
+
1329
+ def _v2_components(self, q, q_ref, qd, qd_ref, pos, quat, com, root, _lerp, i0, i1, wf):
1330
+ """Per-component squared errors for each dimension group, in the order _v2_build named them.
1331
+
1332
+ Every entry is a (k, n) tensor in that group's own units -- rad^2, m^2, (rad/s)^2, (m/s)^2 -- which
1333
+ is the whole point of grouping: v1 compared rad^2 against m^2 inside one sum and the comparison was
1334
+ meaningless. Differentiable in q/qd (SHAC/RPO pathwise): nothing here is detached.
1335
+ """
1336
+ m = self.m
1337
+ out = {}
1338
+ ang = [(q[self._v2_ang_scalars] - q_ref[self._v2_ang_scalars]) ** 2] # (k,n) rad^2
1339
+ for (s, L) in self._v2_quat_blocks:
1340
+ dot = (q[s:s + L] * q_ref[s:s + L]).sum(0).abs().clamp(max=1.0 - 1e-6)
1341
+ ang.append(((2.0 * torch.acos(dot)) ** 2)[None, :]) # squared geodesic
1342
+ for k, b in enumerate(self._v2_feet_q):
1343
+ ang.append(self._v2_geodesic(quat[b], self._ref_foot_q[k], i0, i1, wf)[None, :])
1344
+ out["ang"] = torch.cat(ang, 0)
1345
+ ee = [(((pos[b] - root) - _lerp(self._ref_ee[k])) ** 2).sum(0)[None, :]
1346
+ for k, b in enumerate(m.feet)] # (1,n) m^2 each
1347
+ com_xy = ((com[:2] - root[:2]) - _lerp(self._ref_com_rel_xy)) ** 2
1348
+ ee.append(com_xy.sum(0)[None, :])
1349
+ ee.append(((q[m.root_height] - q_ref[m.root_height]) ** 2)[None, :])
1350
+ out["pos"] = torch.cat(ee, 0)
1351
+ dv = (qd - qd_ref) ** 2
1352
+ out["angvel"] = dv[self._v2_angvel_idx]
1353
+ out["linvel"] = dv[self._v2_linvel_idx]
1354
+ return {g: out[g] for g in GROUPS if out[g].shape[0]}
1355
+
1356
+ def _v2_geodesic(self, cq, ref_q4, i0, i1, wf):
1357
+ """Squared geodesic angle (rad^2) between an FK quat (4,n) and the phase-interpolated ref (4,T)."""
1358
+ a4 = ref_q4[:, i0]; b4 = ref_q4[:, i1]
1359
+ b4 = torch.where((a4 * b4).sum(0, keepdim=True) < 0.0, -b4, b4) # shortest-arc sign align
1360
+ rq = a4 * (1.0 - wf) + b4 * wf
1361
+ rq = rq / (rq.norm(dim=0, keepdim=True) + 1e-9)
1362
+ dot = (cq * rq).sum(0).abs().clamp(max=1.0 - 1e-6)
1363
+ return (2.0 * torch.acos(dot)) ** 2
1364
+
1365
+ def _pose_term_names(self):
1366
+ """Joint name per pose TERM, in the exact order reward()/pose_error() accumulate them:
1367
+ the scalar dofs (pose_scalar_idx), then the quat blocks minus the root quat when IM_WROOT rewards
1368
+ it separately. One list serves both the lumped sum and the IM_POSE_DECOUPLE per-joint terms."""
1369
+ m = self.m
1370
+ assert m.q_joint is not None, "Morphology has no q_joint names -- rebuild it (Morphology.build)"
1371
+ names = [m.q_joint[int(i)] for i in m.pose_scalar_idx.tolist()]
1372
+ for (s, L) in m.quat_blocks:
1373
+ names.append(m.q_joint[s])
1374
+ return names
1375
+
1376
+ def _joint_ranges(self):
1377
+ """Per-q travel from the dnmodel, for the variance floor. Unlimited/absent -> a full turn.
1378
+ The myoLeg envs construct the task without `model_jm`; every dof then takes the full-turn default,
1379
+ which makes the floor loose rather than wrong (a loose floor only under-weights a pinned dof)."""
1380
+ rng = {}
1381
+ for b in (self.m_jm or {}).get("bodies", []):
1382
+ jt = b.get("joint", "fixed")
1383
+ if jt == "fixed" or "coupled" in b:
1384
+ continue
1385
+ r = b.get("range")
1386
+ span = float(r[1] - r[0]) if (r and b.get("limited", True)) else 2.0 * math.pi
1387
+ for k in range({"free": 7, "ball": 4, "revolute": 1, "slide": 1}[jt]):
1388
+ rng[int(b["qadr"]) + k] = span
1389
+ return rng
1390
+
1391
+ def _pose_var_scale(self):
1392
+ """(n_terms,) reference variance per POSE term, floored at (frac*range)^2. Term order == the
1393
+ reward's (pose_scalar_idx, then quat_blocks minus the separately-rewarded root quat)."""
1394
+ m, rng = self.m, self._joint_ranges()
1395
+ out = []
1396
+ for i in m.pose_scalar_idx.tolist():
1397
+ v = float(self.ref_q[:, i].var(unbiased=False))
1398
+ out.append(max(v, (self.IM_VARNORM_FLOOR * rng.get(i, 2.0 * math.pi)) ** 2))
1399
+ for (s, L) in m.quat_blocks:
1400
+ rq = self.ref_q[:, s:s + L] # geodesic spread about the mean rotation
1401
+ mu = rq.mean(0); mu = mu / mu.norm().clamp_min(1e-12)
1402
+ d = (rq @ mu).abs().clamp(max=1.0 - 1e-6)
1403
+ v = float(((2.0 * torch.acos(d)) ** 2).mean()) # rad^2, same units as the scalar terms
1404
+ out.append(max(v, (self.IM_VARNORM_FLOOR * math.pi) ** 2))
1405
+ t = torch.tensor(out, dtype=torch.float32, device=self.ref_q.device)
1406
+ assert t.numel() == self._n_pose_terms_reward and bool((t > 0).all()), (t.numel(), t)
1407
+ return t
1408
+
1409
+ def _vel_var_scale(self):
1410
+ """(nv,) reference velocity variance per dof, floored at a fraction of the clip's own peak so a
1411
+ dof the reference holds still does not dominate. Same rationale as the pose floor."""
1412
+ v = self.ref_qd.var(dim=0, unbiased=False)
1413
+ floor = (self.IM_VARNORM_FLOOR * self.ref_qd.abs().max()) ** 2
1414
+ return v.clamp_min(floor.clamp_min(1e-9))
1415
+
1416
+ def _build_pose_weights(self, spec):
1417
+ """Parse `<substring>:<multiplier>[,...]` into a per-term weight vector (unmatched terms = 1.0).
1418
+
1419
+ Substring match on the joint name, case-insensitive, so `knee:2` catches knee_angle_r and _l without
1420
+ naming either. Fails loudly on a pattern that matches nothing -- a typo must not silently train the
1421
+ unweighted reward for hours."""
1422
+ names = self._pose_term_names()
1423
+ w = [1.0] * len(names)
1424
+ for item in spec.split(","):
1425
+ if not item.strip():
1426
+ continue
1427
+ pat, sep, mul = item.partition(":")
1428
+ assert sep and pat.strip(), f"DN_IM_POSE_W item must be '<joint>:<mult>', got {item!r}"
1429
+ mul = float(mul)
1430
+ assert mul > 0.0, f"pose weight must be > 0 (it scales a weighted mean), got {mul} for {pat!r}"
1431
+ pat = pat.strip().lower()
1432
+ hit = [k for k, nm in enumerate(names) if pat in nm.lower()]
1433
+ assert hit, (f"DN_IM_POSE_W pattern {pat!r} matched no tracked pose dof; "
1434
+ f"tracked: {sorted(set(names))}")
1435
+ for k in hit:
1436
+ w[k] *= mul
1437
+ print("[imitation] pose term weights: "
1438
+ + ", ".join(f"{nm}={x:g}" for nm, x in zip(names, w) if x != 1.0)
1439
+ + f" (rest 1.0, {len(names)} terms, weight sum {sum(w):g})", flush=True)
1440
+ return torch.tensor(w, dtype=torch.float32, device=self.m.pose_scalar_idx.device)
1441
+
1442
+ def frame_idx(self, phase):
1443
+ """(i0, i1, wf) GLOBAL frame indices bracketing `phase` in each env's OWN clip, plus the blend.
1444
+
1445
+ The clips are concatenated along time, so `clip_start[c] + (k % clip_T[c])` addresses the whole
1446
+ corpus with one index -- which is what lets every per-frame precompute stay a single tensor and every
1447
+ `A[..., i0]` gather stay untouched from the single-clip code.
1448
+
1449
+ A WHOLE clip (loop=False) never wraps: its phase is not taken mod 1 and both indices CLAMP at the last
1450
+ frame, so at or past frame T-1 the target is the last frame itself, never a blend with frame 0. The env
1451
+ truncates the episode before the phase can leave the clip (clip_end), so the clamp only absorbs float
1452
+ round-off at the final step.
1453
+ """
1454
+ cid = self._clip_of(phase)
1455
+ if not self.cyclic: # open clips (the step library), clip_frame_idx
1456
+ return clip_frame_idx(phase, self.clip_start[cid], self.clip_T[cid], False)
1457
+ T = self.clip_T[cid]
1458
+ if not self.any_nonloop:
1459
+ f = (phase % 1.0) * T.to(phase.dtype)
1460
+ k = torch.floor(f).long()
1461
+ i0 = self.clip_start[cid] + (k % T)
1462
+ i1 = self.clip_start[cid] + ((k + 1) % T)
1463
+ return i0, i1, f - torch.floor(f)
1464
+ loop = self.clip_loop[cid]
1465
+ f = torch.where(loop, phase % 1.0, phase) * T.to(phase.dtype)
1466
+ k = torch.floor(f).long()
1467
+ last = T - 1
1468
+ i0 = self.clip_start[cid] + torch.where(loop, k % T, torch.minimum(k, last))
1469
+ i1 = self.clip_start[cid] + torch.where(loop, (k + 1) % T, torch.minimum(k + 1, last))
1470
+ return i0, i1, f - torch.floor(f)
1471
+
1472
+ def _clip_of(self, phase):
1473
+ """Per-env clip ids, broadcast to match `phase`. A scalar/short clip_id (the single-clip case, or a
1474
+ bare ref_at before any reset) expands rather than erroring, so tools and tests need no clip bookkeeping."""
1475
+ cid = self.clip_id
1476
+ if cid.numel() == phase.shape[0]:
1477
+ return cid
1478
+ assert cid.numel() == 1 or self.n_clips == 1, (
1479
+ f"clip_id has {cid.numel()} entries for {phase.shape[0]} envs; call rsi() to assign clips")
1480
+ return cid[:1].expand(phase.shape[0]) if cid.numel() else \
1481
+ torch.zeros(phase.shape[0], dtype=torch.long, device=phase.device)
1482
+
1483
+ def ref_at(self, phase):
1484
+ """Reference (q, qd) at continuous phase of each env's own clip: CYCLIC in [0,1) on a loop, clamped at the
1485
+ last frame on a whole clip, and [0,1] from the first to the last frame on an open one (self.cyclic,
1486
+ clip_frame_idx); see frame_idx. Linear interp on scalars; sign-aligned nlerp on quat blocks. Returns
1487
+ (q_ref (nq,n), (nv,n))."""
1488
+ return self._ref_at_frames(*self.frame_idx(phase))
1489
+
1490
+ def _ref_at_frames(self, i0, i1, wf):
1491
+ """ref_at on frames frame_idx already bracketed (a caller that also needs the frames takes them once)."""
1492
+ w = wf.unsqueeze(0) # (1,n)
1493
+ q0 = self.ref_q[i0].t(); q1 = self.ref_q[i1].t() # (nq,n)
1494
+ qd0 = self.ref_qd[i0].t(); qd1 = self.ref_qd[i1].t()
1495
+ q = q0 * (1.0 - w) + q1 * w
1496
+ qd = qd0 * (1.0 - w) + qd1 * w
1497
+ for (s, L) in self.m.quat_blocks:
1498
+ a = q0[s:s + L]; b = q1[s:s + L]
1499
+ b = torch.where((a * b).sum(0, keepdim=True) < 0.0, -b, b) # shortest-arc sign align
1500
+ blend = a * (1.0 - w) + b * w
1501
+ q[s:s + L] = blend / (blend.norm(dim=0, keepdim=True) + 1e-9)
1502
+ return q, qd
1503
+
1504
+ def rsi(self, n, rng, stochastic):
1505
+ """Reference-state-init: phi ~ U[0,1) (a whole clip: U[0, phase_max], see set_control_dt) then
1506
+ (q0,qd0) ON the clip (+ optional reset noise, quat
1507
+ blocks renormalized). Draws from the PASSED (shared env) generator in a fixed order -- the env
1508
+ MUST have already consumed its own _start_state draws before calling this (RNG-stream parity)."""
1509
+ # MULTI-CLIP: pick each env's clip first, then a phase within it. Drawn from the SAME shared
1510
+ # generator in a fixed order, so the RNG-stream parity contract above still holds -- a single-clip
1511
+ # run draws nothing extra (the branch is skipped), keeping its stream bit-identical.
1512
+ # RETURNED, not stored: reset() is called for a SUBSET of envs (`env_ids`), so writing clip_id
1513
+ # wholesale here replaced all n_env entries with just that subset -- caught by _clip_of's own assert
1514
+ # ("clip_id has 14 entries for 2048 envs"). The env scatters it into clip_id[env_ids], exactly as it
1515
+ # already does for phase.
1516
+ # DN_CLIP_ONLY restricts the draw to a subset (comma-separated indices into the corpus list).
1517
+ # A multi-clip EVAL that samples uniformly reports the average over 115 different motions, which is not
1518
+ # a number anything can be concluded from -- "did it learn to walk at 0.5 m/s" needs the 0.5 m/s clip.
1519
+ # Training leaves it unset and draws from the whole corpus.
1520
+ if getattr(self, "clip_mix", None) is not None:
1521
+ # CURRICULUM OVER THE RSI POOL. `clip_mix = (n_first, p)`: clips [0, n_first) are the STARTING
1522
+ # pool and [n_first, n_clips) the FINAL one, and `p` is the probability of drawing from the
1523
+ # final pool. The env advances p from 0 to 1 on a schedule declared in the config, so the
1524
+ # whole thing reproduces from config + seed -- which is the line between a curriculum and a
1525
+ # warm start (see `every-knob-must-survive-a-writeup`).
1526
+ #
1527
+ # TWO DRAWS, not one, and only on this branch: the uniform picks the pool and the randint
1528
+ # picks within it. Gated so a run without a mix takes the original single-draw path and stays
1529
+ # bit-identical.
1530
+ n_first, p = self.clip_mix
1531
+ assert 0 < n_first < self.n_clips, (n_first, self.n_clips)
1532
+ use_final = torch.rand(n, generator=rng, device=self.device) < float(p)
1533
+ lo = torch.randint(n_first, (n,), generator=rng, device=self.device)
1534
+ hi = n_first + torch.randint(self.n_clips - n_first, (n,), generator=rng, device=self.device)
1535
+ cid = torch.where(use_final, hi, lo)
1536
+ elif self._clip_only is not None:
1537
+ sel = torch.randint(len(self._clip_only), (n,), generator=rng, device=self.device)
1538
+ cid = self._clip_only[sel]
1539
+ elif self.n_clips > 1:
1540
+ cid = torch.randint(self.n_clips, (n,), generator=rng, device=self.device)
1541
+ else:
1542
+ cid = torch.zeros(n, dtype=torch.long, device=self.device)
1543
+ self._rsi_clip_id = cid
1544
+ assert not (getattr(self, "RSI_STANCE", False) and self.n_clips > 1), (
1545
+ "RSI_STANCE indexes frames and turns them into a phase by dividing by ONE clip's length; that is "
1546
+ "meaningless across a concatenated corpus. Port it to per-clip stance frames before combining.")
1547
+ if getattr(self, "RSI_STANCE", False): # running: sample only stance phases (avoid mid-flight RSI)
1548
+ sel = torch.randint(len(self._stance_frames), (n,), generator=rng, device=self.device)
1549
+ phi = self._stance_frames[sel].float() / self.ref_T
1550
+ else:
1551
+ phi = torch.rand(n, generator=rng, device=self.device)
1552
+ if self.any_nonloop:
1553
+ # WHOLE CLIP: the same single draw, scaled into [0, phase_max] so the start keeps
1554
+ # RSI_END_MARGIN control steps before the clip end (set_control_dt). A loop clip's cap is
1555
+ # exactly 1.0, so its draw is unchanged in a mixed corpus.
1556
+ assert self._rsi_phase_max is not None, (
1557
+ "a whole clip (loop=False) needs the control dt for its RSI range; the env must call "
1558
+ "ImitationTask.set_control_dt before the first reset")
1559
+ phi = phi * self._rsi_phase_max[cid]
1560
+ if self.RSI_WINDOW is not None:
1561
+ assert self.n_clips == 1 and self.any_nonloop, "DN_RSI_WINDOW: one whole clip only"
1562
+ t0_, t1_, pw_ = self.RSI_WINDOW
1563
+ assert t1_ < self.ref_secs, (t1_, self.ref_secs)
1564
+ use_ = torch.rand(n, generator=rng, device=self.device) < pw_
1565
+ u_ = torch.rand(n, generator=rng, device=self.device)
1566
+ phw_ = torch.minimum((t0_ + u_ * (t1_ - t0_)) / self.ref_secs, self._rsi_phase_max[cid])
1567
+ phi = torch.where(use_, phw_, phi)
1568
+ prev, self.clip_id = self.clip_id, cid # ref_at must read the clips just drawn, not the stored ones
1569
+ try:
1570
+ q0, qd0 = self.ref_at(phi)
1571
+ finally:
1572
+ self.clip_id = prev
1573
+ # DN_RSI_NO_NOISE: skip the Gaussian reset noise so q0 sits EXACTLY on the clip. The 0.02-rad
1574
+ # per-DOF noise looks tiny at the root but COMPOUNDS up the spine chain to ~15 cm at the head, so a
1575
+ # ghost-overlay eval must disable it for frame-0 to coincide with the reference (RNG-stream parity
1576
+ # is irrelevant in eval). Still draws the randn so the shared-rng stream advances identically.
1577
+ # RSI reset noise: a SMALL Gaussian perturbation so the value fn / policy don't overfit to the exact
1578
+ # clip frames. A little is enough -- the rollout diverges from the clip anyway, we only need "not
1579
+ # bit-identical". The old 0.02 rad compounded up the spine/neck to a ~10 cm head offset at reset
1580
+ # (visible in the ghost overlay); default reduced to 0.005 (~0.3 deg/joint -> ~2 cm head), runtime-
1581
+ # configurable via DN_RSI_NOISE. The FREE BASE (root pos q[0:3]+quat q[3:7], vel qd[0:6]) is
1582
+ # skipped (a root tilt levers the whole body; the qk-drop reset excludes it too). DN_RSI_NO_NOISE
1583
+ # forces 0 (exact-on-clip, for ghost overlays).
1584
+ rsi_sd = 0.0 if os.environ.get("DN_RSI_NO_NOISE") else 0.005
1585
+ if stochastic and rsi_sd > 0.0:
1586
+ nq0 = rsi_sd * torch.randn(self.m.nq, n, generator=rng, device=self.device)
1587
+ nqd0 = (2.5 * rsi_sd) * torch.randn(self.m.nv, n, generator=rng, device=self.device)
1588
+ nq0[:7] = 0.0
1589
+ nqd0[:6] = 0.0
1590
+ q0 = q0 + nq0
1591
+ qd0 = qd0 + nqd0
1592
+ for (s, L) in self.m.quat_blocks:
1593
+ q0[s:s + L] = q0[s:s + L] / (q0[s:s + L].norm(dim=0, keepdim=True) + 1e-9)
1594
+ return q0, qd0, phi, cid
1595
+
1596
+ def pose_error(self, q, q_ref, w=None, scale=None):
1597
+ """Lumped squared pose error. `w` (per-term, from _build_pose_weights) re-weights the sum for the
1598
+ REWARD; callers that define a THRESHOLD (desync ET, DiffMimic snap drift) pass nothing, so their
1599
+ metric stays the plain sum. w=None keeps the original op order (bit-parity)."""
1600
+ idx = self.m.pose_scalar_idx
1601
+ sq = (q[idx] - q_ref[idx]) ** 2
1602
+ k = idx.numel()
1603
+ if scale is not None: # per-joint variance normalization (dimensionless)
1604
+ sq = sq / scale[:k].unsqueeze(1)
1605
+ if w is None:
1606
+ e_pose = sq.sum(0)
1607
+ else:
1608
+ assert w.numel() >= k, (w.numel(), k)
1609
+ e_pose = (w[:k].unsqueeze(1) * sq).sum(0)
1610
+ j = idx.numel() # next weight slot = first quat term
1611
+ for (s, L) in self.m.quat_blocks:
1612
+ dot = (q[s:s + L] * q_ref[s:s + L]).sum(0).abs()
1613
+ term = (1.0 - dot.clamp(max=1.0)) # legacy (1-|dot|); bit-parity
1614
+ if scale is not None:
1615
+ term = term / scale[j]
1616
+ e_pose = e_pose + (term if w is None else w[j] * term)
1617
+ j += 1
1618
+ if w is not None:
1619
+ assert j == w.numel(), (j, w.numel()) # term order must match the weights
1620
+ return e_pose
1621
+
1622
+ def advance_phase(self, phase, dt_ctrl):
1623
+ """Advance phase one control step. Returns (new_phase, wrapped). The env stores prev_phase=phase
1624
+ and self.phase=new_phase; reward/desync use the NEW phase (scores q_{t+1} vs ref(phi_{t+1})).
1625
+
1626
+ The `% 1.0` LOOPS the clip: at the wrap the tracking target jumps from ref(1-eps) back to ref(0).
1627
+ TRAINING INVARIANT: a clip that wraps MUST therefore be a LOOP ref (start pose ~= end pose) made by
1628
+ tools/reference/make_loopable_ref.py -- otherwise the target teleports here and the walk dies at the
1629
+ first seam. All env defaults + training runs use data/reference/cmu/<clip>_loop_<model>_ref.npz.
1630
+ A WHOLE clip (`loop=False` in its npz) is the other answer to the same seam: its phase is NOT wrapped
1631
+ (so `wrapped` is False for it), and the env ends the episode at the clip's last frame as a truncation
1632
+ (clip_end). See docs/training/concepts/loopable-refs.md."""
1633
+ secs = self.clip_secs[self._clip_of(phase)] if self.n_clips > 1 else self.ref_secs
1634
+ if not self.any_nonloop:
1635
+ new_phase = (phase + dt_ctrl / secs) % 1.0
1636
+ wrapped = new_phase < phase # crossed the clip seam (closed on a _loop_ ref)
1637
+ return new_phase, wrapped
1638
+ adv = phase + dt_ctrl / secs
1639
+ new_phase = torch.where(self.clip_loop[self._clip_of(phase)], adv % 1.0, adv)
1640
+ wrapped = new_phase < phase # only a loop clip's phase can decrease
1641
+ return new_phase, wrapped
1642
+
1643
+ # A whole clip ends when one more control step would carry the phase past its last frame. Float32 phase
1644
+ # round-off is ~5e-4 frames per ulp on a 7840-frame clip; this tolerance keeps an exactly representable
1645
+ # final frame from ending the episode one step early, and frame_idx's clamp absorbs the residual overshoot.
1646
+ _CLIP_END_TOL_FRAMES = 1e-3
1647
+
1648
+ def set_control_dt(self, dt_ctrl):
1649
+ """Bind the env's control step. A whole clip's RSI range and its end are counted in control steps.
1650
+
1651
+ Per clip: the latest start frame that still leaves RSI_END_MARGIN whole control steps before the
1652
+ clip-end truncation is f_max = (T - 1) - margin * df, with df = dt_ctrl / ref_dt reference frames per
1653
+ control step, i.e. phase_max = f_max / T (phase = frame / T, as on a loop). Started at f_max, an episode
1654
+ reaches the last frame after exactly `margin` steps and is truncated there. A loop clip's cap is 1.0.
1655
+ """
1656
+ assert dt_ctrl > 0.0, dt_ctrl
1657
+ self.dt_ctrl = float(dt_ctrl)
1658
+ if not self.any_nonloop:
1659
+ return
1660
+ df = self.dt_ctrl / self.ref_dt
1661
+ T = self.clip_T.to(torch.float64)
1662
+ f_max = (T - 1.0) - self.RSI_END_MARGIN * df
1663
+ short = [(self.clip_paths[c], int(self.clip_T[c])) for c in range(self.n_clips)
1664
+ if not bool(self.clip_loop[c]) and float(f_max[c]) < 0.0]
1665
+ assert not short, (
1666
+ f"whole clips shorter than DN_RSI_END_MARGIN={self.RSI_END_MARGIN} control steps "
1667
+ f"({df:.4g} frames each): {short}")
1668
+ self._rsi_phase_max = torch.where(self.clip_loop, torch.ones_like(T), f_max / T).to(torch.float32)
1669
+
1670
+ def _rsi_start_frames(self):
1671
+ """(n_clips,) float: the frames rsi() can start on in each clip, clip_T times the whole-clip cap
1672
+ (DN_CLIP_DRAW=frame weights the clip draw by it)."""
1673
+ T = self.clip_T.to(torch.float32)
1674
+ if not self.any_nonloop:
1675
+ return T
1676
+ assert self._rsi_phase_max is not None, (
1677
+ "a whole clip (loop=False) needs the control dt for its RSI range; the env must call "
1678
+ "ImitationTask.set_control_dt before the first reset")
1679
+ return T * self._rsi_phase_max
1680
+
1681
+ def clip_end(self, phase, dt_ctrl):
1682
+ """(n,) bool: the env tracks a WHOLE clip and its next control step would pass the clip's last frame.
1683
+
1684
+ Called on the POST-step phase, after this step's reward scored a target inside the clip. The env ends
1685
+ those episodes as a TRUNCATION (episode_end, the flag SAPO bootstraps V(s') on, like its time limit),
1686
+ not as a fall: the policy did nothing wrong, the reference simply has no frame beyond this one.
1687
+ Always False on a loop clip. Pure tensor ops, no host sync."""
1688
+ cid = self._clip_of(phase)
1689
+ T = self.clip_T[cid].to(phase.dtype)
1690
+ df = dt_ctrl / self.ref_dt
1691
+ return ~self.clip_loop[cid] & (phase * T + df > T - 1.0 + self._CLIP_END_TOL_FRAMES)
1692
+
1693
+ def desync_mask(self, q, phase, height, train_steps=0):
1694
+ """Imitation desync mask (pose OR root-height deviation). The env applies `& ~wrapped`, the
1695
+ `not eval_mode` gate, and ORs it into its own (model-specific) fall gate. When ET_ANNEAL, the
1696
+ thresholds tighten early and grow to IM_ET_* over ET_ANNEAL_STEPS (env passes its step counter)."""
1697
+ if self.IM_MIMIC: # MuscleMimic's deviation terminations, on what reward() measured this step
1698
+ return self.mimic_failed()
1699
+ et_pose, et_h = self.IM_ET_POSE, self.IM_ET_H
1700
+ q_ref, _ = self.ref_at(phase)
1701
+ pose_err = self.pose_error(q, q_ref)
1702
+ pose_desync = pose_err > et_pose
1703
+ height_desync = (height - q_ref[self.m.root_height]).abs() > et_h
1704
+ # TRUNK ET (opt-in): geodesic trunk-vs-ref deviation, cached by reward() so it costs no extra FK.
1705
+ # ORed into every return below -- with IM_ET_EE set this function returns on the EE branch, so a
1706
+ # trunk check placed only at the end would be dead code (as pose_desync already is in that config).
1707
+ torso_desync = torch.zeros_like(height_desync)
1708
+ return pose_desync | height_desync | torso_desync
1709
+
1710
+ # ------------------------------------------------------------------ MuscleMimic's MDP (DN_IM_MIMIC=1)
1711
+ # MimicReward with MuscleMimic's full-body weights (w_sum) and kernels (w_exp): fullbody/conf_fullbody.yaml and
1712
+ # musclemimic/core/reward/trajectory_based.py, use_mean_exp_reward=False, i.e. exp(-w_exp * mean squared error).
1713
+ # rvel's w_sum applies to its angular and to its linear half separately, as there. No effort term (the config's
1714
+ # action_rate_coeff and activation_energy_coeff are 0).
1715
+ MM_TERMS = (("qpos", 0.1, 10.0), ("qvel", 0.1, 2.0), ("root_pos", 0.1, 10.0), ("root_vel", 0.1, 10.0),
1716
+ ("rpos", 0.6, 100.0), ("rquat", 0.01, 10.0), ("rvel_rot", 0.1, 0.1), ("rvel_lin", 0.1, 0.1))
1717
+ MM_ET = (1.0, 1.0, 1.0) # MeanRelativeSiteDeviationWithRoot: mean site (m), root position (m), root angle (rad)
1718
+ MM_LOOKAHEAD, MM_STRIDE = 5, 20 # GoalTrajMimic: n_step_lookahead, n_step_stride (frames; 0.2 s at 100 Hz)
1719
+ MM_CHUNK = 32768 # reference frames per FK pass at build time (the corpus is ~5e5 frames)
1720
+
1721
+ def _mimic_build(self):
1722
+ from diffneusim.model.monitor import _quat_rotate
1723
+ assert abs(self.ref_dt - 0.01) < 1e-9, (
1724
+ f"MuscleMimic's goal strides 20 frames = 0.2 s at its 100 Hz; this corpus has dt {self.ref_dt}")
1725
+ # DN_MM_ET="site,root,angle" (m, m, rad; inf = that check off) overrides MM_ET, e.g. to score a checkpoint under
1726
+ # the MuscleMimic paper's Table 2 rule "0.5,0.5,inf" (opt-in; unset = MM_ET, the code's training thresholds)
1727
+ et = os.environ.get("DN_MM_ET")
1728
+ if et is not None:
1729
+ self.MM_ET = tuple(float(x) for x in et.split(","))
1730
+ assert len(self.MM_ET) == 3 and min(self.MM_ET) > 0.0, f"DN_MM_ET={et!r} needs three positive thresholds"
1731
+ path = str(_ROOT / "data/reference/musclemimic/myofullbody_mimic_sites.json")
1732
+ spec = json.loads(pathlib.Path(path).read_text())["sites"]
1733
+ names = [b["name"] for b in self.monitor.bodies]
1734
+ last = {n: i for i, n in enumerate(names)} # a split stack's LAST body = the frame after all of its joints
1735
+ self.mm_site_names = [s["site"] for s in spec]
1736
+ assert self.mm_site_names[0] == "pelvis_mimic", "the first site is MuscleMimic's main (root-relative) site"
1737
+ self._mm_body = [last[s["body"]] for s in spec]
1738
+ dev = self.device
1739
+ self._mm_spos = torch.tensor([s["pos"] for s in spec], dtype=torch.float32, device=dev).t()[:, :, None] # (3,S,1)
1740
+ self._mm_squat = torch.tensor([s["quat"] for s in spec], dtype=torch.float32, device=dev).t()[:, :, None] # (4,S,1)
1741
+ free = [i for i, b in enumerate(self.monitor.bodies) if b.get("joint") in ("free", "freejoint")]
1742
+ assert len(free) == 1, free
1743
+ fb = self._mm_root_body = free[0]
1744
+ qa, va = int(self.monitor.bodies[fb]["qadr"]), int(self.monitor.bodies[fb]["vadr"])
1745
+ self._mm_root_va = va
1746
+ quat_dims = {i for (s, L) in self.m.quat_blocks for i in range(s, s + L)}
1747
+ self._mm_q_scalar = torch.tensor([i for i in range(self.m.nq) if i not in quat_dims], dtype=torch.long, device=dev)
1748
+ self._mm_qd_rest = torch.tensor([i for i in range(self.m.nv) if not va <= i < va + 6], dtype=torch.long, device=dev)
1749
+ self._mm_tw_bodies = sorted(set(self._mm_body) | {fb})
1750
+ self.mm_max_step_reward = float(sum(w for _, w, _ in self.MM_TERMS))
1751
+ # per-frame reference quantities, in FK chunks over the concatenated corpus
1752
+ out = {k: [] for k in ("rpos", "rrot", "ang", "lin", "root_p", "root_q", "root_vw")}
1753
+ with torch.no_grad():
1754
+ for a in range(0, self.ref_T_total, self.MM_CHUNK):
1755
+ Q = self.ref_q[a:a + self.MM_CHUNK].t().contiguous()
1756
+ QD = self.ref_qd[a:a + self.MM_CHUNK].t().contiguous()
1757
+ pos, quat = self.monitor.body_poses(Q)
1758
+ tw = self.monitor.body_twists_from_poses(pos, quat, Q, QD, self._mm_tw_bodies)
1759
+ rpos, rrot, ang, lin = self._mm_sites(pos, quat, tw)
1760
+ for k, v in (("rpos", rpos), ("rrot", rrot), ("ang", ang), ("lin", lin), ("root_p", pos[fb]),
1761
+ ("root_q", quat[fb]), ("root_vw", _quat_rotate(quat[fb], QD[va + 3:va + 6]))):
1762
+ out[k].append(v)
1763
+ self._mm_ref = {k: torch.cat(v, -1).contiguous() for k, v in out.items()} # (..., T_total)
1764
+ # GoalTrajMimic's concise lookahead reads, per frame: the site rpos (world frame), the root position and the
1765
+ # free joint's qvel in MuJoCo's convention [v world, w body]
1766
+ R = self._mm_ref
1767
+ self._mm_goal_rpos = R["rpos"].permute(2, 0, 1).reshape(self.ref_T_total, -1).contiguous() # (T, 3(S-1))
1768
+ self._mm_goal_root_p = R["root_p"].t().contiguous() # (T, 3)
1769
+ self._mm_goal_root_qvel = torch.cat([R["root_vw"], self.ref_qd[:, va:va + 3].t()], 0).t().contiguous() # (T, 6)
1770
+ self._mm_goal_steps = torch.arange(1, self.MM_LOOKAHEAD, device=dev) * self.MM_STRIDE # (L-1,) frames ahead
1771
+ print(f"[imitation] MuscleMimic MDP: {len(spec)} mimic sites, max step reward {self.mm_max_step_reward:.2f}, "
1772
+ f"goal dim {self.mimic_goal_dim()}", flush=True)
1773
+
1774
+ def _mm_sites(self, pos, quat, tw):
1775
+ """MuscleMimic's calculate_relative_site_quantities on our bodies, quirks included (loco_mujoco/core/utils/math.py):
1776
+ rpos = p_s - p_main in the WORLD frame; rrot = log(R_main^T R_s); rvel = [R_rel^T w_s - w_main, R_main (v_main - v_s)]
1777
+ with R_rel = R_main^T R_s and every velocity a world one (MuscleMimic's linear part applies R_main, not its
1778
+ transpose). Returns four (S-1, 3, n). The sites are stacked along a second axis and every quaternion op runs ONCE
1779
+ on (k, S*n): one dispatch per op instead of one per site (the hot reward path is launch-bound)."""
1780
+ from diffneusim.model.monitor import _quat_mul, _quat_rotate
1781
+ B = self._mm_body
1782
+ S = len(B)
1783
+ n = pos[B[0]].shape[-1]
1784
+ pb = torch.stack([pos[b] for b in B], 1) # (3,S,n)
1785
+ qb = torch.stack([quat[b] for b in B], 1) # (4,S,n)
1786
+ vb = torch.stack([tw[b][0] for b in B], 1)
1787
+ W = torch.stack([tw[b][1] for b in B], 1)
1788
+
1789
+ def flat(x):
1790
+ return x.reshape(x.shape[0], -1)
1791
+ off = _quat_rotate(flat(qb), flat(self._mm_spos.expand(3, S, n))).reshape(3, S, n)
1792
+ P = pb + off
1793
+ Qs = _quat_mul(flat(qb), flat(self._mm_squat.expand(4, S, n))).reshape(4, S, n)
1794
+ V = vb + torch.cross(W, off, dim=0)
1795
+ q0 = Qs[:, :1].expand(4, S - 1, n)
1796
+ qrel = _quat_mul(flat(_tq_conj(q0)), flat(Qs[:, 1:])) # (4,(S-1)n)
1797
+ rpos = P[:, 1:] - P[:, :1]
1798
+ rrot = _tq_log(qrel).reshape(3, S - 1, n)
1799
+ ang = _quat_rotate(_tq_conj(qrel), flat(W[:, 1:])).reshape(3, S - 1, n) - W[:, :1]
1800
+ lin = _quat_rotate(flat(q0), flat(V[:, :1] - V[:, 1:])).reshape(3, S - 1, n)
1801
+ return tuple(x.permute(1, 0, 2) for x in (rpos, rrot, ang, lin))
1802
+
1803
+ def _mimic_reward(self, q, qd, q_ref, qd_ref, pos, quat, i0, i1, wf):
1804
+ """MimicReward (see MM_TERMS) at the post-step state, differentiable in q and qd. Caches the three deviation
1805
+ measures mimic_failed() terminates on."""
1806
+ core = self._mimic_core
1807
+ if self._mm_compile and torch.is_grad_enabled() and (q.requires_grad or qd.requires_grad):
1808
+ key = (int(q.shape[1]), q.dtype, q.device.type)
1809
+ core = self._mm_compiled.get(key)
1810
+ if core is None:
1811
+ core = self._mm_compiled[key] = torch.compile(self._mimic_core, fullgraph=True, dynamic=False)
1812
+ r, e, d_rpos, root_p_ref, root_q_ref = core(q, qd, q_ref, qd_ref, pos, quat, i0, i1, wf)
1813
+ fb = self._mm_root_body
1814
+ with torch.no_grad():
1815
+ self._mm_last = (d_rpos.norm(dim=1).mean(0), (pos[fb] - root_p_ref).norm(dim=0), _tq_angle(quat[fb], root_q_ref))
1816
+ self._mm_last_terms = {name: torch.exp(-k * e[name]).detach() for name, _, k in self.MM_TERMS}
1817
+ return r
1818
+
1819
+ def _mimic_core(self, q, qd, q_ref, qd_ref, pos, quat, i0, i1, wf):
1820
+ """The differentiable part of _mimic_reward: (r, the eight errors by term, d_rpos, and the root position and
1821
+ orientation targets the deviation measures read). Runs eager, or compiled under DN_MIMIC_COMPILE=1, where
1822
+ the twists are traced inline (their own compiled callable is not nested in this trace)."""
1823
+ from diffneusim.model.monitor import _quat_rotate
1824
+ R = self._mm_ref
1825
+
1826
+ def lerp(A):
1827
+ return A[..., i0] * (1.0 - wf) + A[..., i1] * wf
1828
+ fb, va = self._mm_root_body, self._mm_root_va
1829
+ # qpos: every scalar coordinate (root xyz, hinges) squared, mean; plus the mean geodesic angle of the quaternions
1830
+ e_qpos = ((q[self._mm_q_scalar] - q_ref[self._mm_q_scalar]) ** 2).mean(0)
1831
+ e_qpos = e_qpos + torch.stack([_tq_angle(q[s:s + L], q_ref[s:s + L]) for (s, L) in self.m.quat_blocks], 0).mean(0)
1832
+ # qvel: the free joint in MuJoCo's [v world, w body] convention, then every other dof rate
1833
+ root_q_ref = lerp(R["root_q"])
1834
+ root_q_ref = root_q_ref / root_q_ref.norm(dim=0, keepdim=True)
1835
+ v_w = _quat_rotate(quat[fb], qd[va + 3:va + 6])
1836
+ qv = torch.cat([v_w, qd[va:va + 3], qd[self._mm_qd_rest]], 0)
1837
+ qv_ref = torch.cat([lerp(R["root_vw"]), qd_ref[va:va + 3], qd_ref[self._mm_qd_rest]], 0)
1838
+ e_qvel = ((qv - qv_ref) ** 2).mean(0)
1839
+ root_p_ref = lerp(R["root_p"])
1840
+ e_root_pos = ((pos[fb] - root_p_ref) ** 2).mean(0)
1841
+ # root_vel: [R^T v world, w body] = the free joint's own [v body, w body]
1842
+ e_root_vel = ((qd[va:va + 6] - qd_ref[va:va + 6]) ** 2).mean(0)
1843
+ twists = (self.monitor._body_twists_from_poses_eager if self._mm_compile else self.monitor.body_twists_from_poses)
1844
+ tw = twists(pos, quat, q, qd, self._mm_tw_bodies)
1845
+ rpos, rrot, ang, lin = self._mm_sites(pos, quat, tw)
1846
+ d_rpos = rpos - lerp(R["rpos"])
1847
+ e = {"qpos": e_qpos, "qvel": e_qvel, "root_pos": e_root_pos, "root_vel": e_root_vel,
1848
+ "rpos": (d_rpos ** 2).mean((0, 1)), "rquat": ((rrot - lerp(R["rrot"])) ** 2).mean((0, 1)),
1849
+ "rvel_rot": ((ang - lerp(R["ang"])) ** 2).mean((0, 1)), "rvel_lin": ((lin - lerp(R["lin"])) ** 2).mean((0, 1))}
1850
+ r = sum(w * torch.exp(-k * e[name]) for name, w, k in self.MM_TERMS)
1851
+ return r, e, d_rpos, root_p_ref, root_q_ref
1852
+
1853
+ def mimic_failed(self):
1854
+ """(n,) bool: MuscleMimic's MeanRelativeSiteDeviationWithRoot on the state reward() just scored."""
1855
+ assert getattr(self, "_mm_last", None) is not None, "mimic_failed reads what reward() measured; call reward first"
1856
+ site, root, ang = self._mm_last
1857
+ t_site, t_root, t_ang = self.MM_ET
1858
+ return (site > t_site) | (root > t_root) | (ang > t_ang)
1859
+
1860
+ def mimic_goal_dim(self):
1861
+ n = self._mm_goal_rpos.shape[1]
1862
+ return n + (self.MM_LOOKAHEAD - 1) * (3 + 6 + n) + 1
1863
+
1864
+ def mimic_goal_obs(self, phase):
1865
+ """GoalTrajMimic's concise lookahead (use_concise_lookahead, enable_motion_phase), (n, mimic_goal_dim()): the
1866
+ reference site rpos at the current frame, then for 4 frames 0.2 s apart (clamped at the clip end) the root
1867
+ position and root-qvel deltas from the current frame and that frame's site rpos, then the motion phase. Frames
1868
+ are ROUNDED from the phase: control and reference share the 100 Hz clock, so a floor would lag one frame on
1869
+ float round-off."""
1870
+ cid = self._clip_of(phase)
1871
+ T = self.clip_T[cid]
1872
+ k = torch.clamp(torch.round(phase * T.to(phase.dtype)).long(), min=torch.zeros_like(T), max=T - 1)
1873
+ f = self.clip_start[cid] + k
1874
+ end = self.clip_start[cid] + T - 1
1875
+ G, RP, RV = self._mm_goal_rpos, self._mm_goal_root_p, self._mm_goal_root_qvel
1876
+ # the lookahead frames as one (n, L-1) index: each block is [RP[g] - RP[f], RV[g] - RV[f], G[g]] for g = frame j,
1877
+ # laid out j-major exactly as a loop over j would concatenate them (gathers and one subtraction each: exact)
1878
+ g = torch.minimum(f[:, None] + self._mm_goal_steps, end[:, None])
1879
+ look = torch.cat([RP[g] - RP[f][:, None], RV[g] - RV[f][:, None], G[g]], -1).reshape(f.shape[0], -1)
1880
+ return torch.cat([G[f], look, (k.to(phase.dtype) / T.to(phase.dtype)).unsqueeze(-1)], -1)
1881
+
1882
+ def phase_obs(self, phase):
1883
+ """The opt-in DeepMimic phase clock (sin,cos of 2*pi*phi), or None when disabled."""
1884
+ return None
1885
+ ph = (2.0 * 3.141592653589793) * phase
1886
+ return torch.cat([torch.sin(ph)[:, None], torch.cos(ph)[:, None]], dim=1)
1887
+
1888
+ def cond_obs(self, n):
1889
+ """Per-env task conditioning (v_fwd, cadence) of the clip that env is tracking, normalised, or None.
1890
+
1891
+ This is what makes a multi-clip policy a CONTROLLER rather than an averager: without it the policy
1892
+ sees the same observation for a slow walk and a run and can only learn their mean. With it, the two
1893
+ scalars say which locomotion is being asked for, and at eval they can be set to ask for a speed the
1894
+ corpus never contained exactly."""
1895
+ return None
1896
+ cid = self.clip_id if self.clip_id.numel() == n else self.clip_id[:1].expand(n)
1897
+ raw = torch.stack([self.clip_vfwd[cid], self.clip_cadence[cid]], dim=1) # (n,2)
1898
+ return (raw - self.cond_mean) / self.cond_std
1899
+
1900
+ def _effort(self, r, a_mean, train_steps):
1901
+ """The effort price, shared by every reward version. DN_IM_ACT_PEN_VOL > 0 prices it in the TASKWALK
1902
+ currency instead -- the volume-weighted L1 mean sum V_i a_i / sum V_i, V_i = F_max_i l_opt_i (task_walk_reward's
1903
+ `_muscle_mass` up to a constant) -- and REPLACES the L2 forms; else MEAN replaces the sum form, as before."""
1904
+ r = r + self.IM_ACT_PEN * (a_mean ** 2).t().sum(dim=1)
1905
+ return r
1906
+
1907
+ def act_pen_scale(self, train_steps):
1908
+ """Anneal factor for the mean-form effort price (1.0 when no anneal is configured)."""
1909
+ return 1.0
1910
+ return min(1.0, max(0, int(train_steps)) / self.IM_ACT_PEN_ANNEAL_STEPS)
1911
+
1912
+ def reward(self, q, qd, a_mean, phase, prev_phase, h_prev, x_prev, upright, dt_ctrl,
1913
+ train_steps=0, foot_grf_z=None, foot_contact_f=None, q_prev=None):
1914
+ """DeepMimic tracking reward: w_p*r_pose + w_v*r_speed_track + w_e*r_endeff + w_c*r_com - act cost, each
1915
+ r_* = exp(-alpha*sq_err). Feet (root-relative) + COM via differentiable FK; COM tracks world-z
1916
+ height only. Optional upright/anti-sink/task terms (default off). Differentiable in q,qd (SHAC/RPO
1917
+ pathwise) -- do NOT detach/clone the inputs. Mirrors the mixin op-for-op (addition order).
1918
+ DN_IM_RECON=mvae returns MuscleVAE's reconstruction objective instead (`_recon_reward`; needs q_prev)."""
1919
+ if self.IM_RECON:
1920
+ return self._recon_reward(q, q_prev, a_mean, phase, prev_phase, dt_ctrl, train_steps)
1921
+ m = self.m
1922
+ if self.IM_MIMIC: # MuscleMimic's MimicReward: its own return path, reading none of the DeepMimic errors below
1923
+ i0, i1, wf = self.frame_idx(phase)
1924
+ q_ref, qd_ref = self._ref_at_frames(i0, i1, wf)
1925
+ pos, quat, _com = self.monitor.body_poses_subset(q, self._fk_bodies, self._fk_need_com)
1926
+ return self._mimic_reward(q, qd, q_ref, qd_ref, pos, quat, i0, i1, wf)
1927
+ q_ref, qd_ref = self.ref_at(phase) # (nq,n), (nv,n)
1928
+ e_pose = self.pose_error(q, q_ref, w=self._pose_w, scale=self._pose_scale) # w/scale None => raw
1929
+ sq_vel = (qd - qd_ref) ** 2
1930
+ e_vel = sq_vel.sum(0)
1931
+ # differentiable FK (current state only), REDUCED to the frames this reward config reads:
1932
+ # welded subtrees are pre-composed and the COM is regrouped by composite body -- same values and
1933
+ # same gradient as the full 156-body walk, ~7x fewer kernel launches (the training bottleneck).
1934
+ pos, quat, com = self.monitor.body_poses_subset(q, self._fk_bodies, self._fk_need_com)
1935
+ n = q.shape[1]
1936
+ # reference FK targets: gather+lerp the per-frame precompute by phase (no second 156-body FK). Same
1937
+ # phase indexing as ref_at (cyclic linear interp), but on the precomputed world-pose targets.
1938
+ i0, i1, wf = self.frame_idx(phase) # clip-aware GLOBAL indices; see frame_idx
1939
+ def _lerp(A): # A:(...,T) -> (...,n): gather frames i0,i1 on the last axis and linearly blend
1940
+ return A[..., i0] * (1.0 - wf) + A[..., i1] * wf
1941
+ root = pos[m.root_body] # (3,n)
1942
+ ee_rel_r = [_lerp(e) for e in self._ref_ee] # per foot, root-relative (3,n)
1943
+ ee_errs = torch.stack([(((pos[b] - root) - ee_rel_r[k]) ** 2).sum(0)
1944
+ for k, b in enumerate(m.feet)], 0) # (n_ee, n) per-EE squared error
1945
+ e_ee = ee_errs.sum(0) # reward term: sum over EEs (unchanged)
1946
+
1947
+ wc = self.IM_WC # drop the inaccurate absolute-height COM target
1948
+ com_z_r = _lerp(self._ref_com_z) # (n,)
1949
+ e_com = (com[2] - com_z_r) ** 2 # height component only (world z-up)
1950
+ r_pose = torch.exp(-self.IM_AP * e_pose) # lumped exp-of-sum (coupled; bit-parity default)
1951
+ r = (self.IM_WP * r_pose
1952
+ + self.IM_WV * torch.exp(-self.IM_AV * e_vel)
1953
+ + self.IM_WE * torch.exp(-self.IM_AE * e_ee))
1954
+ r = r + wc * torch.exp(-self.IM_AC * e_com)
1955
+ return self._effort(r, a_mean, train_steps)
1956
+
1957
+ def _recon_reward(self, q, q_prev, a_mean, phase, prev_phase, dt_ctrl, train_steps):
1958
+ """r = 1 - pose_err / 20 - effort: MuscleVAE's per-step reconstruction loss (mvae_recon.py) on the post-step state against
1959
+ ref(phi_{t+1}), its velocities a backward difference over this control step as their `resample` takes them.
1960
+
1961
+ THE FORM. Their policy minimises sum_t 0.95^t (pose_err_t + beta KL_t + l1 |a|_1 + l2 |a|^2) through a world model; SAPO
1962
+ maximises sum_t gamma^t (r_t - beta' KL_t) through the engine, so r_t = -pose_err_t / 20 - effort / 20 hands the actor
1963
+ their loss's gradient, scaled by 1/20, which Adam does not see (the KL weight and the effort prices then carry the same
1964
+ 1/20: beta' = beta / 20, DN_IM_ACT_PEN(_L1) = -l2 / 20, -l1 / 20). The constant 1 is the zeroth-order term of
1965
+ their own reward of this error, exp(-pose_err / 20) (`cal_rwd`): it changes no gradient inside a window, and it keeps a
1966
+ surviving step worth more than termination wherever pose_err < 20 (lumb3ne's own readout tracks at 2.3 on walk1 and 4.1
1967
+ on run1 per 20 Hz step; the reference against itself lagged 0.5 s reads 7 and 12). Linear, not exp: their loss does not
1968
+ saturate, and 1 - x / 20 is within 3% of exp(-x / 20) below x = 5.
1969
+
1970
+ q_prev is the pre-step state IN THE GRAPH (the env's q before this step's substeps): a detached previous sample would
1971
+ over-count the velocity terms' gradient under BPTT (docs/logs/bug-grad-audits.md 2026-09-28). The EE desync ET keeps
1972
+ its input, from the same FK."""
1973
+ assert q_prev is not None and prev_phase is not None, "DN_IM_RECON needs the env's pre-step q and phase"
1974
+ m = self.m
1975
+ pos, quat, _ = self.monitor.body_poses_subset(q, self._fk_bodies, False)
1976
+ pos0, quat0, _ = self.monitor.body_poses_subset(q_prev, self._rc_idx, False)
1977
+ P, Q = _R.com_poses(pos, quat, self._rc_idx, self._rc_com)
1978
+ P0, Q0 = _R.com_poses(pos0, quat0, self._rc_idx, self._rc_com)
1979
+ i0, i1, wf = self.frame_idx(phase)
1980
+ j0, j1, wg = self.frame_idx(prev_phase)
1981
+ A, A0 = self._ref_rc_P, self._ref_rc_Q
1982
+ Pr = A[..., i0] * (1.0 - wf) + A[..., i1] * wf
1983
+ Pr0 = A[..., j0] * (1.0 - wg) + A[..., j1] * wg
1984
+ Qr, Qr0 = _R.nlerp(A0[..., i0], A0[..., i1], wf), _R.nlerp(A0[..., j0], A0[..., j1], wg)
1985
+ t = _R.l1_terms(_R.features(P, Q, P0, Q0, dt_ctrl), _R.features(Pr, Qr, Pr0, Qr0, dt_ctrl), dt_ctrl)
1986
+ L = _R.weighted(t)
1987
+ with torch.no_grad(): # per-term means for the training log, summed on the device (pop_recon_stats reads them)
1988
+ s = torch.stack([(_R.MVAE_WEIGHT[k] * t[k]).mean() for k in _R.TERMS] + [L.mean()])
1989
+ self._rc_sum = s if self._rc_sum is None else self._rc_sum + s
1990
+ self._rc_n += 1
1991
+ return self._effort(1.0 - L / _R.MVAE_RWD_SCALE, a_mean, train_steps)
1992
+
1993
+ def head_height_error(self, q, phase):
1994
+ """|head height - the reference's| per env (n,): MuscleVAE's termination quantity (muscle_env.py cal_done: the head body's
1995
+ world height against the target frame's), on the head's centre of mass as their state's body position. No gradient."""
1996
+ h = self._head_body
1997
+ pos, quat, _ = self.monitor.body_poses_subset(q, [h], False)
1998
+ z = (pos[h] + _R._qrot(quat[h], self._head_com.to(q.dtype).expand(3, q.shape[1])))[2]
1999
+ i0, i1, wf = self.frame_idx(phase)
2000
+ return (z - (self._ref_head_z[i0] * (1.0 - wf) + self._ref_head_z[i1] * wf)).abs()
2001
+
2002
+ def pop_recon_stats(self):
2003
+ """Mean weighted pose_err terms (pos, rot, vel, avel, height, up_dir) and their sum per env-step since the last call,
2004
+ then reset (one host read per call)."""
2005
+ n = max(self._rc_n, 1)
2006
+ v = (self._rc_sum / n).tolist() if self._rc_sum is not None else [0.0] * (len(_R.TERMS) + 1)
2007
+ self._rc_sum, self._rc_n = None, 0
2008
+ return dict(zip(list(_R.TERMS) + ["L"], v))
2009
+
2010
+ def _v2_reward(self, q, q_ref, qd, qd_ref, pos, quat, com, root, _lerp, i0, i1, wf,
2011
+ a_mean, train_steps):
2012
+ """r = sum_g W_g * exp(-alpha_g * E_g) - effort, E_g = sum_j c_j * e_j / s_j (#44).
2013
+
2014
+ The effort penalty is carried over UNCHANGED from v1: it is not a tracking term, it has no
2015
+ reference to be dimensionless against, and its mean form is already model-size invariant.
2016
+ """
2017
+ e = self._v2_components(q, q_ref, qd, qd_ref, pos, quat, com, root, _lerp, i0, i1, wf)
2018
+ E, r = {}, None
2019
+ for g in self._v2.active:
2020
+ E[g] = self._v2.group_error(g, e[g])
2021
+ term = self._v2.W[g] * torch.exp(-self._v2.alpha(g) * E[g])
2022
+ r = term if r is None else r + term
2023
+ with torch.no_grad(): # adaptation rides along with the rollout, no separate diagnostic pass
2024
+ self._v2.observe({g: e[g].detach() for g in self._v2.active},
2025
+ {g: E[g].detach() for g in self._v2.active})
2026
+ self._v2_last_E = {g: E[g].detach() for g in self._v2.active}
2027
+ return self._effort(r, a_mean, train_steps)