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.
- diffneusim/__init__.py +1 -0
- diffneusim/_cache.py +42 -0
- diffneusim/_paths.py +5 -0
- diffneusim/bindings/rew14_ext.cu +115 -0
- diffneusim/bindings/soft14_capi.cpp +443 -0
- diffneusim/bindings/soft14_engine_ext.cu +596 -0
- diffneusim/bindings/soft_capi.cpp +782 -0
- diffneusim/bindings/soft_engine_ext.cu +495 -0
- diffneusim/core/cpu_engine/build.sh +40 -0
- diffneusim/core/cpu_engine/fiber/cuda_runtime.h +445 -0
- diffneusim/core/cpu_engine/x14_cpu.cpp +283 -0
- diffneusim/core/diff/dual.h +126 -0
- diffneusim/core/include/diffneusim/macros.h +35 -0
- diffneusim/core/kin/kinematic_tree.h +273 -0
- diffneusim/core/math/so3.h +182 -0
- diffneusim/core/soft/adj/out_adj.h +102 -0
- diffneusim/core/soft/adj/rnea_adj.h +425 -0
- diffneusim/core/soft/adj/rows_adj.h +439 -0
- diffneusim/core/soft/adj/rows_functor.h +89 -0
- diffneusim/core/soft/adj/rows_lanes.h +443 -0
- diffneusim/core/soft/adj/shell_adj.h +243 -0
- diffneusim/core/soft/adj/tree_adj.h +356 -0
- diffneusim/core/soft/collide.h +183 -0
- diffneusim/core/soft/gpu/adj14.cuh +233 -0
- diffneusim/core/soft/gpu/adj14_mus.cuh +98 -0
- diffneusim/core/soft/gpu/adj_shell.cuh +50 -0
- diffneusim/core/soft/gpu/adj_tab.cuh +49 -0
- diffneusim/core/soft/gpu/body14.cuh +47 -0
- diffneusim/core/soft/gpu/chol_rn.cuh +458 -0
- diffneusim/core/soft/gpu/chol_small.cuh +123 -0
- diffneusim/core/soft/gpu/chol_split.cuh +193 -0
- diffneusim/core/soft/gpu/engine_launch.cuh +263 -0
- diffneusim/core/soft/gpu/fk_rn.cuh +109 -0
- diffneusim/core/soft/gpu/generated/body_019e20820f86_mmfloor.cuh +28 -0
- diffneusim/core/soft/gpu/generated/body_62f77a4bb16b_mmfloor.cuh +52 -0
- diffneusim/core/soft/gpu/generated/body_77dbb7213f26_mmfloor_rampsb3l_n6t12.cuh +28 -0
- diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rampsb3l_n6t12.cuh +28 -0
- diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsd05_n6t12.cuh +28 -0
- diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsdef_n6t12.cuh +28 -0
- diffneusim/core/soft/gpu/generated/body_8989b60e4486_mmfloor_rhlsmjd_n6t12.cuh +28 -0
- diffneusim/core/soft/gpu/generated/body_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +52 -0
- diffneusim/core/soft/gpu/generated/body_a944653edd64_mmfloor.cuh +25 -0
- diffneusim/core/soft/gpu/generated/body_a944653edd64_mmfloor_rampsb3l_n6t12.cuh +25 -0
- diffneusim/core/soft/gpu/generated/g1_soft_5db44fd45286.cuh +74 -0
- diffneusim/core/soft/gpu/generated/split_62f77a4bb16b_mmfloor.cuh +18 -0
- diffneusim/core/soft/gpu/generated/split_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +18 -0
- diffneusim/core/soft/gpu/generated/x14_soft_019e20820f86_mmfloor.cuh +123 -0
- diffneusim/core/soft/gpu/generated/x14_soft_62f77a4bb16b_mmfloor.cuh +129 -0
- diffneusim/core/soft/gpu/generated/x14_soft_77dbb7213f26_mmfloor_rampsb3l_n6t12.cuh +123 -0
- diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rampsb3l_n6t12.cuh +123 -0
- diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsd05_n6t12.cuh +123 -0
- diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsdef_n6t12.cuh +123 -0
- diffneusim/core/soft/gpu/generated/x14_soft_8989b60e4486_mmfloor_rhlsmjd_n6t12.cuh +123 -0
- diffneusim/core/soft/gpu/generated/x14_soft_a1e8b196b2cd_mmfloor_rampsb3l_n6t12.cuh +129 -0
- diffneusim/core/soft/gpu/generated/x14_soft_a944653edd64_mmfloor.cuh +123 -0
- diffneusim/core/soft/gpu/generated/x14_soft_a944653edd64_mmfloor_rampsb3l_n6t12.cuh +123 -0
- diffneusim/core/soft/gpu/k_mus.cuh +1038 -0
- diffneusim/core/soft/gpu/k_mus_host.cuh +377 -0
- diffneusim/core/soft/gpu/k_pre.cuh +52 -0
- diffneusim/core/soft/gpu/kernel_p.cuh +490 -0
- diffneusim/core/soft/gpu/kp14.cuh +465 -0
- diffneusim/core/soft/gpu/l2v2.cuh +367 -0
- diffneusim/core/soft/gpu/l2x14.cuh +319 -0
- diffneusim/core/soft/gpu/l3.cuh +1483 -0
- diffneusim/core/soft/gpu/model_view.cuh +48 -0
- diffneusim/core/soft/gpu/mus_case_fits.h +15 -0
- diffneusim/core/soft/gpu/mus_classes.h +182 -0
- diffneusim/core/soft/gpu/mus_row_cf.h +44 -0
- diffneusim/core/soft/gpu/rew14.cuh +177 -0
- diffneusim/core/soft/gpu/rows_ctab.cuh +44 -0
- diffneusim/core/soft/gpu/tree_m.cuh +247 -0
- diffneusim/core/soft/gpu/x14_engine_kernels.cuh +260 -0
- diffneusim/core/soft/gpu/x14_rowcf.h +14 -0
- diffneusim/core/soft/hand.h +124 -0
- diffneusim/core/soft/impedance.h +115 -0
- diffneusim/core/soft/jvp.h +202 -0
- diffneusim/core/soft/kin.h +250 -0
- diffneusim/core/soft/muscle.h +1208 -0
- diffneusim/core/soft/newton.h +371 -0
- diffneusim/core/soft/rows.h +176 -0
- diffneusim/core/soft/step.h +188 -0
- diffneusim/core/soft/tape.h +313 -0
- diffneusim/core/soft/x14/collide14.h +69 -0
- diffneusim/core/soft/x14/jvp14.h +182 -0
- diffneusim/core/soft/x14/law14.h +453 -0
- diffneusim/core/soft/x14adj/collide14_adj.h +134 -0
- diffneusim/core/soft/x14adj/passive14_adj.h +162 -0
- diffneusim/core/soft/x14adj/reward14.h +484 -0
- diffneusim/core/soft/x14adj/rows14_adj.h +400 -0
- diffneusim/core/soft/x14adj/scan14.h +349 -0
- diffneusim/core/soft/x14adj/shell14_adj.h +122 -0
- diffneusim/core/soft/x14adj/sweep14.h +255 -0
- diffneusim/core/soft/x14adj/tree14_adj.h +500 -0
- diffneusim/core/soft/x14adj/x14adj_common.h +96 -0
- diffneusim/data/mirror/H1622v2k_geyer_hfdeq.npz +0 -0
- diffneusim/data/mirror/H1622v2k_hfd.npz +0 -0
- diffneusim/data/mirror/H1622v2k_millard_hfdeq.npz +0 -0
- diffneusim/data/mirror/fullbody_contact.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_p2str.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_p2str_rigid.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_calf2_pe.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfix.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfixlegs01.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01legs.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_jd01lumbar.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_lumbfix.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_lumbfixlegs01.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1a.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n2.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_rom23.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_hinge.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1a.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n2.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_rom23.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_fusedhand_lspine_girdle_osimeq.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_lspine_girdle_millard.npz +0 -0
- diffneusim/data/mirror/fullbody_contact_spinecoupled_lspine_girdle_osimeq.npz +0 -0
- diffneusim/data/mirror/myoleg26_3d_compound_g14eq.npz +0 -0
- diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq.npz +0 -0
- diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose.npz +0 -0
- diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin.npz +0 -0
- diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30.npz +0 -0
- diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30.npz +0 -0
- diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30_luispe.npz +0 -0
- diffneusim/data/mirror/myoleg26_3d_kneeexp_g14eq_trunkpose_spin_ank30_hip30_trunk0701.npz +0 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_axfix.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_axfixlegs01.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01legs.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_jd01lumbar.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_lumbfix.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_lumbfixlegs01.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_n1.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_n1a.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_n2.json +91 -0
- diffneusim/data/muscle_fit/wang_mass_volume_14t_rom23.json +91 -0
- diffneusim/data/reference/musclemimic/myofullbody_mimic_sites.json +261 -0
- diffneusim/data/reference/pose3/pose3_scone.json +305 -0
- diffneusim/data/reference/pose3/pose3_scone.txt +3 -0
- diffneusim/data/reference/pose3/pose3_scone_gait.npz +0 -0
- diffneusim/data/reference/pose3/pose3_scone_mirror.npz +0 -0
- diffneusim/data/reference/pose3/pose3_scone_stand.npz +0 -0
- diffneusim/data/reference/x016run/MD5SUMS +241 -0
- diffneusim/data/reference/x016run/x016run_states.txt +240 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s0_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s0_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s0_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s0_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s0_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s0_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s0_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s0_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s1_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s1_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s1_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s1_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s1_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s1_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s1_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s1_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s2_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s2_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s2_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s2_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s2_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s2_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s2_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s2_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s3_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s3_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s3_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s3_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s3_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s3_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s3_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s3_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s4_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s4_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s4_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s4_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s4_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s4_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s4_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s4_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s5_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s5_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s5_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s5_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s5_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s5_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s5_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s5_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s6_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s6_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s6_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s6_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s6_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s6_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s6_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s6_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s7_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s7_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s7_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s7_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s7_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s7_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s7_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p00_s7_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s0_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s0_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s0_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s0_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s0_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s0_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s0_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s0_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s1_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s1_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s1_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s1_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s1_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s1_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s1_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s1_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s2_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s2_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s2_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s2_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s2_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s2_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s2_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s2_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s3_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s3_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s3_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s3_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s3_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s3_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s3_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s3_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s4_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s4_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s4_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s4_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s4_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s4_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s4_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s4_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s5_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s5_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s5_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s5_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s5_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s5_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s5_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s5_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s6_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s6_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s6_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s6_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s6_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s6_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s6_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s6_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s7_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s7_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s7_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s7_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s7_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s7_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s7_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p25_s7_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s0_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s0_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s0_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s0_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s0_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s0_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s0_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s0_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s1_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s1_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s1_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s1_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s1_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s1_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s1_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s1_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s2_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s2_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s2_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s2_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s2_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s2_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s2_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s2_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s3_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s3_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s3_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s3_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s3_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s3_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s3_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s3_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s5_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s5_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s5_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s5_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s5_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s5_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s5_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s5_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s6_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s6_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s6_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s6_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s6_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s6_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s6_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s6_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s7_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s7_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s7_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s7_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s7_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s7_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s7_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p50_s7_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s0_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s0_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s0_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s0_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s0_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s0_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s0_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s0_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s1_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s1_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s1_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s1_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s1_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s1_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s1_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s1_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s2_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s2_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s2_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s2_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s2_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s2_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s2_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s2_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s3_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s3_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s3_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s3_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s3_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s3_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s3_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s3_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s5_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s5_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s5_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s5_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s5_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s5_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s5_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s5_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s6_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s6_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s6_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s6_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s6_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s6_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s6_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s6_r3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s7_l0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s7_l1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s7_l2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s7_l3.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s7_r0.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s7_r1.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s7_r2.npz +0 -0
- diffneusim/data/reference/x016run/x016run_v3p75_s7_r3.npz +0 -0
- diffneusim/data/state_prior/lumbar_poly_fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc.npz +0 -0
- diffneusim/engine/__init__.py +0 -0
- diffneusim/engine/build_tag.py +52 -0
- diffneusim/engine/case_tables.py +46 -0
- diffneusim/engine/d16_body.py +80 -0
- diffneusim/engine/engine14.py +367 -0
- diffneusim/engine/gen_split.py +159 -0
- diffneusim/engine/hand_format.py +69 -0
- diffneusim/engine/live14.py +149 -0
- diffneusim/engine/phase_b_tree.py +137 -0
- diffneusim/engine/soft14.py +130 -0
- diffneusim/engine/soft_capi.py +373 -0
- diffneusim/engine/soft_engine.py +165 -0
- diffneusim/engine/step14.py +132 -0
- diffneusim/engine/tape_format.py +89 -0
- diffneusim/engine/x14cpu.py +163 -0
- diffneusim/env/__init__.py +0 -0
- diffneusim/env/absent.py +20 -0
- diffneusim/env/cpu14.py +105 -0
- diffneusim/env/e0loop14.py +224 -0
- diffneusim/env/env14.py +568 -0
- diffneusim/env/kin_contact14.py +193 -0
- diffneusim/env/mimic_sites_x14.json +366 -0
- diffneusim/env/old_count.py +78 -0
- diffneusim/env/rew14.py +114 -0
- diffneusim/env/rew14_hook.py +105 -0
- diffneusim/g1/__init__.py +1 -0
- diffneusim/g1/arm_a2.py +165 -0
- diffneusim/g1/arm_a3.py +576 -0
- diffneusim/g1/read_a3.py +79 -0
- diffneusim/g1/rg1_read.py +89 -0
- diffneusim/model/__init__.py +66 -0
- diffneusim/model/case.py +17 -0
- diffneusim/model/dnmodel.py +79 -0
- diffneusim/model/fuse_fixed.py +281 -0
- diffneusim/model/monitor.py +834 -0
- diffneusim/models/BODIES.toml +48 -0
- diffneusim/models/MANIFEST.toml +979 -0
- diffneusim/models/cases/G290/case.bin +0 -0
- diffneusim/models/cases/G290/case.json +1 -0
- diffneusim/models/cases/G356-SRC/case.bin +0 -0
- diffneusim/models/cases/G356-SRC/case.json +1 -0
- diffneusim/models/cases/G416/case.bin +0 -0
- diffneusim/models/cases/G416/case.json +1 -0
- diffneusim/models/cases/M290C-SRC/case.bin +0 -0
- diffneusim/models/cases/M290C-SRC/case.json +1 -0
- diffneusim/models/cases/M290R-SRC/case.bin +0 -0
- diffneusim/models/cases/M290R-SRC/case.json +1 -0
- diffneusim/models/cases/M356C-SRC/case.bin +0 -0
- diffneusim/models/cases/M356C-SRC/case.json +1 -0
- diffneusim/models/cases/M356R-SRC/case.bin +0 -0
- diffneusim/models/cases/M356R-SRC/case.json +1 -0
- diffneusim/models/cases/M416C-SRC/case.bin +0 -0
- diffneusim/models/cases/M416C-SRC/case.json +1 -0
- diffneusim/models/derived/d16_expanded_62f77a4bb16b1e67_mmfloor.xml +673 -0
- diffneusim/models/derived/d16_expanded_a1e8b196b2cd7b3c_mmfloor.xml +673 -0
- diffneusim/models/derived/d16_soft_law_019e20820f8633b9_mmfloor.json +7844 -0
- diffneusim/models/derived/d16_soft_law_62f77a4bb16b1e67_mmfloor.json +16855 -0
- diffneusim/models/derived/d16_soft_law_77dbb7213f26e821_mmfloor_rampsb3l_n6t12.json +7883 -0
- diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rampsb3l_n6t12.json +7883 -0
- diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsd05_n6t12.json +7868 -0
- diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsdef_n6t12.json +7868 -0
- diffneusim/models/derived/d16_soft_law_8989b60e44860c5b_mmfloor_rhlsmjd_n6t12.json +7868 -0
- diffneusim/models/derived/d16_soft_law_a1e8b196b2cd7b3c_mmfloor_rampsb3l_n6t12.json +16894 -0
- diffneusim/models/derived/d16_soft_law_a944653edd642082_mmfloor.json +12655 -0
- diffneusim/models/derived/d16_soft_law_a944653edd642082_mmfloor_rampsb3l_n6t12.json +12700 -0
- diffneusim/models/derived/unitree_g1_soft_law.json +15580 -0
- diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +28913 -0
- diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.dnmodel +29202 -0
- diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid_qk.txt +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_axfixlegs01.dnmodel +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_armless_ball_lspine_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +46970 -0
- diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src.dnmodel +38570 -0
- diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_qk.txt +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid.dnmodel +38923 -0
- diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_millard_stickspin_wrapvia_mtp60k25_trunkfix_toepair_n1_src_rigid_qk.txt +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1.dnmodel +1 -0
- diffneusim/models/fullbody_contact_spinecoupled_fusedhand_ball_lspine_girdle_osimeq_stickspin_wrapvia_mtp60k25_trunkfix_calf2_pe_toepair_flsrc_n1_qk.txt +1 -0
- diffneusim/models/fullbody_meshes/1mc.stl +0 -0
- diffneusim/models/fullbody_meshes/2distph.stl +0 -0
- diffneusim/models/fullbody_meshes/2mc.stl +0 -0
- diffneusim/models/fullbody_meshes/2midph.stl +0 -0
- diffneusim/models/fullbody_meshes/2proxph.stl +0 -0
- diffneusim/models/fullbody_meshes/3distph.stl +0 -0
- diffneusim/models/fullbody_meshes/3mc.stl +0 -0
- diffneusim/models/fullbody_meshes/3midph.stl +0 -0
- diffneusim/models/fullbody_meshes/3proxph.stl +0 -0
- diffneusim/models/fullbody_meshes/4distph.stl +0 -0
- diffneusim/models/fullbody_meshes/4mc.stl +0 -0
- diffneusim/models/fullbody_meshes/4midph.stl +0 -0
- diffneusim/models/fullbody_meshes/4proxph.stl +0 -0
- diffneusim/models/fullbody_meshes/5distph.stl +0 -0
- diffneusim/models/fullbody_meshes/5mc.stl +0 -0
- diffneusim/models/fullbody_meshes/5midph.stl +0 -0
- diffneusim/models/fullbody_meshes/5proxph.stl +0 -0
- diffneusim/models/fullbody_meshes/NOTICE +2 -0
- diffneusim/models/fullbody_meshes/capitate.stl +0 -0
- diffneusim/models/fullbody_meshes/clavicle.stl +0 -0
- diffneusim/models/fullbody_meshes/hamate.stl +0 -0
- diffneusim/models/fullbody_meshes/hat_cervical.stl +0 -0
- diffneusim/models/fullbody_meshes/hat_jaw.stl +0 -0
- diffneusim/models/fullbody_meshes/hat_skull.stl +0 -0
- diffneusim/models/fullbody_meshes/humerus.stl +0 -0
- diffneusim/models/fullbody_meshes/l_bofoot.stl +0 -0
- diffneusim/models/fullbody_meshes/l_femur.stl +0 -0
- diffneusim/models/fullbody_meshes/l_fibula.stl +0 -0
- diffneusim/models/fullbody_meshes/l_foot.stl +0 -0
- diffneusim/models/fullbody_meshes/l_patella.stl +0 -0
- diffneusim/models/fullbody_meshes/l_pelvis.stl +0 -0
- diffneusim/models/fullbody_meshes/l_talus.stl +0 -0
- diffneusim/models/fullbody_meshes/l_tibia.stl +0 -0
- diffneusim/models/fullbody_meshes/lumbar1.stl +0 -0
- diffneusim/models/fullbody_meshes/lumbar2.stl +0 -0
- diffneusim/models/fullbody_meshes/lumbar3.stl +0 -0
- diffneusim/models/fullbody_meshes/lumbar4.stl +0 -0
- diffneusim/models/fullbody_meshes/lumbar5.stl +0 -0
- diffneusim/models/fullbody_meshes/lunate.stl +0 -0
- diffneusim/models/fullbody_meshes/pisiform.stl +0 -0
- diffneusim/models/fullbody_meshes/r_bofoot.stl +0 -0
- diffneusim/models/fullbody_meshes/r_femur.stl +0 -0
- diffneusim/models/fullbody_meshes/r_fibula.stl +0 -0
- diffneusim/models/fullbody_meshes/r_foot.stl +0 -0
- diffneusim/models/fullbody_meshes/r_patella.stl +0 -0
- diffneusim/models/fullbody_meshes/r_pelvis.stl +0 -0
- diffneusim/models/fullbody_meshes/r_talus.stl +0 -0
- diffneusim/models/fullbody_meshes/r_tibia.stl +0 -0
- diffneusim/models/fullbody_meshes/radius.stl +0 -0
- diffneusim/models/fullbody_meshes/sacrum.stl +0 -0
- diffneusim/models/fullbody_meshes/scaphoid.stl +0 -0
- diffneusim/models/fullbody_meshes/scapula.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic10_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic11_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic12_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic1_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic2_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic3_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic4_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic5_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic6_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic7_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic8_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thoracic9_s.stl +0 -0
- diffneusim/models/fullbody_meshes/thorax.stl +0 -0
- diffneusim/models/fullbody_meshes/thumbdist.stl +0 -0
- diffneusim/models/fullbody_meshes/thumbprox.stl +0 -0
- diffneusim/models/fullbody_meshes/trapezium.stl +0 -0
- diffneusim/models/fullbody_meshes/trapezoid.stl +0 -0
- diffneusim/models/fullbody_meshes/triquetrum.stl +0 -0
- diffneusim/models/fullbody_meshes/ulna.stl +0 -0
- diffneusim/models/source/myo_fullbody/UPSTREAM.md +91 -0
- diffneusim/models/source/myoleg/UPSTREAM.md +52 -0
- diffneusim/models/source/unitree_g1/LICENSE.mjlab +202 -0
- diffneusim/models/source/unitree_g1/UPSTREAM.md +38 -0
- diffneusim/models/source/unitree_g1/assets/head_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_ankle_pitch_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_ankle_roll_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_elbow_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_hip_pitch_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_hip_roll_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_hip_yaw_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_knee_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_rubber_hand.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_shoulder_pitch_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_shoulder_roll_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_shoulder_yaw_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_wrist_pitch_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_wrist_roll_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/left_wrist_yaw_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/logo_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/pelvis.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/pelvis_contour_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_ankle_pitch_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_ankle_roll_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_elbow_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_hip_pitch_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_hip_roll_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_hip_yaw_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_knee_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_rubber_hand.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_shoulder_pitch_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_shoulder_roll_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_shoulder_yaw_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_wrist_pitch_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_wrist_roll_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/right_wrist_yaw_link.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/torso_link_rev_1_0.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/waist_roll_link_rev_1_0.STL +0 -0
- diffneusim/models/source/unitree_g1/assets/waist_yaw_link_rev_1_0.STL +0 -0
- diffneusim/models/source/unitree_g1/dump_mjlab_reference.py +30 -0
- diffneusim/models/source/unitree_g1/g1.xml +308 -0
- diffneusim/models/source/unitree_g1/g1_constants.py +298 -0
- diffneusim/models/source/unitree_g1/mjlab_compiled_reference.json +857 -0
- diffneusim/models/unitree_g1.dnmodel +4393 -0
- diffneusim/models/unitree_g1_selfcol.dnmodel +20824 -0
- diffneusim/rl/__init__.py +2 -0
- diffneusim/rl/dynsyn_layer.py +146 -0
- diffneusim/rl/footstep_plan.py +337 -0
- diffneusim/rl/g1_bm_env.py +572 -0
- diffneusim/rl/g1_bm_eval.py +168 -0
- diffneusim/rl/g1_bm_fused.py +275 -0
- diffneusim/rl/g1_bm_ppo.py +622 -0
- diffneusim/rl/g1_bm_sapo.py +551 -0
- diffneusim/rl/g1_ppo.py +395 -0
- diffneusim/rl/g1_sapo_soft.py +240 -0
- diffneusim/rl/g1_soft_env.py +452 -0
- diffneusim/rl/g1_soft_grad.py +145 -0
- diffneusim/rl/geyer_curves_torch.py +108 -0
- diffneusim/rl/gpu_fullbody_vec_env.py +1241 -0
- diffneusim/rl/imitation.py +2027 -0
- diffneusim/rl/imitation_reward_v2.py +248 -0
- diffneusim/rl/imitation_reward_v3.py +349 -0
- diffneusim/rl/latent_task.py +175 -0
- diffneusim/rl/llc_reward.py +316 -0
- diffneusim/rl/millard_curves_torch.py +154 -0
- diffneusim/rl/mirror_symmetry.py +212 -0
- diffneusim/rl/model_path.py +35 -0
- diffneusim/rl/mvae_recon.py +123 -0
- diffneusim/rl/nets_shac.py +599 -0
- diffneusim/rl/reset_pool.py +154 -0
- diffneusim/rl/sapo_capture.py +873 -0
- diffneusim/rl/sapo_vec.py +1051 -0
- diffneusim/rl/shac_vec.py +346 -0
- diffneusim/rl/state_prior.py +151 -0
- diffneusim/rl/step_library.py +105 -0
- diffneusim/rl/task_walk_env.py +1793 -0
- diffneusim/rl/task_walk_reward.py +3300 -0
- diffneusim/run.py +23 -0
- diffneusim/run_env.py +46 -0
- diffneusim/tasks/__init__.py +147 -0
- diffneusim/tasks/legacy_names.py +63 -0
- diffneusim/tasks/paths.py +79 -0
- diffneusim/tasks/settings.py +202 -0
- diffneusim/third_party/instantmimic_947430ee/LICENSE +202 -0
- diffneusim/third_party/instantmimic_947430ee/NOTICE +19 -0
- diffneusim/third_party/instantmimic_947430ee/README.md +31 -0
- diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/benchmark_protocol.py +106 -0
- diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/metrics.py +214 -0
- diffneusim/third_party/instantmimic_947430ee/instantmimic/envs/unitree_g1/tasks/beyondmimic_tracking/reference.py +513 -0
- diffneusim/third_party/instantmimic_947430ee/instantmimic/motion/quaternion.py +193 -0
- diffneusim/train/__init__.py +0 -0
- diffneusim/train/eval_ckpt.py +239 -0
- diffneusim/train/eval_mimic.py +133 -0
- diffneusim/train/gait_report.py +203 -0
- diffneusim/train/gcot_chain.py +51 -0
- diffneusim/train/levers.py +135 -0
- diffneusim/train/masked_reset.py +314 -0
- diffneusim/train/rl_algorithm_suite.py +917 -0
- diffneusim/train/train14.py +240 -0
- diffneusim/train/train_tw14.py +674 -0
- diffneusim/viz/__init__.py +5 -0
- diffneusim/viz/__main__.py +41 -0
- diffneusim/viz/camera.py +115 -0
- diffneusim/viz/dnrec.py +118 -0
- diffneusim/viz/dnrec_io.py +686 -0
- diffneusim/viz/hud.py +565 -0
- diffneusim/viz/meshes.py +458 -0
- diffneusim/viz/play.py +237 -0
- diffneusim/viz/record.py +74 -0
- diffneusim/viz/render.py +1402 -0
- diffneusim/viz/renderer.py +268 -0
- diffneusim/viz/rl_env_render.py +635 -0
- diffneusim/viz/snapshot.py +54 -0
- diffneusim/viz/strobe.py +124 -0
- diffneusim/viz/to_mp4.py +58 -0
- diffneusim/viz/ui.py +481 -0
- diffneusim/viz/viewer.py +2086 -0
- diffneusim-1.0.0.dist-info/METADATA +226 -0
- diffneusim-1.0.0.dist-info/RECORD +682 -0
- diffneusim-1.0.0.dist-info/WHEEL +5 -0
- diffneusim-1.0.0.dist-info/licenses/LICENSE +201 -0
- diffneusim-1.0.0.dist-info/licenses/LICENSES/BSD-3-Clause-NC-ARMS-hand-wrist-4.3.txt +20 -0
- diffneusim-1.0.0.dist-info/licenses/LICENSES/BSD-3-Clause-NC-MoBL-ARMS.txt +25 -0
- diffneusim-1.0.0.dist-info/licenses/LICENSES/CC-BY-3.0-OpenSim-geometry.txt +25 -0
- diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Christophy2012-lumbarspine.txt +10 -0
- diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Lai2017-model-high-flex.txt +10 -0
- diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Lee2015-hand_muscle.txt +11 -0
- diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Rajagopal2016-full_body.txt +11 -0
- diffneusim-1.0.0.dist-info/licenses/LICENSES/MIT-Uhlrich2022-fbmodpassivecal.txt +10 -0
- diffneusim-1.0.0.dist-info/licenses/NOTICE +274 -0
- diffneusim-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1051 @@
|
|
|
1
|
+
"""SAPO -- Soft Analytic Policy Optimization (Xing, Luk, Oh et al., ICLR 2025, arXiv:2412.12089).
|
|
2
|
+
|
|
3
|
+
SAPO = SHAC + maximum-entropy on a differentiable vector env. It reuses the ShacVec machinery (batched
|
|
4
|
+
rollout, td-lambda critic target, obs normalization, linear lr decay) and adds four deltas:
|
|
5
|
+
|
|
6
|
+
1. A STATE-DEPENDENT squashed-Normal actor (ActorSquashedMLP): mu + logstd heads, action = tanh(Normal)
|
|
7
|
+
already in [-1,1] -> fed to the env directly (identity `_env_action`, NO second tanh).
|
|
8
|
+
2. A DOUBLE critic with NO target network (EnsembleCritic, n=2; `target_critic is self.critic`). The
|
|
9
|
+
ACTOR return bootstraps with the AVG of the two critics; the CRITIC td-lambda target bootstraps with
|
|
10
|
+
the MIN (clipped double-Q). The Polyak target-critic update is skipped.
|
|
11
|
+
3. An ENTROPY-AUGMENTED return: the discounted reward accumulator folds in `alpha * ent_norm` (the
|
|
12
|
+
reparameterized, differentiable per-step entropy) -- a first-order (pathwise) max-entropy gradient.
|
|
13
|
+
The same entropy augmentation is added to the td-lambda critic target.
|
|
14
|
+
4. TARGET-ENTROPY normalization + auto-tuned temperature: target_entropy H_bar = -dim(A)/2; the entropy
|
|
15
|
+
is offset+scaled to ~[0,1] before entering the return/target; alpha is learned by a dual step whose
|
|
16
|
+
sign drives alpha DOWN when mean entropy > H_bar and UP when below.
|
|
17
|
+
|
|
18
|
+
Everything is purely additive: ShacVec / RpoVec behavior is untouched, and IVW-H / DDCG / Lattice /
|
|
19
|
+
synergy stay OFF (asserted, fail-fast). See docs and the reference mineral/agents/diffrl/shac.py.
|
|
20
|
+
|
|
21
|
+
Opt-in (latent=True, DN_LATENT=1 in the suite): the ControlVAE / MuscleVAE latent skill model trained by SAPO
|
|
22
|
+
through the exact simulator (see __init__ and docs/training/campaigns/fullbody/latent-skill-model.md).
|
|
23
|
+
Opt-in (latent_task=True, DN_LATENT_TASK=1): its task phase, a high-level policy over z that drives the frozen
|
|
24
|
+
decoder on the env's heading / speed task.
|
|
25
|
+
"""
|
|
26
|
+
import copy
|
|
27
|
+
import inspect
|
|
28
|
+
import os
|
|
29
|
+
import math
|
|
30
|
+
|
|
31
|
+
import torch
|
|
32
|
+
from torch.nn.utils.clip_grad import clip_grad_norm_
|
|
33
|
+
|
|
34
|
+
from .nets_shac import (ActorSquashedLatentMLP, ActorSquashedMLP, EnsembleCritic, LatentSkillEncoder, LatentTaskPolicy,
|
|
35
|
+
RunningMeanStd)
|
|
36
|
+
from .shac_vec import ShacVec
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def scale_new_input_grad(weight, n_cols, mult):
|
|
41
|
+
"""Scale the gradient of the last `n_cols` input columns of `weight` (out, in) by `mult`, in place (SapoVec's new-input step)."""
|
|
42
|
+
assert weight.grad is not None and weight.dim() == 2 and 0 < n_cols < weight.shape[1], (weight.grad is None, tuple(weight.shape), n_cols)
|
|
43
|
+
weight.grad[:, -n_cols:].mul_(mult)
|
|
44
|
+
|
|
45
|
+
class CriticOverlap:
|
|
46
|
+
"""The critic's training on a second CUDA stream, concurrent with the actor's backward of the same window (the walking line's
|
|
47
|
+
E5). Scheduling only: the same operations in the same order on their own data, so training is bitwise the serial path's.
|
|
48
|
+
- before actor_loss.backward(): an event on the main stream (the rollout's writes done);
|
|
49
|
+
- after it returns (the backward enqueued, before the isfinite(gn) host sync): on a side stream that waits on the event,
|
|
50
|
+
_update_alpha, the targets, and train_critic on a SHADOW critic (the backward's captured graphs read the critic's weights,
|
|
51
|
+
so the real critic stays untouched until the backward is done);
|
|
52
|
+
- in place of the serial alpha / targets / critic block: the main stream waits on the side stream, the shadow's parameters
|
|
53
|
+
and optimizer state are copied into the real critic and critic_opt, and the deferred host reads are taken.
|
|
54
|
+
_update_alpha's two float()s and train_critic's float(value_loss) are deferred to the join (defer=True). The actor's return
|
|
55
|
+
detaches alpha (alpha = self.get_alpha().detach()), so the backward writes no log_alpha.grad. train_critic's randperm keeps its
|
|
56
|
+
place in the CUDA generator's sequence (no draws in the backward or the actor step).
|
|
57
|
+
Enable with SapoVec.enable_critic_overlap() after the critic's final form (compiled in place or eager) is set."""
|
|
58
|
+
|
|
59
|
+
def __init__(self):
|
|
60
|
+
self.stream = self.ev = self.done = self.val = self.frozen = self.stats = None
|
|
61
|
+
self.n = 0
|
|
62
|
+
|
|
63
|
+
def _shadow(self, algo):
|
|
64
|
+
c = algo.critic
|
|
65
|
+
comp = getattr(c, "_compiled_call_impl", None)
|
|
66
|
+
if os.environ.get("E0SPEED_LEVERS") == "m1c": # the imitation levers: the critic compiled in place
|
|
67
|
+
assert comp is not None, "m1c: the critic is compiled in place"
|
|
68
|
+
else:
|
|
69
|
+
# no lever: the critic either eager (the shadow eager too) or compiled in place by train_tw14 --tw1-m1c (the shadow as m1c's)
|
|
70
|
+
assert not os.environ.get("E0SPEED_LEVERS"), f"the shadow mirrors m1c's in-place compile only: E0SPEED_LEVERS={os.environ['E0SPEED_LEVERS']!r}"
|
|
71
|
+
if comp is not None:
|
|
72
|
+
c._compiled_call_impl = None # deepcopy without the compiled call (it is bound to the real critic)
|
|
73
|
+
sc = copy.deepcopy(c)
|
|
74
|
+
c._compiled_call_impl = comp
|
|
75
|
+
sc.compile(dynamic=False) # levers.py m1c's call, on the shadow's own parameters
|
|
76
|
+
else:
|
|
77
|
+
sc = copy.deepcopy(c) # an eager critic: an eager shadow (the same modules, its own parameters)
|
|
78
|
+
self.cp, self.sp = list(c.parameters()), list(sc.parameters())
|
|
79
|
+
assert len(self.cp) == len(self.sp) and all(a.data_ptr() != b.data_ptr() and a.shape == b.shape for a, b in zip(self.cp, self.sp))
|
|
80
|
+
oc = algo.critic_opt
|
|
81
|
+
acc = inspect.signature(type(oc).__init__).parameters # (AdamW keeps Adam's decoupled_weight_decay in defaults, not as an argument)
|
|
82
|
+
so = type(oc)(sc.parameters(), **{k: v for k, v in oc.defaults.items() if k in acc})
|
|
83
|
+
assert so.defaults == oc.defaults, f"the shadow optimizer's defaults differ: {so.defaults} vs {oc.defaults}"
|
|
84
|
+
so.load_state_dict(oc.state_dict())
|
|
85
|
+
self.sc, self.so = sc, so
|
|
86
|
+
print(f"[critic overlap] shadow critic: {len(self.sp)} tensors, {sum(p.numel() for p in self.sp)} parameters; optimizer "
|
|
87
|
+
f"{type(so).__name__} {sorted(k for k, v in so.defaults.items() if v is True)}", flush=True)
|
|
88
|
+
|
|
89
|
+
def mark(self, algo, epoch):
|
|
90
|
+
self.ev = torch.cuda.Event()
|
|
91
|
+
self.ev.record() # on the main stream, after the rollout, before the backward
|
|
92
|
+
|
|
93
|
+
def launch(self, algo, epoch):
|
|
94
|
+
if self.stream is None:
|
|
95
|
+
self.stream = torch.cuda.Stream()
|
|
96
|
+
self._shadow(algo)
|
|
97
|
+
self.frozen = frozen = epoch < algo.actor_freeze_epochs
|
|
98
|
+
st = self.stream
|
|
99
|
+
with torch.cuda.stream(st):
|
|
100
|
+
st.wait_event(self.ev)
|
|
101
|
+
self.stats = None
|
|
102
|
+
if not frozen and not algo.ltask:
|
|
103
|
+
algo._update_alpha(defer=True)
|
|
104
|
+
self.stats = algo._e5_alpha_stats
|
|
105
|
+
algo.compute_target_values_with_entropy()
|
|
106
|
+
with torch.no_grad():
|
|
107
|
+
for s, p in zip(self.sp, self.cp):
|
|
108
|
+
s.copy_(p)
|
|
109
|
+
for gs, g in zip(self.so.param_groups, algo.critic_opt.param_groups):
|
|
110
|
+
assert {k: v for k, v in gs.items() if k not in ("params", "lr")} == {k: v for k, v in g.items() if k not in ("params", "lr")}
|
|
111
|
+
gs["lr"] = g["lr"] # the linear schedule sets critic_opt's lr each epoch
|
|
112
|
+
c, o = algo.critic, algo.critic_opt
|
|
113
|
+
algo.critic, algo.critic_opt = self.sc, self.so
|
|
114
|
+
self.val = algo.train_critic(defer=True)
|
|
115
|
+
algo.critic, algo.critic_opt = c, o
|
|
116
|
+
self.done = torch.cuda.Event()
|
|
117
|
+
self.done.record(st)
|
|
118
|
+
|
|
119
|
+
def join(self, algo, epoch, frozen):
|
|
120
|
+
assert frozen == self.frozen and algo.critic is not self.sc
|
|
121
|
+
torch.cuda.current_stream().wait_event(self.done)
|
|
122
|
+
with torch.no_grad():
|
|
123
|
+
for p, s in zip(self.cp, self.sp):
|
|
124
|
+
p.copy_(s)
|
|
125
|
+
so, ss = algo.critic_opt.state[p], self.so.state[s]
|
|
126
|
+
for k, v in ss.items():
|
|
127
|
+
if torch.is_tensor(v):
|
|
128
|
+
if k in so:
|
|
129
|
+
so[k].copy_(v)
|
|
130
|
+
else:
|
|
131
|
+
so[k] = v.clone()
|
|
132
|
+
else:
|
|
133
|
+
so[k] = v
|
|
134
|
+
if self.stats is not None:
|
|
135
|
+
algo.last_alpha = float(self.stats[0])
|
|
136
|
+
algo.last_entropy_mean = float(self.stats[1])
|
|
137
|
+
self.n += 1
|
|
138
|
+
return float(self.val)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class SapoVec(ShacVec):
|
|
142
|
+
def __init__(self, env, actor_units=(128, 64, 32), critic_units=(64, 64), activation="silu",
|
|
143
|
+
n_critics=2, init_alpha=1.0, alpha_lr=5e-3, alpha_betas=(0.7, 0.95),
|
|
144
|
+
target_entropy_scalar=0.5, actor_out_bias=None, betas=(0.7, 0.95),
|
|
145
|
+
adaptive_horizon=False, ahac_steps_min=8, ahac_steps_max=None, ahac_C=None,
|
|
146
|
+
ahac_lambd_lr=1e-4, ahac_shorten_on_stiff=True,
|
|
147
|
+
per_env_cut=False, pec_C=None, pec_cut_critic=False, actor_freeze_epochs=0,
|
|
148
|
+
actor_opt="adamw", actor_sgd_lr_scale=1.0, entropy_dims=None,
|
|
149
|
+
latent=False, latent_dim=64, latent_sigma=0.3, latent_units=(512, 512), latent_beta_start=0.01,
|
|
150
|
+
latent_beta_end=0.1, latent_beta_every=500, latent_beta_steps=8, latent_prior_frac=0.0,
|
|
151
|
+
latent_task=False, latent_task_ckpt=None, latent_task_wz=20.0, latent_task_sigma=None,
|
|
152
|
+
latent_task_units=(256, 256, 256), new_input_cols=0, new_input_lr_mult=1.0, **kw):
|
|
153
|
+
# SAPO is a pure max-entropy add-on; the pathwise-gradient band-aids and the correlated/synergy
|
|
154
|
+
# exploration priors are neither used nor wired here (they change the action density / gradient
|
|
155
|
+
# blend). Fail-fast rather than silently ignore an incompatible flag.
|
|
156
|
+
assert not kw.get("ivw_h", False), "SAPO does not use IVW-H"
|
|
157
|
+
assert not kw.get("ddcg", False), "SAPO does not use DDCG"
|
|
158
|
+
assert not kw.get("lattice", False), "SAPO uses a squashed-Normal actor, not Lattice"
|
|
159
|
+
assert kw.get("synergy_path") is None, "SAPO does not use the synergy exploration prior"
|
|
160
|
+
# action_grad_clip (per-env pathwise-grad cap) IS allowed: it is ENV-LEVEL gradient taming for the
|
|
161
|
+
# stiff-contact full-body FoBG explosion (fullbody/myoleg26 cfg default 2.0), orthogonal to SAPO's
|
|
162
|
+
# max-entropy mechanism and applied in the inherited _action_grad_hook (ivw_h is off, so the hook
|
|
163
|
+
# just clips each env's action-grad to `factor`x the median -- stops a few chaotic envs' exploding
|
|
164
|
+
# BPTT gradient from dominating the grad-norm-clipped actor step). Without it full-body SAPO's raw
|
|
165
|
+
# actor grad-norm explodes (measured gn 2e3->6e4 over 3 epochs); with it the direction stays clean.
|
|
166
|
+
super().__init__(env, actor_units=actor_units, critic_units=critic_units,
|
|
167
|
+
actor_out_bias=actor_out_bias, betas=betas, **kw)
|
|
168
|
+
|
|
169
|
+
# --- SAPO actor/critic (replace the ShacVec ActorStochasticMLP / CriticMLP / Adam) ---
|
|
170
|
+
# DeepLoco's phase-gated input on both nets when the env carries phase-bin slots (TASKWALK_CYCLE_PHASE_BINS); None = ungated
|
|
171
|
+
_bins = getattr(env, "phase_gate_bins", None)
|
|
172
|
+
# LATENT SKILL MODEL (latent=True; default off => none of the latent code runs, byte-identical). ControlVAE /
|
|
173
|
+
# MuscleVAE (arXiv:2210.06063, 2312.07340) trained through the EXACT simulator instead of a world model: a prior
|
|
174
|
+
# p(z | s), a posterior q(z | s, s~') on the env's next-reference block (env.latent_ref_obs) and a decoder pi(a | s,
|
|
175
|
+
# z) = the SAPO actor with z at every layer (nets_shac.LatentSkillEncoder / ActorSquashedLatentMLP). z is drawn
|
|
176
|
+
# from the posterior by reparameterisation each control step, so the return's pathwise gradient reaches the
|
|
177
|
+
# decoder, the posterior offset AND the prior. The papers' reconstruction loss is replaced by SAPO's return on the
|
|
178
|
+
# env's tracking reward; their KL term enters that return per step, -beta KL, discounted like the reward. The
|
|
179
|
+
# critic sees the next-reference block too: the value of a tracking state depends on the target it is asked for.
|
|
180
|
+
self.latent = None
|
|
181
|
+
self.num_ref_obs = 0
|
|
182
|
+
# THE LATENT MODEL'S TASK PHASE (latent_task=True, P3; default off => none of it runs). MuscleVAE App. B.3 /
|
|
183
|
+
# ControlVAE Sec. 4.2: a high-level policy N(mu_p(s) + mu_g(s, g), sigma_g^2 I) over z, an OFFSET on the state
|
|
184
|
+
# prior's mean, drives the decoder pi(a | s, z) of a trained latent checkpoint (latent_task_ckpt). Decoder, prior
|
|
185
|
+
# and the observation normaliser are FROZEN: no optimiser holds them and requires_grad is off, but they stay in
|
|
186
|
+
# the graph, so the return's pathwise gradient through the simulator reaches z and mu_g THROUGH them. `self.actor`
|
|
187
|
+
# is the trainable task policy mu_g (nets_shac.LatentTaskPolicy); the loss is the env's task reward (ALIVE - L_g)
|
|
188
|
+
# minus MuscleVAE's w_z ||mu_g||^2 per step, discounted like the reward, in the actor's return AND the critic's
|
|
189
|
+
# target (as P2 charges its KL). No entropy term: sigma_g is fixed, and the frozen decoder's action entropy is not
|
|
190
|
+
# the task's objective. The critic reads [s, g].
|
|
191
|
+
self.ltask = bool(latent_task)
|
|
192
|
+
self.num_task_obs = 0
|
|
193
|
+
assert not (latent and self.ltask), "latent=True trains a latent model, latent_task=True drives a frozen one"
|
|
194
|
+
assert _bins is None or not (latent or self.ltask), (
|
|
195
|
+
"the phase gate (TASKWALK_CYCLE_PHASE_BINS) is not wired into the latent model or its task policy")
|
|
196
|
+
if latent:
|
|
197
|
+
assert getattr(env, "LATENT", False) and int(getattr(env, "num_ref_obs", 0)) > 0, (
|
|
198
|
+
f"latent=True needs an env that emits the next-reference block (DN_LATENT=1); {type(env).__name__} "
|
|
199
|
+
"does not")
|
|
200
|
+
self.num_ref_obs = int(env.num_ref_obs)
|
|
201
|
+
self.actor = ActorSquashedLatentMLP(self.num_obs, latent_dim, self.num_actions, units=actor_units,
|
|
202
|
+
activation=activation, device=self.device, out_bias=actor_out_bias)
|
|
203
|
+
elif self.ltask:
|
|
204
|
+
assert hasattr(env, "latent_task_obs") and int(getattr(env, "num_task_obs", 0)) > 0, (
|
|
205
|
+
f"latent_task=True needs an env that emits the command block (DN_LATENT_TASK=1); {type(env).__name__} "
|
|
206
|
+
"does not")
|
|
207
|
+
self.num_task_obs = int(env.num_task_obs)
|
|
208
|
+
self._load_frozen_latent_model(latent_task_ckpt, activation)
|
|
209
|
+
assert latent_task_wz >= 0.0, latent_task_wz
|
|
210
|
+
self.ltask_wz = float(latent_task_wz)
|
|
211
|
+
# sigma_g = sigma_q (MuscleVAE App. B.3), the checkpoint's; 0 = the released code's deterministic z = mu_p + mu_g
|
|
212
|
+
self.ltask_sigma = float(self.ltask_encoder.sigma if latent_task_sigma is None else latent_task_sigma)
|
|
213
|
+
assert self.ltask_sigma >= 0.0, self.ltask_sigma
|
|
214
|
+
self.actor = LatentTaskPolicy(self.num_obs, self.num_task_obs, self.ltask_encoder.latent_dim,
|
|
215
|
+
units=latent_task_units, activation="elu", device=self.device)
|
|
216
|
+
self.ltask_cfg = dict(source=str(latent_task_ckpt), source_epoch=self._ltask_src_epoch,
|
|
217
|
+
latent_cfg=dict(self._ltask_latent_cfg), decoder_units=list(self._ltask_dec_units),
|
|
218
|
+
activation=str(activation), wz=self.ltask_wz, sigma=self.ltask_sigma,
|
|
219
|
+
units=[int(u) for u in latent_task_units], num_task_obs=self.num_task_obs)
|
|
220
|
+
self.task_buf = torch.zeros((self.steps_num, self.num_envs, self.num_task_obs), device=self.device)
|
|
221
|
+
self.offsq_buf = torch.zeros((self.steps_num, self.num_envs), device=self.device) # ||mu_g||^2 per step
|
|
222
|
+
self.last_task_reg_mean = 0.0
|
|
223
|
+
self.last_task_offset_rms = 0.0
|
|
224
|
+
self.last_task_stats = {}
|
|
225
|
+
else:
|
|
226
|
+
self.actor = ActorSquashedMLP(self.num_obs, self.num_actions, units=actor_units,
|
|
227
|
+
activation=activation, device=self.device, out_bias=actor_out_bias, phase_bins=_bins)
|
|
228
|
+
self.critic = EnsembleCritic(self.num_obs + self.num_ref_obs + self.num_task_obs, units=critic_units,
|
|
229
|
+
activation=activation, device=self.device, n_critics=n_critics, phase_bins=_bins)
|
|
230
|
+
if latent:
|
|
231
|
+
self.latent = LatentSkillEncoder(self.num_obs, self.num_ref_obs, latent_dim=latent_dim, units=latent_units,
|
|
232
|
+
sigma=latent_sigma, activation="elu", device=self.device)
|
|
233
|
+
self.latent_cfg = dict(dim=int(latent_dim), sigma=float(latent_sigma), units=[int(u) for u in latent_units],
|
|
234
|
+
num_obs=int(self.num_obs), num_ref_obs=int(self.num_ref_obs))
|
|
235
|
+
self.ref_rms = RunningMeanStd((self.num_ref_obs,), device=self.device)
|
|
236
|
+
self.ref_buf = torch.zeros((self.steps_num, self.num_envs, self.num_ref_obs), device=self.device)
|
|
237
|
+
self.kl_buf = torch.zeros((self.steps_num, self.num_envs), device=self.device)
|
|
238
|
+
# THE KL WEIGHT. ControlVAE (Sec. 3.3.1): "beta ... increases once every 500 training epochs from 0.01 to 0.1";
|
|
239
|
+
# its released code steps it linearly in 8 increments, one every 500 iterations (ptu.scheduler(0, 8, 0.009,
|
|
240
|
+
# 0.09, 500 * 8) stepped once per each of its 8 minibatches), i.e. full weight at iteration 4000 of 20001, and
|
|
241
|
+
# with the values 0.009 -> 0.09. Here beta(epoch) = start + (end - start) min(epoch // every, steps) / steps,
|
|
242
|
+
# one SAPO epoch per paper epoch; every=1 with steps=N is a linear ramp over N epochs.
|
|
243
|
+
assert 0.0 <= latent_beta_start and 0.0 <= latent_beta_end, (latent_beta_start, latent_beta_end)
|
|
244
|
+
assert latent_beta_every >= 1 and latent_beta_steps >= 1, (latent_beta_every, latent_beta_steps)
|
|
245
|
+
self.latent_beta_start, self.latent_beta_end = float(latent_beta_start), float(latent_beta_end)
|
|
246
|
+
self.latent_beta_every, self.latent_beta_steps = int(latent_beta_every), int(latent_beta_steps)
|
|
247
|
+
self.last_beta = self.latent_beta(0)
|
|
248
|
+
# MuscleVAE's COLLECTION mix (trajectory_collection.py:53-61; CVp Sec. 3.4.4): each step, with probability 0.4, the
|
|
249
|
+
# action comes from a PRIOR z instead of the posterior. There those steps only shape the replay buffer (the policy's
|
|
250
|
+
# loss runs the posterior through the world model), so here a prior step carries no KL, and its action and entropy
|
|
251
|
+
# are detached: it moves the state the window visits, and BPTT still runs through its dynamics. 0 = off (no draw).
|
|
252
|
+
assert 0.0 <= latent_prior_frac < 1.0, latent_prior_frac
|
|
253
|
+
self.latent_prior_frac = float(latent_prior_frac)
|
|
254
|
+
self.last_kl_mean = 0.0
|
|
255
|
+
self.last_latent_gn = 0.0
|
|
256
|
+
# which z the deterministic act() uses: "tracking" = the posterior mean given the reference, "generation" =
|
|
257
|
+
# z sampled from the prior, no reference (eval_ckpt --latent-mode)
|
|
258
|
+
self.latent_eval_mode = "tracking"
|
|
259
|
+
# eval diagnostic, off unless set to a list: tracking-mode act() appends the per-env KL of the posterior mean
|
|
260
|
+
# against the prior mean, |mu_q|^2 / (2 sigma^2), i.e. how far the prior sits from what the reference asks for
|
|
261
|
+
self.latent_kl_trace = None
|
|
262
|
+
# KICKSTARTING (Schmitt et al. 2018, arXiv:1803.03835; opt-in, unset = bit-identical). A frozen TEACHER policy
|
|
263
|
+
# (SAPO_KICKSTART_CKPT: actor + obs_rms, e.g. a padded imitation actor) adds an auxiliary distillation loss to the
|
|
264
|
+
# student's actor loss: w(epoch) * mean over the window's visited states of the squared distance between the two
|
|
265
|
+
# pre-tanh action MEANS, each network on its OWN normalised observation, on DETACHED states (a supervised pull, no
|
|
266
|
+
# pathwise term). w anneals linearly from SAPO_KICKSTART_W to 0 over SAPO_KICKSTART_EPOCHS, so after that the
|
|
267
|
+
# student trains on the task reward alone. The student starts cold; only its learning path is pulled toward the
|
|
268
|
+
# teacher (gradient-field-ioc.md STATE 2026-10-15 21:5x).
|
|
269
|
+
self._ks_teacher = None
|
|
270
|
+
self.target_critic = self.critic # NO target network (same object); Polyak update skipped
|
|
271
|
+
# E0 step 4 (tools/d16_fused_env/CAPTURE_PLAN.md), both off by default:
|
|
272
|
+
# 4e, SAPO_FREEZE_CRITIC_BPTT=1: the critic's parameters do not require grad while the actor's window is built, so its
|
|
273
|
+
# BPTT computes only the bootstrap's input gradient. The weight gradients it skips were accumulated into the critic's
|
|
274
|
+
# .grad and discarded unread: train_critic's critic_opt.zero_grad() runs before its first read (checked 11-03).
|
|
275
|
+
# 4d', SAPO_ONE_BOOTSTRAP=1: one target-critic call per step, on obs_before_reset, instead of two. A non-done env's
|
|
276
|
+
# obs and obs_before_reset are the same state, and a done env's bootstrap never read V(obs). "planted" is the gate's
|
|
277
|
+
# control: V(obs) for the done envs (wrong; it must fail the gate).
|
|
278
|
+
self.freeze_critic_bptt = os.environ.get("SAPO_FREEZE_CRITIC_BPTT", "0") == "1"
|
|
279
|
+
self.one_bootstrap = os.environ.get("SAPO_ONE_BOOTSTRAP", "0")
|
|
280
|
+
assert self.one_bootstrap in ("0", "1", "planted"), self.one_bootstrap
|
|
281
|
+
# CRITIC WARM-UP (2026-10-03). For a warm start whose critic cannot be reused (another reward valued it), the
|
|
282
|
+
# first epochs train the critic on the frozen actor's rollouts: no actor step, no alpha step. Without it a fresh
|
|
283
|
+
# critic's bootstrap gradient (gn 29 at ep12 of fb_tw_PROBE_imwarm_s1) wrecked the warm-started gait by ep48.
|
|
284
|
+
# 0 = OFF, byte-identical.
|
|
285
|
+
assert actor_freeze_epochs >= 0, actor_freeze_epochs
|
|
286
|
+
self.actor_freeze_epochs = int(actor_freeze_epochs)
|
|
287
|
+
# THE ACTOR'S OPTIMISER (2026-10-10, gradient-field-ioc.md STATE 20:5x). AdamW at betas (0.7, 0.95) is SHAC's / the SAPO
|
|
288
|
+
# paper's; measured in the G5h checkpoints its step m_hat / sqrt(v_hat) has cos 0.23-0.32 with the averaged gradient and 0.84-0.91
|
|
289
|
+
# with sign(m), i.e. sign descent, so a feature on which the reward is neutral is not held. "sgd" = the gradient itself (momentum
|
|
290
|
+
# and dampening = beta1, so the buffer is the same EMA of the clipped gradient as Adam's m), its lr = the scheduled actor lr x
|
|
291
|
+
# `actor_sgd_lr_scale`, the scale derived from a checkpoint's Adam state for an equal first-order gain per step,
|
|
292
|
+
# lr_adam (m . step) / |m|^2. The critic keeps AdamW. "adamw" default => byte-identical.
|
|
293
|
+
assert actor_opt in ("adamw", "sgd"), actor_opt
|
|
294
|
+
assert actor_sgd_lr_scale > 0.0, actor_sgd_lr_scale
|
|
295
|
+
assert actor_opt == "sgd" or actor_sgd_lr_scale == 1.0, "SAPO_ACTOR_SGD_LR_SCALE only acts on SAPO_ACTOR_OPT=sgd"
|
|
296
|
+
self._actor_lr_scale = float(actor_sgd_lr_scale)
|
|
297
|
+
# The latent encoder (prior + posterior) trains in the ACTOR's optimiser, on the same loss and lr schedule, as
|
|
298
|
+
# ControlVAE trains its encoder and decoder in one optimiser (vae_optimizer); their norms are clipped separately.
|
|
299
|
+
_pol = self.actor.parameters() if self.latent is None else (
|
|
300
|
+
list(self.actor.parameters()) + list(self.latent.parameters()))
|
|
301
|
+
if actor_opt == "sgd":
|
|
302
|
+
self.actor_opt = torch.optim.SGD(_pol, lr=self.actor_lr * self._actor_lr_scale,
|
|
303
|
+
momentum=betas[0], dampening=betas[0])
|
|
304
|
+
else:
|
|
305
|
+
self.actor_opt = torch.optim.AdamW(_pol, betas=betas, lr=self.actor_lr)
|
|
306
|
+
self.critic_opt = torch.optim.AdamW(self.critic.parameters(), betas=betas, lr=self.critic_lr)
|
|
307
|
+
# NEW-INPUT STEP (2026-10-22, docs-dev/deeploco/20261022_1700_hoc_steer): the last `new_input_cols` input columns of the
|
|
308
|
+
# actor's first layer (the heading columns a warm start appends as zeros, tools/pad_heading_actor.py) step `new_input_lr_mult`
|
|
309
|
+
# times the actor lr, applied after the global gradient-norm clip so the rest of the actor's step is unchanged. MEASURED: at
|
|
310
|
+
# the walker's end lr the heading columns moved 0.07 median column norms in 500 epochs (steer1flh), steer1f's 1.03 at 36x;
|
|
311
|
+
# a column-only step of 1-4 column norms along the update turns the body 3-10 deg toward a command. 0 / 1.0 = off.
|
|
312
|
+
assert new_input_cols >= 0 and new_input_lr_mult > 0.0, (new_input_cols, new_input_lr_mult)
|
|
313
|
+
assert (new_input_cols == 0) == (new_input_lr_mult == 1.0), "SAPO_ACTOR_NEW_INPUT_COLS and _LR_MULT go together"
|
|
314
|
+
self._new_in_cols, self._new_in_mult, self._new_in_w = int(new_input_cols), float(new_input_lr_mult), None
|
|
315
|
+
if self._new_in_cols:
|
|
316
|
+
ws = [p for n, p in self.actor.named_parameters() if n.endswith(".0.weight")]
|
|
317
|
+
assert len(ws) >= 1 and ws[0].shape[1] == self.num_obs, ([n for n, _ in self.actor.named_parameters()][:4], self.num_obs)
|
|
318
|
+
assert self._new_in_cols < ws[0].shape[1], (self._new_in_cols, tuple(ws[0].shape))
|
|
319
|
+
self._new_in_w = ws[0]
|
|
320
|
+
|
|
321
|
+
# --- auto-temperature (max-entropy) ---
|
|
322
|
+
# target entropy H_bar = -dim(A)/2 (target_entropy_scalar=0.5); |H_bar| scales the normalization.
|
|
323
|
+
# THE ENTROPY BLOCK (2026-10-14, gradient-field-ioc.md STATE 05:5x). With the summed target, the light trunk fascicles carry
|
|
324
|
+
# the budget (+0.58 nats per dim under 10 g, the legs -2.7: docs-dev/task-rl/20261014_0505_tflb_bushing_cold), because the bonus is
|
|
325
|
+
# the same per dim while the effort price scales with mass. `entropy_dims` = the action dims whose entropy enters the bonus
|
|
326
|
+
# and the temperature dual, a block with its own target (Delalleau et al. 2019, Eq. 2); the other dims get none. The target is
|
|
327
|
+
# -target_entropy_scalar per block dim. The normaliser keeps the full action's 0.5 dim(A), so the per-nat temperature
|
|
328
|
+
# alpha / dim(A), and the bonus at the target (0), are the default's: a warm start carries alpha over unchanged.
|
|
329
|
+
# None = every dim, byte-identical.
|
|
330
|
+
if entropy_dims is None:
|
|
331
|
+
self._ent_dims = None
|
|
332
|
+
self.target_entropy = -target_entropy_scalar * self.num_actions
|
|
333
|
+
self._abs_H = abs(self.target_entropy)
|
|
334
|
+
else:
|
|
335
|
+
dims = [int(d) for d in entropy_dims]
|
|
336
|
+
assert dims == sorted(set(dims)) and 0 < len(dims) < self.num_actions, (len(dims), self.num_actions)
|
|
337
|
+
assert dims[0] >= 0 and dims[-1] < self.num_actions, (dims[0], dims[-1], self.num_actions)
|
|
338
|
+
self._ent_dims = torch.tensor(dims, dtype=torch.long, device=self.device)
|
|
339
|
+
self.target_entropy = -target_entropy_scalar * len(dims)
|
|
340
|
+
self._abs_H = 0.5 * self.num_actions
|
|
341
|
+
self.log_alpha = torch.nn.Parameter(
|
|
342
|
+
torch.tensor(math.log(init_alpha), dtype=torch.float32, device=self.device))
|
|
343
|
+
self.alpha_opt = torch.optim.AdamW([self.log_alpha], lr=alpha_lr, betas=alpha_betas)
|
|
344
|
+
# per-step RAW Monte-Carlo entropy (summed over action dims), stashed detached during the rollout;
|
|
345
|
+
# re-used by the entropy-augmented critic target and the alpha dual loss.
|
|
346
|
+
self.ent_raw_buf = torch.zeros((self.steps_num, self.num_envs), device=self.device)
|
|
347
|
+
# PREREG_S290 Amendment 16: the env's decision rate (TASKWALK_DECISION_EVERY; 1 = off, and nothing below is allocated or read)
|
|
348
|
+
self.decision_every = getattr(env, "decision_every", 1)
|
|
349
|
+
if self.decision_every > 1:
|
|
350
|
+
assert not self.ltask, "the decision-rate hold is not defined for the latent-task phase"
|
|
351
|
+
self.dec_buf = torch.ones((self.steps_num, self.num_envs), device=self.device) # 1 = a decision step (alpha's mask)
|
|
352
|
+
self.last_alpha = float(self.get_alpha().detach())
|
|
353
|
+
self.last_entropy_mean = 0.0
|
|
354
|
+
self._e5 = None # CriticOverlap once enable_critic_overlap() ran
|
|
355
|
+
if self.ltask:
|
|
356
|
+
self.last_alpha = 0.0 # the task phase has no entropy term (the log says so)
|
|
357
|
+
|
|
358
|
+
# --- AHAC adaptive horizon (opt-in; default OFF => byte-identical fixed-H SAPO) ---
|
|
359
|
+
# The tight imitation-ET acted as an IMPLICIT adaptive-horizon (termination chopped the BPTT window,
|
|
360
|
+
# bounding the pathwise gradient); releasing it uncapped the horizon -> stiff muscle-contact gradient
|
|
361
|
+
# blow-up (raw actor gn 2-5 -> 19) -> mode-collapse. AHAC (Georgiev et al. ICML2024, arXiv 2405.17784)
|
|
362
|
+
# restores that bound principally: a GLOBAL adaptive rollout length H, so the imitation tube can
|
|
363
|
+
# open/off WITHOUT the blow-up. SapoVec already IS AHAC's critic (double, no target, min/avg
|
|
364
|
+
# bootstrap) -> only the horizon controller is added. Controller (single-integrator on the actor
|
|
365
|
+
# grad-norm gn): H += lr * sgn * (C - gn); sgn=+1 (shorten_on_stiff, our goal) SHRINKS H when gn > C
|
|
366
|
+
# so the window is capped BEFORE it explodes -- the sign-inverted variant of the published H-update
|
|
367
|
+
# (which GROWS H under stiffness to maximise credit-horizon s.t. a stiffness bound). Buffers stay
|
|
368
|
+
# allocated at steps_max; self.steps_num is re-pinned to round(H) each epoch so the fixed-H rollout/
|
|
369
|
+
# target/loss code runs unchanged at the current length. Signal = the post-rollout actor grad-norm
|
|
370
|
+
# (the exact quantity that blew up), used 1 epoch late (fine for a slow lr). C is in gn units and
|
|
371
|
+
# MUST be calibrated per model (fail-fast if unset).
|
|
372
|
+
self.adaptive_horizon = bool(adaptive_horizon)
|
|
373
|
+
if self.adaptive_horizon:
|
|
374
|
+
self.steps_max = int(ahac_steps_max) if ahac_steps_max else self.steps_num
|
|
375
|
+
assert self.steps_max <= self.steps_num, (self.steps_max, self.steps_num) # buffers sized at steps_num
|
|
376
|
+
self.steps_min = int(ahac_steps_min)
|
|
377
|
+
assert 1 <= self.steps_min <= self.steps_max, (self.steps_min, self.steps_max)
|
|
378
|
+
assert ahac_C is not None, "adaptive_horizon needs ahac_C (threshold in actor grad-norm units)"
|
|
379
|
+
self.ahac_C = float(ahac_C)
|
|
380
|
+
self.ahac_lambd_lr = float(ahac_lambd_lr)
|
|
381
|
+
self.ahac_sgn = 1.0 if ahac_shorten_on_stiff else -1.0
|
|
382
|
+
self.H = torch.tensor(float(self.steps_max), device=self.device) # start full; shrink if stiff
|
|
383
|
+
self.last_H = float(self.H)
|
|
384
|
+
|
|
385
|
+
# --- per-env AHAC cut (opt-in; default OFF => byte-identical) ---
|
|
386
|
+
# Per-env pathwise-gradient truncation: an env whose contact-impulse norm (extra["cfnorm"], a
|
|
387
|
+
# forward-available stiffness proxy) exceeds pec_C is truncated at that step -- V-bootstrap + obs
|
|
388
|
+
# detach -- so each env gets its OWN effective BPTT horizon within the fixed synchronous window.
|
|
389
|
+
# This is the vectorizable form of AHAC-1's per-env cut (fixed window forward + per-env graph
|
|
390
|
+
# detach), avoiding the paper's asynchronous-rollout "infinite graph". pec_C is in contact-impulse
|
|
391
|
+
# units, per-model. See compute_actor_loss.
|
|
392
|
+
self.per_env_cut = bool(per_env_cut)
|
|
393
|
+
self.pec_cut_critic = bool(pec_cut_critic) # see compute_actor_loss: OFF = gradient-only truncation
|
|
394
|
+
if self.per_env_cut:
|
|
395
|
+
assert pec_C is not None, "per_env_cut needs pec_C (ground-contact-force threshold; calibrate per model)"
|
|
396
|
+
self.pec_C = float(pec_C)
|
|
397
|
+
# The cut needs BOTH halves of the env contract: the forward stiffness signal and the state
|
|
398
|
+
# detach. Envs that lack them (gpu_vec_env, gpu_myoleg_vec_env) would otherwise die mid-rollout
|
|
399
|
+
# on a bare KeyError for extra["cfnorm"]; say so at construction instead.
|
|
400
|
+
assert hasattr(env, "detach_envs"), (
|
|
401
|
+
f"per_env_cut needs env.detach_envs(mask); {type(env).__name__} does not implement it")
|
|
402
|
+
assert getattr(env, "_emit_cfnorm", False), (
|
|
403
|
+
f"per_env_cut needs extra['cfnorm'] from the env; {type(env).__name__} is not emitting it "
|
|
404
|
+
"(set SAPO_PEC=1 before the env is constructed)")
|
|
405
|
+
|
|
406
|
+
# --- CRITIC SLOPE (opt-in; SAPO_CRITIC_SLOPE_W unset or 0 => byte-identical) ---
|
|
407
|
+
# The actor follows the critic's STATE gradient at the window's end, 28-86x the largest reward term's, and that slope
|
|
408
|
+
# is orthogonal to the pathwise slope of the critic's own Bellman target (cos 0.00-0.02 at windows 32 and 64, early and
|
|
409
|
+
# late; tools/gait/critic_slope_gates.py, docs-dev/deeploco/20261025_0640_llc_h64). A value-trained critic leaves its
|
|
410
|
+
# slope free (MAGE, D'Oro & Jaskowski 2020); the remedy is to train it against a pathwise target (Fairbank's VGL(lambda),
|
|
411
|
+
# Sobolev training; JAVE, Opat 2026, the SHAC-family precedent). Here the target is EXACT and needs no model: the
|
|
412
|
+
# simulator's gradient of the window's own soft return from s_t, VGL's lambda = 0 (no bootstrap: 58-89% of the
|
|
413
|
+
# bootstrapped target is the critic's own slope carried back, and the window's Jacobian expands random directions
|
|
414
|
+
# 11-13x, so a bootstrapped target has no guaranteed fixed point). States s_t for t = 1 .. H // 2 only, so every target
|
|
415
|
+
# spans at least half a window. Matched in RAW state units on the blocks the critic observes as raw coordinates
|
|
416
|
+
# (env.slope_slots: q[7:], qd, lce), so the fibre lengths, where the slope is 6-7x too large, are constrained where they
|
|
417
|
+
# act (in normalised units a 1 / sigma ~137 block would weigh ~5e-5). The value loss stays as the anchor (MAGE App. B.1:
|
|
418
|
+
# a gradient-only critic collapses). Scale-free weight: the term is the relative slope error times the TD target's
|
|
419
|
+
# variance, so SAPO_CRITIC_SLOPE_W = 1 is Sobolev training's 1 : 1 (Czarnecki et al. 2017).
|
|
420
|
+
self.slope_w = 0.0
|
|
421
|
+
self._slope = None
|
|
422
|
+
|
|
423
|
+
def get_alpha(self):
|
|
424
|
+
return self.log_alpha.exp()
|
|
425
|
+
|
|
426
|
+
def latent_beta(self, epoch):
|
|
427
|
+
"""The KL weight at `epoch` (the step schedule set in __init__)."""
|
|
428
|
+
k = min(int(epoch) // self.latent_beta_every, self.latent_beta_steps)
|
|
429
|
+
return self.latent_beta_start + (self.latent_beta_end - self.latent_beta_start) * k / self.latent_beta_steps
|
|
430
|
+
|
|
431
|
+
def _load_frozen_latent_model(self, path, activation):
|
|
432
|
+
"""The task phase's frozen parts from a latent skill model checkpoint (P2, DN_LATENT=1): the decoder (saved as
|
|
433
|
+
`actor`), the encoder (only its prior is used) and the observation normaliser both were trained on. Shapes are
|
|
434
|
+
checked against this env; a checkpoint without the latent model is refused."""
|
|
435
|
+
assert path, "latent_task=True needs latent_task_ckpt, the latent skill model checkpoint it drives"
|
|
436
|
+
ck = torch.load(path, map_location=self.device, weights_only=False)
|
|
437
|
+
assert "latent_task" not in ck, f"{path} is a task-phase checkpoint; give the latent model checkpoint it drove"
|
|
438
|
+
assert "latent" in ck and "latent_cfg" in ck and "ref_rms" in ck, (
|
|
439
|
+
f"{path} is not a latent skill model checkpoint (DN_LATENT=1 saves latent / ref_rms / latent_cfg)")
|
|
440
|
+
cfg = dict(ck["latent_cfg"])
|
|
441
|
+
Z = int(cfg["dim"])
|
|
442
|
+
assert int(cfg["num_obs"]) == self.num_obs, (
|
|
443
|
+
f"{path} was trained on {cfg['num_obs']} observations, this env gives {self.num_obs}")
|
|
444
|
+
sd = ck["actor"]
|
|
445
|
+
n_layers = sum(1 for k in sd if k.startswith("layers.") and k.endswith(".weight"))
|
|
446
|
+
units = [int(sd[f"layers.{k}.weight"].shape[0]) for k in range(n_layers)]
|
|
447
|
+
assert n_layers >= 1 and int(sd["layers.0.weight"].shape[1]) == self.num_obs + Z, (
|
|
448
|
+
"the checkpoint's actor is not a latent decoder reading [obs, z]", n_layers)
|
|
449
|
+
assert tuple(sd["mu.weight"].shape) == (self.num_actions, units[-1] + Z), (
|
|
450
|
+
f"the decoder emits {tuple(sd['mu.weight'].shape)}, this env takes {self.num_actions} actions")
|
|
451
|
+
dec = ActorSquashedLatentMLP(self.num_obs, Z, self.num_actions, units=units, activation=activation,
|
|
452
|
+
device=self.device)
|
|
453
|
+
dec.load_state_dict(sd)
|
|
454
|
+
enc = LatentSkillEncoder(self.num_obs, int(cfg["num_ref_obs"]), latent_dim=Z, units=tuple(cfg["units"]),
|
|
455
|
+
sigma=float(cfg["sigma"]), activation="elu", device=self.device)
|
|
456
|
+
enc.load_state_dict(ck["latent"])
|
|
457
|
+
for m in (dec, enc):
|
|
458
|
+
m.requires_grad_(False)
|
|
459
|
+
m.eval()
|
|
460
|
+
self.ltask_decoder, self.ltask_encoder = dec, enc
|
|
461
|
+
r = ck["obs_rms"] # frozen: the task phase never updates it (compute_actor_loss)
|
|
462
|
+
self.obs_rms.mean, self.obs_rms.var, self.obs_rms.count = r["mean"].to(self.device), r["var"].to(self.device), r["count"]
|
|
463
|
+
self._ltask_rms0 = (self.obs_rms.mean.clone(), self.obs_rms.var.clone())
|
|
464
|
+
self._ltask_latent_cfg, self._ltask_dec_units, self._ltask_src_epoch = cfg, units, ck.get("epoch")
|
|
465
|
+
print(f"[latent-task] frozen decoder {units} + prior {list(cfg['units'])} (z {Z}, sigma {cfg['sigma']}) from {path} "
|
|
466
|
+
f"(ep{ck.get('epoch')})", flush=True)
|
|
467
|
+
|
|
468
|
+
def latent_task_state(self):
|
|
469
|
+
"""Checkpoint entries of the task phase beyond the task policy (saved as `actor`): the frozen decoder and encoder
|
|
470
|
+
as they were loaded (so a resume or an eval can verify it drives the same model) and the configuration."""
|
|
471
|
+
return {"latent_task": {"decoder": self.ltask_decoder.state_dict(), "encoder": self.ltask_encoder.state_dict()},
|
|
472
|
+
"latent_task_cfg": dict(self.ltask_cfg)}
|
|
473
|
+
|
|
474
|
+
def load_latent_task_state(self, ck):
|
|
475
|
+
"""A task-phase checkpoint (resume / eval): its configuration must match, and its frozen decoder, encoder and
|
|
476
|
+
observation normaliser must be the ones this run loaded from latent_task_ckpt, bit for bit."""
|
|
477
|
+
assert "latent_task" in ck and "latent_task_cfg" in ck, (
|
|
478
|
+
"a latent-task run resumes or evaluates only a checkpoint saved by one (keys latent_task / latent_task_cfg)")
|
|
479
|
+
c = ck["latent_task_cfg"]
|
|
480
|
+
for k in ("latent_cfg", "decoder_units", "units", "num_task_obs", "activation"):
|
|
481
|
+
assert c[k] == self.ltask_cfg[k], (k, c[k], self.ltask_cfg[k])
|
|
482
|
+
for name, mod in (("decoder", self.ltask_decoder), ("encoder", self.ltask_encoder)):
|
|
483
|
+
saved = ck["latent_task"][name]
|
|
484
|
+
assert sorted(saved) == sorted(mod.state_dict()), name
|
|
485
|
+
for k, v in mod.state_dict().items():
|
|
486
|
+
assert torch.equal(v, saved[k].to(v.device)), (
|
|
487
|
+
f"the checkpoint's frozen {name} ({k}) is not the one in {self.ltask_cfg['source']}")
|
|
488
|
+
r = ck["obs_rms"]
|
|
489
|
+
assert torch.equal(r["mean"].to(self.device), self._ltask_rms0[0]) and torch.equal(
|
|
490
|
+
r["var"].to(self.device), self._ltask_rms0[1]), "the checkpoint's observation normaliser is not the frozen one"
|
|
491
|
+
|
|
492
|
+
@torch.no_grad()
|
|
493
|
+
def act(self, obs_raw, deterministic=True, ref_raw=None, task_raw=None):
|
|
494
|
+
"""Eval action (PRE-tanh, the harness squashes it). With the latent model, z depends on latent_eval_mode:
|
|
495
|
+
"tracking" = the posterior mean given the env's next-reference block `ref_raw` (env.latent_ref_obs()),
|
|
496
|
+
"generation" = z sampled from the prior p(z | s); the reference is then not read at all. In the task phase z is
|
|
497
|
+
mu_p(s) + mu_g(s, g) for the env's command block `task_raw` (env.latent_task_obs()), plus sigma_g noise when not
|
|
498
|
+
deterministic, decoded by the frozen decoder."""
|
|
499
|
+
if self.ltask:
|
|
500
|
+
assert task_raw is not None and ref_raw is None, "the task phase reads the command block (env.latent_task_obs())"
|
|
501
|
+
obs = self.obs_rms.normalize(obs_raw)
|
|
502
|
+
z = self.ltask_encoder.prior_mean(obs) + self.actor(obs, task_raw)
|
|
503
|
+
if not deterministic:
|
|
504
|
+
z = z + self.ltask_sigma * torch.randn_like(z)
|
|
505
|
+
return self.ltask_decoder(obs, z, deterministic=deterministic)
|
|
506
|
+
assert task_raw is None, "task_raw is the latent task policy's input; this policy has none"
|
|
507
|
+
if self.latent is None:
|
|
508
|
+
assert ref_raw is None, "ref_raw is the latent model's input; this policy has none"
|
|
509
|
+
return super().act(obs_raw, deterministic=deterministic)
|
|
510
|
+
obs = self.obs_rms.normalize(obs_raw)
|
|
511
|
+
if self.latent_eval_mode == "tracking":
|
|
512
|
+
assert ref_raw is not None, "tracking mode needs the next-reference block (env.latent_ref_obs())"
|
|
513
|
+
z = self.latent.posterior_mean(obs, self.ref_rms.normalize(ref_raw))
|
|
514
|
+
if self.latent_kl_trace is not None:
|
|
515
|
+
self.latent_kl_trace.append(self.latent.kl(z - self.latent.prior_mean(obs)))
|
|
516
|
+
else:
|
|
517
|
+
assert self.latent_eval_mode == "generation", self.latent_eval_mode
|
|
518
|
+
assert ref_raw is None, "generation mode must not read the reference"
|
|
519
|
+
z = self.latent.sample_prior(obs)
|
|
520
|
+
return self.actor(obs, z, deterministic=deterministic)
|
|
521
|
+
|
|
522
|
+
def latent_state(self):
|
|
523
|
+
"""Checkpoint entries of the latent model beyond the decoder (saved as `actor`): the encoder (prior +
|
|
524
|
+
posterior), the next-reference normaliser and the shapes needed to rebuild them."""
|
|
525
|
+
return {"latent": self.latent.state_dict(), "ref_rms": self.ref_rms.state_dict(),
|
|
526
|
+
"latent_cfg": dict(self.latent_cfg)}
|
|
527
|
+
|
|
528
|
+
def load_latent_state(self, ck):
|
|
529
|
+
assert "latent" in ck and "ref_rms" in ck and "latent_cfg" in ck, (
|
|
530
|
+
"a latent run needs a checkpoint saved by one (keys latent / ref_rms / latent_cfg)")
|
|
531
|
+
assert ck["latent_cfg"] == self.latent_cfg, (ck["latent_cfg"], self.latent_cfg)
|
|
532
|
+
self.latent.load_state_dict(ck["latent"])
|
|
533
|
+
r = ck["ref_rms"]
|
|
534
|
+
self.ref_rms.mean = r["mean"].to(self.device)
|
|
535
|
+
self.ref_rms.var = r["var"].to(self.device)
|
|
536
|
+
self.ref_rms.count = r["count"]
|
|
537
|
+
|
|
538
|
+
def _action_noise(self):
|
|
539
|
+
"""The rollout step's two standard-normal draws, made eagerly (CAPTURE_PLAN.md P2), so a captured step can take them as
|
|
540
|
+
inputs: (eps_a (N, A) for the action, eps_e (1, N, A) for the entropy's single draw), with exactly the calls
|
|
541
|
+
Normal.rsample makes inside rsample() and entropy() (torch.distributions.utils._standard_normal), in that order. (None,
|
|
542
|
+
None) for an actor other than ActorSquashedMLP, which keeps drawing inside its distribution."""
|
|
543
|
+
if not isinstance(self.actor, ActorSquashedMLP):
|
|
544
|
+
return None, None
|
|
545
|
+
from torch.distributions.utils import _standard_normal
|
|
546
|
+
p = self.actor.mu.weight
|
|
547
|
+
shape = (self.num_envs, self.actor.act_dim)
|
|
548
|
+
eps_a = _standard_normal(shape, dtype=p.dtype, device=p.device)
|
|
549
|
+
eps_e = _standard_normal((1, *shape), dtype=p.dtype, device=p.device)
|
|
550
|
+
return eps_a, eps_e
|
|
551
|
+
|
|
552
|
+
def _ent_norm(self, ent):
|
|
553
|
+
# normalized entropy ~[0,1]: offset by |H_bar| then scale by 1/(2|H_bar|). Applied identically in
|
|
554
|
+
# the actor return and the critic target so alpha carries the same units in both. Written as ent - H_bar, which is the
|
|
555
|
+
# default's ent + |H_bar| exactly (H_bar = -|H_bar|) and puts an entropy block's bonus at 0 on its own target.
|
|
556
|
+
return (ent - self.target_entropy) / (2.0 * self._abs_H)
|
|
557
|
+
|
|
558
|
+
def _env_action(self, actions):
|
|
559
|
+
# SAPO's actor already emits a squashed action in [-1,1] (SquashedNormal.rsample), so feed it to the
|
|
560
|
+
# env DIRECTLY. A second tanh (the ShacVec default) would double-squash. Synergy prior is unused.
|
|
561
|
+
return actions
|
|
562
|
+
|
|
563
|
+
def compute_actor_loss(self):
|
|
564
|
+
if not self.freeze_critic_bptt:
|
|
565
|
+
return self._compute_actor_loss()
|
|
566
|
+
ps = [p for p in self.critic.parameters() if p.requires_grad]
|
|
567
|
+
for p in ps: # 4e: the window's graph is built without the critic's weight gradients
|
|
568
|
+
p.requires_grad_(False)
|
|
569
|
+
loss = self._compute_actor_loss()
|
|
570
|
+
for p in ps:
|
|
571
|
+
p.requires_grad_(True)
|
|
572
|
+
return loss
|
|
573
|
+
|
|
574
|
+
def _compute_actor_loss(self):
|
|
575
|
+
self._rag_max_gpu.zero_() # reset raw action-grad monitor for this window
|
|
576
|
+
self._rag_nonfinite_gpu.zero_()
|
|
577
|
+
rew_acc = torch.zeros((self.steps_num + 1, self.num_envs), device=self.device)
|
|
578
|
+
gamma = torch.ones(self.num_envs, device=self.device)
|
|
579
|
+
next_values = torch.zeros((self.steps_num + 1, self.num_envs), device=self.device) # AVG critic (actor bootstrap)
|
|
580
|
+
next_values_min = torch.zeros((self.steps_num + 1, self.num_envs), device=self.device) # MIN critic (critic target)
|
|
581
|
+
actor_loss = torch.zeros((), device=self.device)
|
|
582
|
+
n_cut_gpu = torch.zeros((), device=self.device) # per-env-cut diagnostic (GPU-accumulated, one sync/epoch)
|
|
583
|
+
|
|
584
|
+
alpha = self.get_alpha().detach() # normalized-scale temperature (detached in the return)
|
|
585
|
+
|
|
586
|
+
rms = copy.deepcopy(self.obs_rms) # frozen normalization for this window
|
|
587
|
+
obs = self.env.initialize_trajectory() # detach state at the window boundary
|
|
588
|
+
slope = self._slope is not None
|
|
589
|
+
if slope: # the states, discounts and mirror flips the slope targets need
|
|
590
|
+
self._slope_states, self._slope_disc, self._slope_flip, self._slope_steps, self._slope_prev = [], [], [], [], []
|
|
591
|
+
prev = None # (reward, its discount) of the previous step: it is computed FROM s_i
|
|
592
|
+
self._slope_sig = torch.sqrt(rms.var + 1e-5)[self._slope["idx"]] # this window's normaliser at the raw slots
|
|
593
|
+
ret_only = torch.zeros((), device=self.device)
|
|
594
|
+
flip_next = self.env.slope_obs_flip()
|
|
595
|
+
ks_w = 0.0 if self._ks_teacher is None else (
|
|
596
|
+
self._ks_w_end + (self._ks_w0 - self._ks_w_end) * max(0.0, 1.0 - self._ks_epoch / self._ks_epochs))
|
|
597
|
+
ks_raw = obs if ks_w > 0.0 else None # the teacher normalises the RAW obs with its own obs_rms
|
|
598
|
+
ks_acc = torch.zeros((), device=self.device)
|
|
599
|
+
lt = self.ltask
|
|
600
|
+
if not lt: # the task phase keeps the frozen model's normaliser as it was trained
|
|
601
|
+
self.obs_rms.update(obs)
|
|
602
|
+
obs = rms.normalize(obs)
|
|
603
|
+
lat = self.latent is not None
|
|
604
|
+
if lat: # the posterior's next-reference block, normalised like obs
|
|
605
|
+
beta = self.last_beta
|
|
606
|
+
rrms = copy.deepcopy(self.ref_rms)
|
|
607
|
+
ref = self.env.latent_ref_obs()
|
|
608
|
+
self.ref_rms.update(ref)
|
|
609
|
+
ref = rrms.normalize(ref)
|
|
610
|
+
if lt: # the command block [v*, cos, sin] (O(1) already, read raw as in the
|
|
611
|
+
g = self.env.latent_task_obs() # released code), in the graph through the root yaw
|
|
612
|
+
self._window_states = None
|
|
613
|
+
self._grad_order = []
|
|
614
|
+
for i in range(self.steps_num):
|
|
615
|
+
if slope and 1 <= i <= self._slope["t_max"]: # s_i is the state the previous step produced (in the graph)
|
|
616
|
+
self._slope_states.append([getattr(self.env, a) for a, _, _, _ in self._slope["slots"]])
|
|
617
|
+
self._slope_disc.append(gamma.clone()) # gamma^(i - sub-window start): the weight r_i enters with
|
|
618
|
+
self._slope_flip.append(flip_next)
|
|
619
|
+
self._slope_steps.append(i)
|
|
620
|
+
self._slope_prev.append(prev)
|
|
621
|
+
g_top = gamma
|
|
622
|
+
if self._window_states is not None:
|
|
623
|
+
e = self.env
|
|
624
|
+
self._window_states.append({k: getattr(e, k).detach().clone() for k in ("q", "qd", "lce", "a", "z", "_tw_normals")
|
|
625
|
+
if isinstance(getattr(e, k, None), torch.Tensor)})
|
|
626
|
+
self.obs_buf[i] = obs.detach()
|
|
627
|
+
if ks_w > 0.0: # kickstart: student mean vs teacher mean at this visited state
|
|
628
|
+
with torch.no_grad():
|
|
629
|
+
t_mu = self._ks_teacher.mu(self._ks_teacher.feature_net((ks_raw.detach() - self._ks_mean) / self._ks_std))
|
|
630
|
+
s_mu = self.actor.mu(self.actor.feature_net(obs.detach()))
|
|
631
|
+
ks_acc = ks_acc + ((s_mu - t_mu) ** 2).mean(-1).sum()
|
|
632
|
+
eps_a = eps_e = None # the latent branches keep drawing inside rsample() / entropy()
|
|
633
|
+
if lat: # z ~ q(z | s, s~') (reparameterised), then pi(a | s, z)
|
|
634
|
+
self.ref_buf[i] = ref.detach()
|
|
635
|
+
z, kl = self.latent.sample_posterior(obs, ref)
|
|
636
|
+
pm = None
|
|
637
|
+
if self.latent_prior_frac > 0.0: # prior steps (see __init__)
|
|
638
|
+
pm = torch.rand(self.num_envs, device=self.device) < self.latent_prior_frac
|
|
639
|
+
z = torch.where(pm[:, None], self.latent.sample_prior(obs).detach(), z)
|
|
640
|
+
kl = torch.where(pm, torch.zeros_like(kl), kl)
|
|
641
|
+
dist = self.actor.distribution(obs, z)
|
|
642
|
+
elif lt: # z ~ N(mu_p(s) + mu_g(s, g), sigma_g^2 I) (reparameterised), then the
|
|
643
|
+
self.task_buf[i] = g.detach() # FROZEN pi(a | s, z): its weights get no gradient, z and mu_g do
|
|
644
|
+
off = self.actor(obs, g)
|
|
645
|
+
z = self.ltask_encoder.prior_mean(obs) + off + self.ltask_sigma * torch.randn_like(off)
|
|
646
|
+
offsq = (off * off).sum(-1) # ||mu_g||^2 per env; MuscleVAE charges w_z of it
|
|
647
|
+
dist = self.ltask_decoder.distribution(obs, z)
|
|
648
|
+
else:
|
|
649
|
+
# the action noise drawn here, eagerly, and passed in (CAPTURE_PLAN.md P2): the same two standard-normal draws, in
|
|
650
|
+
# the same order and shapes, as dist.rsample() and dist.entropy() made on the default generator (nothing between
|
|
651
|
+
# the old and the new place draws from it), so the actions and the entropy are bitwise to before
|
|
652
|
+
eps_a, eps_e = self._action_noise()
|
|
653
|
+
dist = self.actor.distribution(obs)
|
|
654
|
+
actions = dist.rsample_eps(eps_a) if eps_a is not None else dist.rsample() # SQUASHED in [-1,1]; reparameterized
|
|
655
|
+
if lat and pm is not None: # a prior step's action moves the state, not the policy
|
|
656
|
+
actions = torch.where(pm[:, None], actions.detach(), actions)
|
|
657
|
+
actions.register_hook(self._action_grad_hook) # monitor the raw pathwise action-grad (the moat signal)
|
|
658
|
+
if lt: # no entropy term in the task phase (__init__)
|
|
659
|
+
ent = torch.zeros(self.num_envs, device=self.device)
|
|
660
|
+
else:
|
|
661
|
+
ent = dist.entropy_eps(eps_e) if eps_e is not None else dist.entropy() # (N, A) single-sample MC entropy per dim
|
|
662
|
+
ent = (ent if self._ent_dims is None else ent[:, self._ent_dims]).sum(-1) # (N,) over the entropy block
|
|
663
|
+
if lat and pm is not None:
|
|
664
|
+
ent = torch.where(pm, ent.detach(), ent)
|
|
665
|
+
if self.decision_every > 1: # PREREG_S290 Amendment 16: only a DECISION step carries the entropy bonus (the
|
|
666
|
+
dec = (self.env.progress % self.decision_every) == 0 # held step's ent = H_bar -> ent_norm 0); the clock before the step
|
|
667
|
+
if self.env._dr_diag != "no_entmask": # (a gate diagnostic only: the entropy unmasked)
|
|
668
|
+
ent = torch.where(dec, ent, torch.full_like(ent, self.target_entropy))
|
|
669
|
+
self.dec_buf[i] = dec.float()
|
|
670
|
+
ent_norm = self._ent_norm(ent) # normalized ~[0,1]
|
|
671
|
+
obs_raw, rew, done, extra = self.env.step(self._env_action(actions))
|
|
672
|
+
if slope:
|
|
673
|
+
flip_next = self.env.slope_obs_flip()
|
|
674
|
+
if self._window_states is not None:
|
|
675
|
+
self._window_states[-1]["action"] = self._env_action(actions).detach().clone()
|
|
676
|
+
self._window_states[-1]["done"] = done.detach().clone()
|
|
677
|
+
# backward-time gradient census of the post-step state: per (step, tensor) the count of envs whose incoming
|
|
678
|
+
# gradient is non-finite and the largest finite |g| per env; the first non-finite in BACKWARD order is the origin
|
|
679
|
+
rec = self._window_states[-1].setdefault("grad", {})
|
|
680
|
+
for _nm in ("q", "qd", "lce", "z"):
|
|
681
|
+
_t = getattr(self.env, _nm, None)
|
|
682
|
+
if isinstance(_t, torch.Tensor) and _t.requires_grad:
|
|
683
|
+
def _hook(g, _nm=_nm, _rec=rec):
|
|
684
|
+
bad = ~torch.isfinite(g).all(dim=0)
|
|
685
|
+
_rec[_nm] = dict(order=len(self._grad_order), bad=bad.detach().clone(),
|
|
686
|
+
gmax=torch.where(torch.isfinite(g), g.abs(), torch.zeros_like(g)).amax(dim=0).detach().clone())
|
|
687
|
+
self._grad_order.append(_nm)
|
|
688
|
+
_t.register_hook(_hook)
|
|
689
|
+
if not lt:
|
|
690
|
+
self.obs_rms.update(obs_raw)
|
|
691
|
+
obs = rms.normalize(obs_raw)
|
|
692
|
+
if ks_w > 0.0:
|
|
693
|
+
ks_raw = obs_raw
|
|
694
|
+
if lat: # the block of the state just returned (post-reset where reset)
|
|
695
|
+
ref = self.env.latent_ref_obs()
|
|
696
|
+
self.ref_rms.update(ref)
|
|
697
|
+
ref = rrms.normalize(ref)
|
|
698
|
+
if lt: # the command block of the state just returned (post-reset where reset)
|
|
699
|
+
g = self.env.latent_task_obs()
|
|
700
|
+
# bootstrap: MIN + AVG in one forward. Actor uses AVG; the critic-target buffer stores MIN.
|
|
701
|
+
if self.one_bootstrap != "1":
|
|
702
|
+
base_min, base_avg = self.target_critic(obs if not (lat or lt) else torch.cat([obs, ref if lat else g], -1),
|
|
703
|
+
return_type="min_and_avg")
|
|
704
|
+
base_min, base_avg = base_min.squeeze(-1), base_avg.squeeze(-1)
|
|
705
|
+
else:
|
|
706
|
+
assert not (lat or lt or self.per_env_cut), "4d' (SAPO_ONE_BOOTSTRAP=1) is built for E0's plain window"
|
|
707
|
+
|
|
708
|
+
# vectorized terminal handling (mirrors ShacVec): non-finite obr -> 0; early-term (fell) -> 0;
|
|
709
|
+
# timeout (ep_end, finite) -> bootstrap. Sanitize obr before the critic so NaN can't poison it.
|
|
710
|
+
obr, ep_end = extra["obs_before_reset"], extra["episode_end"]
|
|
711
|
+
obr_valid = torch.isfinite(obr).all(dim=1) & (obr.abs() <= 1e6).all(dim=1)
|
|
712
|
+
obr_safe = torch.where(obr_valid[:, None], obr, torch.zeros_like(obr))
|
|
713
|
+
obr_c = rms.normalize(obr_safe)
|
|
714
|
+
if lat: # V(s') of a truncated episode reads ITS reference block
|
|
715
|
+
rbr = extra["latent_ref_before_reset"]
|
|
716
|
+
obr_c = torch.cat([obr_c, rrms.normalize(torch.where(obr_valid[:, None], rbr, torch.zeros_like(rbr)))], -1)
|
|
717
|
+
if lt: # V(s', g') of a truncated episode reads ITS command block
|
|
718
|
+
tbr = extra["latent_task_obs_before_reset"]
|
|
719
|
+
obr_c = torch.cat([obr_c, torch.where(obr_valid[:, None], tbr, torch.zeros_like(tbr))], -1)
|
|
720
|
+
to_min, to_avg = self.target_critic(obr_c, return_type="min_and_avg")
|
|
721
|
+
to_min, to_avg = to_min.squeeze(-1), to_avg.squeeze(-1)
|
|
722
|
+
if self.one_bootstrap == "1": # 4d': the non-done envs' V(obs) is V(obs_before_reset)
|
|
723
|
+
# its premise (11-03): every non-done row has a valid obs_before_reset (else it would bootstrap V(0), not
|
|
724
|
+
# V(obs)); a device-side check, no host sync
|
|
725
|
+
torch._assert_async((obr_valid | done).all())
|
|
726
|
+
base_min, base_avg = to_min, to_avg
|
|
727
|
+
elif self.one_bootstrap == "planted": # the gate's control: V(obs) (the post-reset state) for the done envs
|
|
728
|
+
to_min, to_avg, base_min, base_avg = base_min, base_avg, to_min, to_avg
|
|
729
|
+
boot = done & ep_end & obr_valid
|
|
730
|
+
next_values[i + 1] = torch.where(
|
|
731
|
+
done, torch.where(boot, to_avg, torch.zeros_like(base_avg)), base_avg)
|
|
732
|
+
next_values_min[i + 1] = torch.where(
|
|
733
|
+
done, torch.where(boot, to_min, torch.zeros_like(base_min)), base_min)
|
|
734
|
+
|
|
735
|
+
# per-env AHAC cut (opt-in): stiffness (contact-impulse norm) > pec_C is a per-env TRUNCATION.
|
|
736
|
+
# cut envs finalize with the V(s') bootstrap (== base_avg, already the non-done value at line
|
|
737
|
+
# above), reset the sub-window (gamma/rew_acc), and get their obs DETACHED so the pathwise
|
|
738
|
+
# gradient stops here -- the env keeps rolling physically (no reset), only the gradient truncates.
|
|
739
|
+
# Each env thus gets its OWN effective BPTT length (its stiff step), within the fixed window.
|
|
740
|
+
# done_eff folds cut into the existing per-env done handling; per_env_cut=False => done_eff==done
|
|
741
|
+
# (byte-identical). This is the vectorizable form of AHAC-1 (per-env cut) via per-env graph detach.
|
|
742
|
+
if self.per_env_cut:
|
|
743
|
+
cut = (extra["cfnorm"] > self.pec_C) & ~done # real done handled by `done`'s own bootstrap
|
|
744
|
+
done_eff = done | cut
|
|
745
|
+
n_cut_gpu = n_cut_gpu + cut.sum()
|
|
746
|
+
else:
|
|
747
|
+
cut = None
|
|
748
|
+
done_eff = done
|
|
749
|
+
|
|
750
|
+
if slope:
|
|
751
|
+
prev = (rew, g_top)
|
|
752
|
+
if lt: # the task phase: w_z ||mu_g||^2 per step, discounted like the reward;
|
|
753
|
+
rew_aug = rew - self.ltask_wz * offsq # no entropy term
|
|
754
|
+
else:
|
|
755
|
+
rew_aug = rew + alpha * ent_norm # entropy-augmented reward (differentiable via ent)
|
|
756
|
+
if lat: # the KL bottleneck, a per-step cost discounted like the reward
|
|
757
|
+
rew_aug = rew_aug - beta * kl
|
|
758
|
+
rew_acc[i + 1] = rew_acc[i] + gamma * rew_aug
|
|
759
|
+
if i < self.steps_num - 1: # finalize returns for just-terminated/cut envs (masked sum)
|
|
760
|
+
actor_loss = actor_loss + ((-rew_acc[i + 1] - self.gamma * gamma * next_values[i + 1]) * done_eff.float()).sum()
|
|
761
|
+
if slope: # the same sub-window returns WITHOUT the bootstrap
|
|
762
|
+
ret_only = ret_only + (-rew_acc[i + 1] * done_eff.float()).sum()
|
|
763
|
+
else: # truncate-bootstrap all envs at window end
|
|
764
|
+
actor_loss = actor_loss + (-rew_acc[i + 1] - self.gamma * gamma * next_values[i + 1]).sum()
|
|
765
|
+
if slope:
|
|
766
|
+
ret_only = ret_only + (-rew_acc[i + 1]).sum()
|
|
767
|
+
gamma = torch.where(done_eff, torch.ones_like(gamma), gamma * self.gamma)
|
|
768
|
+
rew_acc[i + 1] = torch.where(done_eff, torch.zeros_like(rew_acc[i + 1]), rew_acc[i + 1])
|
|
769
|
+
if cut is not None: # per-env BPTT truncation at this step:
|
|
770
|
+
self.env.detach_envs(cut) # (1) detach the ENV STATE (q/qd/lce/z/a) = the dynamics BPTT carrier
|
|
771
|
+
obs = torch.where(cut[:, None], obs.detach(), obs) # (2) detach the trainer's obs = the actor-input path
|
|
772
|
+
if lat: # (3) and the posterior's block, which reads the root state
|
|
773
|
+
ref = torch.where(cut[:, None], ref.detach(), ref)
|
|
774
|
+
if lt: # (3') or the command block, which reads the root yaw
|
|
775
|
+
g = torch.where(cut[:, None], g.detach(), g)
|
|
776
|
+
# (no `cut.any()` guard: it is a host read of a device tensor == a sync every step; both
|
|
777
|
+
# operations below are already masked no-ops when nothing is cut. See detach_envs.)
|
|
778
|
+
|
|
779
|
+
with torch.no_grad(): # data for the critic regression + alpha dual
|
|
780
|
+
self.rew_buf[i] = rew # RAW reward (entropy re-added in the entropy target)
|
|
781
|
+
# done_mask drives the CRITIC's td-lambda recursion, which is a separate question from the
|
|
782
|
+
# actor's pathwise truncation. Folding cut in here makes a cut step reset `lam`, so at a
|
|
783
|
+
# firing rate of ~20% the critic target collapses toward TD(0) -- extra bootstrap bias
|
|
784
|
+
# exactly while the critic is still learning, and a confound when comparing two pec_C
|
|
785
|
+
# values (they then differ in critic bias as well as in gradient horizon). Default: cut
|
|
786
|
+
# truncates the GRADIENT only. Set pec_cut_critic=True to restore the coupled behavior.
|
|
787
|
+
cut_mask = done_eff if self.pec_cut_critic else done
|
|
788
|
+
self.done_mask[i] = cut_mask.float() if i < self.steps_num - 1 else torch.ones(self.num_envs, device=self.device)
|
|
789
|
+
self.next_values[i] = next_values_min[i + 1] # MIN critic -> critic-target bootstrap
|
|
790
|
+
self.ent_raw_buf[i] = ent.detach() # raw MC entropy (target + alpha loss)
|
|
791
|
+
if lat:
|
|
792
|
+
self.kl_buf[i] = kl.detach() # the KL re-enters the critic target like the entropy
|
|
793
|
+
if lt:
|
|
794
|
+
self.offsq_buf[i] = offsq.detach() # and so does the task phase's w_z ||mu_g||^2
|
|
795
|
+
|
|
796
|
+
if ks_w > 0.0:
|
|
797
|
+
actor_loss = actor_loss + ks_w * ks_acc
|
|
798
|
+
self.last_ks_mse = float(ks_acc.detach()) / (self.steps_num * self.num_envs); self.last_ks_w = ks_w
|
|
799
|
+
elif self._ks_teacher is not None:
|
|
800
|
+
self.last_ks_w = 0.0
|
|
801
|
+
actor_loss = actor_loss / (self.steps_num * self.num_envs)
|
|
802
|
+
if slope:
|
|
803
|
+
self._slope_ret = ret_only
|
|
804
|
+
self.step_count += self.steps_num * self.num_envs
|
|
805
|
+
self.last_cut_frac = (n_cut_gpu / (self.steps_num * self.num_envs)).item() if self.per_env_cut else 0.0
|
|
806
|
+
return actor_loss
|
|
807
|
+
|
|
808
|
+
def _slope_targets(self):
|
|
809
|
+
"""The critic-slope targets of this window (SAPO_CRITIC_SLOPE_W): one backward of the return-only loss to the recorded states
|
|
810
|
+
s_i, i = 1 .. H // 2, before the actor's backward frees the graph. ret_only = -sum over sub-windows of sum_u gamma^(u - start)
|
|
811
|
+
(r_u + alpha ent_u). Of the rewards before s_i only r_(i-1) depends on it (the env computes a step's reward from the state the
|
|
812
|
+
step produced), so the slope of the soft return from s_i is g_i = (-dret_only/ds_i - disc_(i-1) dr_(i-1)/ds_i) / disc_i. It
|
|
813
|
+
passes through the policy at every later step, so d pi / d s is in it, and through training's per-env action-gradient cap,
|
|
814
|
+
so it is the slope of the CLIPPED closed loop (the cap's raw-gradient monitor also sees this backward). Placed in the
|
|
815
|
+
pre-mirror obs layout, mapped through the mirror the obs went through, kept at the raw slots; a non-finite target is masked
|
|
816
|
+
out. tests/test_sapo_critic_slope.py checks it against a closed-loop finite difference."""
|
|
817
|
+
S = self._slope
|
|
818
|
+
flat = [x for st in self._slope_states for x in st]
|
|
819
|
+
g = torch.autograd.grad(self._slope_ret, flat, retain_graph=True, allow_unused=True)
|
|
820
|
+
self.slope_tgt.zero_()
|
|
821
|
+
self.slope_mask.zero_()
|
|
822
|
+
k = len(S["slots"])
|
|
823
|
+
for j, i in enumerate(self._slope_steps):
|
|
824
|
+
# the env's reward of step i - 1 is computed from the state that step produced, s_i, so dret_only/ds_i also holds
|
|
825
|
+
# -disc_(i-1) dr_(i-1)/ds_i, which V(s_i) does not contain: removed by one small backward (r_(i-1) reaches s_i only
|
|
826
|
+
# inside step i - 1's own post-step computation)
|
|
827
|
+
r_prev, d_prev = self._slope_prev[j]
|
|
828
|
+
gp = torch.autograd.grad(r_prev.sum(), self._slope_states[j], retain_graph=True, allow_unused=True)
|
|
829
|
+
gf = torch.zeros((self.num_envs, self.num_obs), device=self.device)
|
|
830
|
+
for (_, r0, s0, n), gi, gpi in zip(S["slots"], g[j * k:(j + 1) * k], gp):
|
|
831
|
+
tot = torch.zeros((n, self.num_envs), device=self.device) # -dret_only/ds_i - disc_(i-1) dr_(i-1)/ds_i
|
|
832
|
+
if gi is not None:
|
|
833
|
+
tot = tot - gi[r0:r0 + n].to(tot.dtype)
|
|
834
|
+
if gpi is not None:
|
|
835
|
+
tot = tot - d_prev[None, :] * gpi[r0:r0 + n].to(tot.dtype)
|
|
836
|
+
gf[:, s0:s0 + n] = tot.t()
|
|
837
|
+
gf = gf / self._slope_disc[j][:, None]
|
|
838
|
+
tgt = self.env.slope_to_obs(gf, self._slope_flip[j])[:, S["idx"]]
|
|
839
|
+
ok = torch.isfinite(tgt).all(dim=1)
|
|
840
|
+
self.slope_tgt[i] = torch.where(ok[:, None], tgt, torch.zeros_like(tgt))
|
|
841
|
+
self.slope_mask[i] = ok
|
|
842
|
+
self._slope_states = self._slope_flip = self._slope_prev = None # drop the graph references
|
|
843
|
+
self._slope_ret = None
|
|
844
|
+
|
|
845
|
+
@torch.no_grad()
|
|
846
|
+
def compute_target_values_with_entropy(self):
|
|
847
|
+
"""ShacVec.compute_target_values but with the entropy-augmented reward rew_buf + alpha*ent_norm in
|
|
848
|
+
BOTH the Ai and Bi recursions, and self.next_values already holding the MIN critic bootstrap."""
|
|
849
|
+
alpha = self.get_alpha().detach()
|
|
850
|
+
ent_norm = self._ent_norm(self.ent_raw_buf) # (S,N) normalized entropy
|
|
851
|
+
Ai = torch.zeros(self.num_envs, device=self.device)
|
|
852
|
+
Bi = torch.zeros(self.num_envs, device=self.device)
|
|
853
|
+
lam = torch.ones(self.num_envs, device=self.device)
|
|
854
|
+
for i in reversed(range(self.steps_num)):
|
|
855
|
+
lam = lam * self.lam * (1.0 - self.done_mask[i]) + self.done_mask[i]
|
|
856
|
+
if self.ltask: # the same w_z ||mu_g||^2 the actor's return charged; no
|
|
857
|
+
rew = self.rew_buf[i] - self.ltask_wz * self.offsq_buf[i] # entropy term
|
|
858
|
+
else:
|
|
859
|
+
rew = self.rew_buf[i] + alpha * ent_norm[i]
|
|
860
|
+
if self.latent is not None: # the same -beta KL the actor's return charged
|
|
861
|
+
rew = rew - self.last_beta * self.kl_buf[i]
|
|
862
|
+
Ai = (1.0 - self.done_mask[i]) * (self.lam * self.gamma * Ai + self.gamma * self.next_values[i]
|
|
863
|
+
+ (1.0 - lam) / (1.0 - self.lam) * rew)
|
|
864
|
+
Bi = self.gamma * (self.next_values[i] * self.done_mask[i] + Bi * (1.0 - self.done_mask[i])) + rew
|
|
865
|
+
self.target_values[i] = (1.0 - self.lam) * Ai + lam * Bi
|
|
866
|
+
|
|
867
|
+
def enable_critic_overlap(self):
|
|
868
|
+
assert self._e5 is None
|
|
869
|
+
self._e5 = CriticOverlap()
|
|
870
|
+
print("[critic overlap] on: alpha, targets and the critic on a side stream during the actor's backward", flush=True)
|
|
871
|
+
|
|
872
|
+
def train_critic(self, defer=False):
|
|
873
|
+
# Both critics regress to the SAME target_values (min-bootstrapped, entropy-augmented TD(lambda));
|
|
874
|
+
# the loss is the mean over the ensemble of the per-critic MSEs.
|
|
875
|
+
S = self.steps_num # AHAC: only the currently-active rows (== full buffer when fixed-H)
|
|
876
|
+
obs = self.obs_buf[:S].reshape(-1, self.num_obs)
|
|
877
|
+
if self.latent is not None: # the critic reads [obs, next-reference block]
|
|
878
|
+
obs = torch.cat([obs, self.ref_buf[:S].reshape(-1, self.num_ref_obs)], -1)
|
|
879
|
+
if self.ltask: # the task phase's critic reads [obs, command block]
|
|
880
|
+
obs = torch.cat([obs, self.task_buf[:S].reshape(-1, self.num_task_obs)], -1)
|
|
881
|
+
tgt = self.target_values[:S].reshape(-1)
|
|
882
|
+
n = obs.shape[0]
|
|
883
|
+
bs = self.num_envs * S // self.num_batch # recompute for the current horizon (== self.batch_size when fixed-H)
|
|
884
|
+
value_loss = 0.0
|
|
885
|
+
if self._slope is not None: # CRITIC SLOPE: the raw-unit slope target, its mask and its scale
|
|
886
|
+
s_idx = self._slope["idx"]
|
|
887
|
+
s_tgt = self.slope_tgt[:S].reshape(n, -1)
|
|
888
|
+
s_m = self.slope_mask[:S].reshape(n)
|
|
889
|
+
assert bool(s_m.any()), "no finite slope target in this window"
|
|
890
|
+
s_g2 = (s_tgt[s_m] ** 2).sum(1).mean()
|
|
891
|
+
s_scale = self.slope_w * tgt.var() / s_g2.clamp_min(1e-30) # relative slope error x the TD target's variance
|
|
892
|
+
s_acc = torch.zeros(5, device=self.device) # sums of |err|^2, <dV, g>, |dV|^2, |g|^2 and the count (on device)
|
|
893
|
+
for _ in range(self.critic_iterations):
|
|
894
|
+
perm = torch.randperm(n, device=self.device)
|
|
895
|
+
# the epoch loss is summed ON THE DEVICE in float64: loss.item() per minibatch synchronized the host with the
|
|
896
|
+
# GPU every minibatch, draining the launch queue each time (nsys, perf-log 2026-10-28). The same float32 values
|
|
897
|
+
# added in the same order in float64 are what the Python float sum computed, so value_loss is unchanged.
|
|
898
|
+
ep_loss, nb = torch.zeros((), dtype=torch.float64, device=self.device), 0
|
|
899
|
+
for s in range(0, n, bs):
|
|
900
|
+
idx = perm[s:s + bs]
|
|
901
|
+
self.critic_opt.zero_grad()
|
|
902
|
+
if self._slope is None:
|
|
903
|
+
pred = self.critic(obs[idx], return_type="all").squeeze(-1) # (n_critics, B)
|
|
904
|
+
loss = ((pred - tgt[idx][None, :]) ** 2).mean() # mean over critics + batch
|
|
905
|
+
else:
|
|
906
|
+
ob = obs[idx].detach().requires_grad_(True)
|
|
907
|
+
pred = self.critic(ob, return_type="all").squeeze(-1)
|
|
908
|
+
loss = ((pred - tgt[idx][None, :]) ** 2).mean()
|
|
909
|
+
m = s_m[idx].float()
|
|
910
|
+
gl = torch.zeros((), device=self.device)
|
|
911
|
+
for h in range(pred.shape[0]): # each head's raw-unit slope at the slots
|
|
912
|
+
gh = torch.autograd.grad(pred[h].sum(), ob, create_graph=True)[0][:, s_idx] / self._slope_sig
|
|
913
|
+
gl = gl + ((((gh - s_tgt[idx]) ** 2).sum(1) * m).sum() / m.sum().clamp_min(1.0))
|
|
914
|
+
with torch.no_grad():
|
|
915
|
+
gd, td = gh.detach() * m[:, None], s_tgt[idx] * m[:, None]
|
|
916
|
+
s_acc += torch.stack([((gd - td) ** 2).sum(), (gd * td).sum(), (gd ** 2).sum(), (td ** 2).sum(), m.sum()])
|
|
917
|
+
loss = loss + s_scale * gl / pred.shape[0]
|
|
918
|
+
loss.backward()
|
|
919
|
+
for p in self.critic.parameters():
|
|
920
|
+
p.grad.nan_to_num_(0.0, 0.0, 0.0)
|
|
921
|
+
clip_grad_norm_(self.critic.parameters(), self.grad_norm)
|
|
922
|
+
self.critic_opt.step()
|
|
923
|
+
ep_loss = ep_loss + loss.detach().double()
|
|
924
|
+
nb += 1
|
|
925
|
+
value_loss = ep_loss / nb
|
|
926
|
+
if self._slope is not None: # this epoch's TRAIN-batch slope error (held-out: critic_slope_gates.py)
|
|
927
|
+
e, d, nv, nt, c = s_acc.tolist()
|
|
928
|
+
self.last_slope = dict(rel_err=e / max(nt, 1e-30), cos=d / max(math.sqrt(nv * nt), 1e-30),
|
|
929
|
+
slope_norm=math.sqrt(nv / max(c, 1.0)), target_norm=math.sqrt(nt / max(c, 1.0)), scale=float(s_scale))
|
|
930
|
+
return value_loss if defer else float(value_loss) # defer: CriticOverlap.join takes the host read
|
|
931
|
+
|
|
932
|
+
def _update_alpha(self, defer=False):
|
|
933
|
+
"""Dual step on the temperature. The return used alpha on the SCALED entropy, so un-scale it back
|
|
934
|
+
(alpha_dual = alpha * |H_bar|) before comparing the UNNORMALIZED entropy to the target. Sign check:
|
|
935
|
+
d(alpha_loss)/d(log_alpha) = alpha_dual * mean(ent_raw - H_bar); when mean entropy > H_bar this is
|
|
936
|
+
> 0 so gradient descent DECREASES log_alpha (alpha down), and increases it when entropy < H_bar."""
|
|
937
|
+
alpha_dual = self.get_alpha() * self._abs_H
|
|
938
|
+
ent_raw = self.ent_raw_buf.detach()
|
|
939
|
+
if self.decision_every > 1:
|
|
940
|
+
# Amendment 16: the dual step averages over DECISION steps only (a held step's ent_raw is H_bar, so its term is 0 and only
|
|
941
|
+
# the denominator would differ); the logged entropy below still averages every step (a held step reads H_bar there)
|
|
942
|
+
alpha_loss = (alpha_dual * (ent_raw - self.target_entropy) * self.dec_buf).sum() / self.dec_buf.sum().clamp_min(1.0)
|
|
943
|
+
else:
|
|
944
|
+
alpha_loss = (alpha_dual * (ent_raw - self.target_entropy)).mean()
|
|
945
|
+
self.alpha_opt.zero_grad()
|
|
946
|
+
alpha_loss.backward()
|
|
947
|
+
clip_grad_norm_([self.log_alpha], 0.5)
|
|
948
|
+
self.alpha_opt.step()
|
|
949
|
+
with torch.no_grad():
|
|
950
|
+
if defer: # CriticOverlap: the host reads wait for its join
|
|
951
|
+
self._e5_alpha_stats = (self.get_alpha().clone(), ent_raw.mean())
|
|
952
|
+
else:
|
|
953
|
+
self.last_alpha = float(self.get_alpha())
|
|
954
|
+
self.last_entropy_mean = float(ent_raw.mean())
|
|
955
|
+
return alpha_loss.detach() if defer else float(alpha_loss.detach())
|
|
956
|
+
|
|
957
|
+
def train(self, log_every=1, callback=None):
|
|
958
|
+
"""Per-iteration order: lr schedule -> rollout (compute_actor_loss) -> actor backward+clip+step ->
|
|
959
|
+
alpha step -> entropy-augmented td-lambda target -> ensemble critic update (NO Polyak)."""
|
|
960
|
+
curve = []
|
|
961
|
+
for epoch in range(self.max_epochs):
|
|
962
|
+
if self.lr_schedule == "linear":
|
|
963
|
+
_off = getattr(self, "epoch_offset", 0) # warm-start: continue the anneal, don't restart at peak lr
|
|
964
|
+
frac = (epoch + _off) / (self.max_epochs + _off)
|
|
965
|
+
for g in self.actor_opt.param_groups:
|
|
966
|
+
g["lr"] = ((1e-5 - self.actor_lr) * frac + self.actor_lr) * self._actor_lr_scale
|
|
967
|
+
for g in self.critic_opt.param_groups:
|
|
968
|
+
g["lr"] = (1e-5 - self.critic_lr) * frac + self.critic_lr
|
|
969
|
+
|
|
970
|
+
if self.adaptive_horizon: # re-pin the rollout length to the current adaptive H (buffers stay at steps_max)
|
|
971
|
+
self.steps_num = int(min(self.steps_max, max(self.steps_min, round(float(self.H)))))
|
|
972
|
+
|
|
973
|
+
if self._ks_teacher is not None:
|
|
974
|
+
self._ks_epoch = epoch
|
|
975
|
+
if self.latent is not None:
|
|
976
|
+
self.last_beta = self.latent_beta(epoch + getattr(self, "epoch_offset", 0))
|
|
977
|
+
self.actor_opt.zero_grad()
|
|
978
|
+
# DIAGNOSTIC (SAPO_DETECT_ANOMALY_FROM, default -1 = off): torch anomaly mode from that epoch on, so a non-finite
|
|
979
|
+
# backward names the forward op that produced it (slow; for localising a NaN stop, never in a training cell).
|
|
980
|
+
_anom = False
|
|
981
|
+
with torch.autograd.set_detect_anomaly(_anom, check_nan=True):
|
|
982
|
+
actor_loss = self.compute_actor_loss()
|
|
983
|
+
if self._slope is not None: # CRITIC SLOPE: the return-only backward first, while the graph lives
|
|
984
|
+
self._slope_targets()
|
|
985
|
+
if self._e5 is not None:
|
|
986
|
+
self._e5.mark(self, epoch)
|
|
987
|
+
actor_loss.backward()
|
|
988
|
+
if self._e5 is not None:
|
|
989
|
+
self._e5.launch(self, epoch)
|
|
990
|
+
gn = clip_grad_norm_(self.actor.parameters(), self.grad_norm)
|
|
991
|
+
if self.latent is not None:
|
|
992
|
+
# the encoder's norm is clipped on its own (ControlVAE clips encoder and decoder separately); `gn`, the
|
|
993
|
+
# number AHAC and the log read, stays the decoder's
|
|
994
|
+
lgn = clip_grad_norm_(self.latent.parameters(), self.grad_norm)
|
|
995
|
+
self.last_latent_gn = float(lgn)
|
|
996
|
+
self.last_kl_mean = float(self.kl_buf[:self.steps_num].mean())
|
|
997
|
+
if not math.isfinite(self.last_latent_gn):
|
|
998
|
+
raise ValueError(f"non-finite latent encoder grad norm at epoch {epoch}")
|
|
999
|
+
if self.ltask:
|
|
1000
|
+
# window means: w_z ||mu_g||^2 per step, the offset's rms per z dim, and the env's task errors (one read)
|
|
1001
|
+
offsq = float(self.offsq_buf[:self.steps_num].mean())
|
|
1002
|
+
self.last_task_reg_mean = self.ltask_wz * offsq
|
|
1003
|
+
self.last_task_offset_rms = math.sqrt(offsq / self.ltask_encoder.latent_dim)
|
|
1004
|
+
self.last_task_stats = self.env.latent_task_stats()
|
|
1005
|
+
if self._ks_teacher is not None and epoch % 25 == 0:
|
|
1006
|
+
print(f"[kickstart] epoch {epoch} w {self.last_ks_w:.4g} mse {self.last_ks_mse:.4g}", flush=True)
|
|
1007
|
+
# the adjoint's per-world flags (env14's Window14) in the same host read as gn's finiteness (TW1, the speed adviser 11-10):
|
|
1008
|
+
# under P3's graphs no eager Step14 sets env14.win_used, so the window-start Window14.reset() check never ran; SapoWindow
|
|
1009
|
+
# points _window_flags at the flags and zeroes them before each graph window. One sync, as before.
|
|
1010
|
+
_wf = getattr(self, "_window_flags", None)
|
|
1011
|
+
if not bool(torch.isfinite(gn) if _wf is None else (torch.isfinite(gn) & (_wf == 0).all())):
|
|
1012
|
+
if _wf is not None and bool((_wf != 0).any()):
|
|
1013
|
+
raise AssertionError(f"the adjoint flagged {int((_wf != 0).sum())} worlds at epoch {epoch} (1: a contact slot not "
|
|
1014
|
+
f"reproduced, 2: a limit-row count, 4: a bad record): {torch.nonzero(_wf).flatten()[:8].tolist()}")
|
|
1015
|
+
raise ValueError(f"non-finite actor grad norm at epoch {epoch}")
|
|
1016
|
+
frozen = epoch < self.actor_freeze_epochs
|
|
1017
|
+
if not frozen:
|
|
1018
|
+
if self._new_in_w is not None:
|
|
1019
|
+
scale_new_input_grad(self._new_in_w, self._new_in_cols, self._new_in_mult)
|
|
1020
|
+
self.actor_opt.step()
|
|
1021
|
+
|
|
1022
|
+
if self.adaptive_horizon: # AHAC: nudge H from the (post-clip-returned) actor grad-norm
|
|
1023
|
+
with torch.no_grad():
|
|
1024
|
+
self.H = (self.H + self.ahac_lambd_lr * self.ahac_sgn * (self.ahac_C - gn)
|
|
1025
|
+
).clamp(self.steps_min, self.steps_max)
|
|
1026
|
+
self.last_H = float(self.H)
|
|
1027
|
+
|
|
1028
|
+
if self._e5 is not None:
|
|
1029
|
+
value_loss = self._e5.join(self, epoch, frozen) # the side stream's alpha / targets / critic, joined
|
|
1030
|
+
else:
|
|
1031
|
+
if not frozen and not self.ltask: # (the task phase has no entropy term, so no temperature)
|
|
1032
|
+
self._update_alpha() # auto-temperature (after the actor step)
|
|
1033
|
+
|
|
1034
|
+
self.compute_target_values_with_entropy() # min-bootstrapped, entropy-augmented td-lambda
|
|
1035
|
+
value_loss = self.train_critic() # NO target-critic Polyak update (no target net)
|
|
1036
|
+
if self._slope is not None and epoch % 40 == 0:
|
|
1037
|
+
print(f"[sapo] slope ep {epoch}: train cos {self.last_slope['cos']:+.3f} rel err {self.last_slope['rel_err']:.3f} "
|
|
1038
|
+
f"|dV/ds| {self.last_slope['slope_norm']:.3e} |target| {self.last_slope['target_norm']:.3e} "
|
|
1039
|
+
f"scale {self.last_slope['scale']:.3e}", flush=True)
|
|
1040
|
+
|
|
1041
|
+
self.last_raw_action_grad_max = float(self._rag_max_gpu)
|
|
1042
|
+
self.last_raw_action_grad_nonfinite = bool(self._rag_nonfinite_gpu)
|
|
1043
|
+
ret = -float(actor_loss.detach())
|
|
1044
|
+
if (epoch + 1) % log_every == 0 or epoch == 0:
|
|
1045
|
+
curve.append((self.step_count, ret, value_loss))
|
|
1046
|
+
if callback is not None:
|
|
1047
|
+
callback(epoch, self.step_count, ret, value_loss, float(gn))
|
|
1048
|
+
# the window's graph goes now, not at the next window's assignment: sapo_capture (E0_P3=1) captures its graphs at the
|
|
1049
|
+
# start of the next window, and a live graph's cached AccumulateGrad nodes break the backward capture
|
|
1050
|
+
del actor_loss
|
|
1051
|
+
return curve
|