diff --git a/.gitattributes b/.gitattributes index 3e9487bbf490bd5b3d7b865c60582afe0e5da70c..7ab7563f12e5ac1165fb4b74f37cc283519e7836 100644 --- a/.gitattributes +++ b/.gitattributes @@ -112,3 +112,46 @@ reconstruction/runs/20200709_142553_836212060125/obj_tracking_out/isaaclab_asset reconstruction/runs/20200709_142553_836212060125/obj_tracking_out/isaaclab_assets/g1_inspire/meshes/Link22_L.STL filter=lfs diff=lfs merge=lfs -text reconstruction/runs/20200709_142553_836212060125/obj_tracking_out/isaaclab_assets/g1_inspire/meshes/Link22_R.STL filter=lfs diff=lfs merge=lfs -text reconstruction/runs/20200709_142553_836212060125/obj_tracking_out/isaaclab_assets/g1_inspire/meshes/R_hand_base_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/L_hand_base_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link12_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link12_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link13_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link13_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link14_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link14_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link15_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link15_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link16_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link16_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link17_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link17_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link18_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link18_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link19_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link19_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link20_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link20_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link21_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link21_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link22_L.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/Link22_R.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_inspire/meshes/R_hand_base_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/left/left_finger1_link1.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/left/left_finger2_link3.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/left/left_finger2_tip_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/left/left_finger3_link3.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/left/left_finger3_tip_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/left/left_finger4_link3.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/left/left_finger4_tip_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/left/left_finger5_link3.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/left/left_finger5_tip_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/left/left_palm_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/right/right_finger1_link1.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/right/right_finger2_tip_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/right/right_finger3_tip_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/right/right_finger4_tip_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/right/right_finger5_tip_link.STL filter=lfs diff=lfs merge=lfs -text +retarget/assets/g1_wuji/meshes/right/right_palm_link.STL filter=lfs diff=lfs merge=lfs -text +simulation/.venv-planner/bin/python filter=lfs diff=lfs merge=lfs -text +simulation/.venv-planner/bin/python3 filter=lfs diff=lfs merge=lfs -text +simulation/.venv-planner/bin/python3.12 filter=lfs diff=lfs merge=lfs -text diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000006.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000006.png new file mode 100644 index 0000000000000000000000000000000000000000..3e485eeb0c2dc5bb40ab9d30466954a624a4b0e8 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000006.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83460d8e273835d77c2a2b8315aa9ccc5a1fbdbd8b946d5f521c010c80f16a0e +size 468530 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000007.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000007.png new file mode 100644 index 0000000000000000000000000000000000000000..8679f7deb1a1dbd5bef43e272f2e88a5c74f9f55 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000007.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e412983fa5b586f1c77c19fcaae8380832be905fdc0b7dd0a5608f4165605fcf +size 467837 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000008.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000008.png new file mode 100644 index 0000000000000000000000000000000000000000..44c3c57406dc06e5df0d2ecf3aa4eb3ff46244c3 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000008.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86e5d963aa3ddfd2ffc3f648868d7e26b2fc66478ccf6ae0ac34ee8f56ea7fa4 +size 467527 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000009.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000009.png new file mode 100644 index 0000000000000000000000000000000000000000..2725e9ec20f2e3e6c9d22cbf62b159dcb9d60f74 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000009.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80d34ed2b8216991ce01ae824f5de7afd76bc62eaa5ea39f415274535c857946 +size 466649 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000010.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000010.png new file mode 100644 index 0000000000000000000000000000000000000000..09e606f0d0263cf2f7a7dd1f277039ee93462050 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000010.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf1ffa7dfeea3037cc530ea9fddda6de462f06da81c6b5c94f472e96bf1bff5f +size 465282 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000011.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000011.png new file mode 100644 index 0000000000000000000000000000000000000000..173ddcf290ff8aacb2d5af0716e9b39be245c247 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000011.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c7ce2f4b32625693286e93b91811666a65273fc853d4057dc796133e726fe621 +size 463972 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000012.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000012.png new file mode 100644 index 0000000000000000000000000000000000000000..e94d399ba7fc04e4c288829ad20952e8feeb2208 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000012.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9672cf46c97e4f4ff665b4525280d6fbd41d26ee156e9bdfecf62d4ac69e460 +size 464595 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000013.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000013.png new file mode 100644 index 0000000000000000000000000000000000000000..331bd2d1d0cfc809fe9fc5bfab24c1486b2b1410 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000013.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:244f1ff70b332b566a631269f07c74dd587cf17f3afb36f8afba4c9e7ee4a437 +size 464964 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000014.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000014.png new file mode 100644 index 0000000000000000000000000000000000000000..885e0796e06ddf1d1051518126c092cc0f067b5b --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000014.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e08d7087a97eb452060efa3a375874495493ae910d583aa7f68730df5d23f138 +size 466123 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000015.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000015.png new file mode 100644 index 0000000000000000000000000000000000000000..a371acc8f1b15daee883c4bd3f173cf6137fc7da --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000015.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0147ee3749909580d899e2cb9248b477e99a8c7ec4df78617b559573ca221db3 +size 466983 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000016.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000016.png new file mode 100644 index 0000000000000000000000000000000000000000..9ca534cccdc8c8ec63dd2935523443b5d3792862 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000016.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c0e95adbb48153869d035d423b6e3957f2420d055627668f675f25f86f847f0 +size 468098 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000017.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000017.png new file mode 100644 index 0000000000000000000000000000000000000000..8f5d77c09cb779e164bdc38258dd3204964b474e --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000017.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4df68b713cbb6e77b75efca6541b33f926db8197da14ea41bfb13e6712087504 +size 468689 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000018.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000018.png new file mode 100644 index 0000000000000000000000000000000000000000..83d4d61357a21a36ffaccb82ce13cc3864ca873f --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000018.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9954674b54466aa5774d01272579774ab251563f1ee0aece8c504946827ce5a4 +size 470069 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000019.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000019.png new file mode 100644 index 0000000000000000000000000000000000000000..5ea5e811c8ed6abf32a41480677a62449511d135 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000019.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:360ba1268f3d721ff8ac65a6f19b2daf8f5542dd30c5d48bf86cfd3b1c114352 +size 469858 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000020.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000020.png new file mode 100644 index 0000000000000000000000000000000000000000..42d95e44761ef4917ffb15b87742cdbc84f3b2d9 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000020.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42a94e40638da28ac6eaa8422ae40f0cfac25d3fa192dc2f197f9d0b59b7c634 +size 471004 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000021.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000021.png new file mode 100644 index 0000000000000000000000000000000000000000..703ddc765d7d366d36f9c6dda0119468ca10dd57 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000021.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa509e4774b6ce19de12c1734e022e59160011d00189419f99e856a257ed9f54 +size 470873 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000022.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000022.png new file mode 100644 index 0000000000000000000000000000000000000000..192e42c13ee9eeb84dc27c144b33f8e8ce43bb44 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000022.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7af5bf13e4b99711fefd95757a24144c9d88221bfdcfc0e5e39a8793e57e5ec6 +size 470638 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000023.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000023.png new file mode 100644 index 0000000000000000000000000000000000000000..6444abb45c29d180678f1d0ac026715e8081d0c6 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000023.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:007859c0b184c6046043a875f7b2fcc97289c85eec5e0a9fe38e0a25ab1c6346 +size 471000 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000024.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000024.png new file mode 100644 index 0000000000000000000000000000000000000000..eee15c8401aae7f269c92db935a9cfc626581808 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000024.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25a79264492d51410bfa8cef2ed5a5cd6e8322ec28bd618ee9d5d3ab8ad04b7a +size 471220 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000025.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000025.png new file mode 100644 index 0000000000000000000000000000000000000000..fc4a0632dd0db4db4ab5a6c3b492091f9b7a077a --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000025.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1aa02ca63203eb68cf90039229c153c326a810e0e338490da56142deb887a48 +size 470664 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000026.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000026.png new file mode 100644 index 0000000000000000000000000000000000000000..4957fc439ebf9731d774ddbbb6ba7d73d35a639a --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000026.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d3e8c64314432549b43bd6fdfc571b2cd44f090ca31a25477102c12f51494c1 +size 470017 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000027.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000027.png new file mode 100644 index 0000000000000000000000000000000000000000..0673ee421c777c75015122bec02f40549f16765a --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000027.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4de22471d85acebd9bc1d40c0b2e87e96af6ff92378e08169d322f1a548382d9 +size 470104 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000028.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000028.png new file mode 100644 index 0000000000000000000000000000000000000000..33c5fad2a94d03f4e9696e7c2961e32fe3eaedc0 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000028.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94d32588f6ef7e7a365759e1ec67603ac91a73cf88e3054a606be6f44945ecc6 +size 469616 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000029.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000029.png new file mode 100644 index 0000000000000000000000000000000000000000..2b941dd92465371174a1797f1e93186dc6be1d12 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000029.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:171f8afa919d93a703b1b3c2ac400b0155b7b98bf786db79571f2187705c1cee +size 469436 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000030.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000030.png new file mode 100644 index 0000000000000000000000000000000000000000..c8c9fb8a89ee1fc34a2e6210a452890f7430458b --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000030.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16e44f77d0dd927071b3d4221429f10a4d1ccf9990c6998da643f1613aa150c5 +size 470484 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000031.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000031.png new file mode 100644 index 0000000000000000000000000000000000000000..4959522cfd62d16476c05f14f7f4c4219f37a57b --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000031.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1c895d43ab0c86fc08a5f38ff3a61d28a81e66c1cbc61a6bf46ccb419b7a383 +size 469616 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000032.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000032.png new file mode 100644 index 0000000000000000000000000000000000000000..bde53fa2447e1484654c023cc2963bc6b44237a6 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000032.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7217e392bec9ecf05fed45eb33b2424dabf4e5eb384f6c99d008cb630b8be90 +size 469933 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000033.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000033.png new file mode 100644 index 0000000000000000000000000000000000000000..f021f958c09554e7cf09a97a4d3ba17d8a0dc3f6 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000033.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46a6a3350c4aae7f45a9bae5c5d56c6bbadbe2951d4818eb64d95b11f095fdc3 +size 469054 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000034.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000034.png new file mode 100644 index 0000000000000000000000000000000000000000..55aff70480041c4dc9109532966021db40786fad --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000034.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f3cc685837dff9cc7f5cd1f5233ca782c3fb17f909d1f830eead5bedf99ca4a +size 469312 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000035.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000035.png new file mode 100644 index 0000000000000000000000000000000000000000..2cb176aed67f6e2582cff9323ea60d89f2690875 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000035.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3e1202fd8ea1d23de4d7982da890a0874d803cd0a711038b940a926df63d938 +size 467732 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000036.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000036.png new file mode 100644 index 0000000000000000000000000000000000000000..0d09e33551f3eb170b28fe1cd14c764afdfc6fc1 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000036.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:167aebbd2294aa079d878db476d09963e38e1ce95506b2e02bc1bc46189cce64 +size 467856 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000037.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000037.png new file mode 100644 index 0000000000000000000000000000000000000000..e5ccc67aa22e2e3c9044f71833341768c52ba9ba --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000037.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f297d668f4065ce34bba1783c42a36d126a3a437fe361e255cb91af3e539636b +size 467866 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000038.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000038.png new file mode 100644 index 0000000000000000000000000000000000000000..f9f04890ce76cc9ea048d48fdd80bd2dacb42083 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000038.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac296e7372f475499abbce5a39b0314e47eb254f2b1d2099b85b5681bbe6a993 +size 467001 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000039.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000039.png new file mode 100644 index 0000000000000000000000000000000000000000..0a271eaad2bbf2f3a2d175d4e9d6d8c06cb93f24 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000039.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50a17aba54774411a9bb0abe78a0f854093b229e8af2e657700aae896d93d0c4 +size 467016 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000040.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000040.png new file mode 100644 index 0000000000000000000000000000000000000000..3db8f6416b0acf09d9c5d2bdb3b2dcc5c45247a4 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000040.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6975c3fe2c8b1b2488396f087005d1d5e178849c4dc8841676a918bc101afdcd +size 467368 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000041.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000041.png new file mode 100644 index 0000000000000000000000000000000000000000..0c175c648acbae4f4c9a22ddc17ca41774085d88 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000041.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a0cee67006bf45b7bddcec3847b56bbb3a2b66406f52c647f509d5ff4489df2 +size 467570 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000042.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000042.png new file mode 100644 index 0000000000000000000000000000000000000000..f3a2f6c094850df54b96a004ebcc72f44e601742 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000042.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1cebde7185464744c1c5565c0c19f7ce0f26538e6a335acac193d5331fa5b171 +size 466487 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000043.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000043.png new file mode 100644 index 0000000000000000000000000000000000000000..c7111edf2a7fe424702fe61be6a8a0fafb0342e0 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000043.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6742108ccadf59bf6c2371ffd9d939e0e661cbf6ba7706f0f5197fdec73e051f +size 466396 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000044.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000044.png new file mode 100644 index 0000000000000000000000000000000000000000..f3de756fdbd8283cd1cd58d68390193ac3a3fb25 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000044.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fe392c46af6cd255a4294c63e23e4c3065ebf014a969fb41f88e196c0b97db4 +size 467268 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000045.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000045.png new file mode 100644 index 0000000000000000000000000000000000000000..991936ea6a926346c84322b023a6b80ab5adab25 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000045.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d477d5e235c295b8d8d989e121c81f855bfed5ad8dbe5a58836f2bcde92febde +size 467265 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000046.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000046.png new file mode 100644 index 0000000000000000000000000000000000000000..de5513394fda02dd5c259e3815561362ef6119b8 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000046.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28b22ca460cf9e9e36ae3681be3b29493ebc2d90c61c3153fc633ef5f883fcfa +size 467749 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000047.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000047.png new file mode 100644 index 0000000000000000000000000000000000000000..9a26879e9451733f183f0ab04f8dcb433b401f69 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000047.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:668836401236730ee6004d440eae87215fb4c9cade66c3f0829946db0230daa3 +size 467302 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000048.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000048.png new file mode 100644 index 0000000000000000000000000000000000000000..c55054e01c56dda1f971efe63457596531ca5182 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000048.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18fd9f4570988437cd996c4366597213ac1fe3515002a0d8c52d3915baa8d29e +size 467833 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000049.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000049.png new file mode 100644 index 0000000000000000000000000000000000000000..ebb395197aa4b098bb756eef3a55bedfdf158bcc --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000049.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c895517312f6467221f05f6ee09a11026da146fec1a330740902aa3e17670dc +size 467502 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000050.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000050.png new file mode 100644 index 0000000000000000000000000000000000000000..d8602e458caa9104eadb31821211b1695a622113 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000050.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9af29cd06b970ea9878503cd34a0f6aa496e2ecc8c9ff0a0d422ff0e6d396cf7 +size 466969 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000051.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000051.png new file mode 100644 index 0000000000000000000000000000000000000000..67197429546f9ffc705714a4c58aa8e118c67fbf --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000051.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5afe916024def884fd1840651d0ea841277bf2f8281d326e8754d2ef1ebfd5b8 +size 466389 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000052.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000052.png new file mode 100644 index 0000000000000000000000000000000000000000..335427f05d1cacd9e79fcfe60baaa8093d597443 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000052.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f37a99865b9696d656ccb638be0e2d01df3ccb49a114d4c5e5b5b853b9ea30f6 +size 466348 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000053.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000053.png new file mode 100644 index 0000000000000000000000000000000000000000..6defe6a1967b5df791b0d98f01456acb59267b23 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000053.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82b56004debb730e7830d57e3fc28355fb654e6de3a40ea252746187537599fe +size 465696 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000054.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000054.png new file mode 100644 index 0000000000000000000000000000000000000000..5ee19fa2908477a92fa0e6a4eca9d3f43760619b --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000054.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9675453b159d4b83d2cdee9a1f5724fccc22b9503ff50f534043ad29805207a0 +size 465743 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000055.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000055.png new file mode 100644 index 0000000000000000000000000000000000000000..a5ab6e98de49e6c784a375b32d6a1db0dc4b93a8 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000055.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ea46faec77ed29831fe59fea4f22f85f7f419ba308655d95812aa9cc0c1a70a +size 465273 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000056.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000056.png new file mode 100644 index 0000000000000000000000000000000000000000..8cc1ade61b889f98d0ef196f28eff45a025d7589 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000056.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:832085e1aa31c1b0f43dd61b620a988482439711e9062e9cfe0ba784d729df79 +size 466473 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000057.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000057.png new file mode 100644 index 0000000000000000000000000000000000000000..cddca35ccad2b5290ac26f6a8743f3c3a2c14f63 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000057.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1dacebe95e0cf2f7c65f621a4288ec4051a234af368d33f36dd3def03fba33b +size 465362 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000058.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000058.png new file mode 100644 index 0000000000000000000000000000000000000000..2908e918d96370ef7bafd36c855c1c3a039847b2 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000058.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1966b7e98af3c7b1842995190c8acabf3e83dbdde40155c784859caaacab77ac +size 464814 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000059.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000059.png new file mode 100644 index 0000000000000000000000000000000000000000..b3df6d5f8bbd27a0a04fa32eabab1d2ac7f0450d --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000059.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c7aac1be0d6f1ff196aad582784d4b372055eb623bb6b5a4db1c7591aacfe46 +size 464418 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000060.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000060.png new file mode 100644 index 0000000000000000000000000000000000000000..992df3f68482b0f15d8fa075e34e73aa36264e00 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000060.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e502204c7ab1cae3a7cf4fa9b1c3954cb24c1ac029ffecb71e711f88b1c80fd2 +size 463800 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000061.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000061.png new file mode 100644 index 0000000000000000000000000000000000000000..66b57b7187585d5f84263ce182a9c86c8597885a --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000061.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eabc1e0209c7c59126da9a49f5f10a7f4cc5856e2cd694b31322d60ea48567eb +size 465015 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000062.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000062.png new file mode 100644 index 0000000000000000000000000000000000000000..1a17e3ccf3d9930b00aa1d37b81e1c07508c1143 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000062.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e626383a83af89de9f139ec891001bea2082f829d234352dc2b0c579888d242c +size 464176 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000063.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000063.png new file mode 100644 index 0000000000000000000000000000000000000000..87b8b2beb78221fd0082ae37011da01e0b0219a1 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000063.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ace18ebab85a45f8067e3027f6fa1f04eea02d808eefeb10fb80bb1553c84bf7 +size 464684 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000064.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000064.png new file mode 100644 index 0000000000000000000000000000000000000000..661ba039633952c05ef82da7b0c3a63168e358da --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000064.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ae55819c6b4f487dbd6e3bdd9c8984efed86a7a0126856d3635a6cb49b7d755 +size 464338 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000065.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000065.png new file mode 100644 index 0000000000000000000000000000000000000000..6070eb172e85a942a4f3187cde3f3924b0f0060b --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000065.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0237b9fade5565462d0daf3c778741979469c3a37f8a200801d58f565a589cfb +size 463862 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000066.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000066.png new file mode 100644 index 0000000000000000000000000000000000000000..e92fea9cca1a4051e62802b435587c60cbe13ec1 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000066.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:949f00a22713323a7b8fe5fd521656b334764f27e22cc1df140b6ae417b94f23 +size 463194 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000067.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000067.png new file mode 100644 index 0000000000000000000000000000000000000000..5957adf1350316feadc1e00475b8c7478b118b60 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000067.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:258fed12a061144ab2684a4cc47e6813ce4e67f007d0dc0ed3e221cfa4271b36 +size 464097 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000068.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000068.png new file mode 100644 index 0000000000000000000000000000000000000000..92e6c3c57c1755e198dcd1ce0955d7582044444e --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000068.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a69b9a1ff448ea74b2c88737124fcbcf66f322c9a9d0ef9a2204048a2b7c22ed +size 464555 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000069.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000069.png new file mode 100644 index 0000000000000000000000000000000000000000..96e3ca742d0f1939d84c6461aee9ef1ba8161a19 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000069.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a30c8f3f55532df992b57885202b4303cdb2603d7d37bd753ee9364fa4b2a4b0 +size 464304 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000070.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000070.png new file mode 100644 index 0000000000000000000000000000000000000000..ec435c5b1596c69a8b17cf699381911bafa92c45 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000070.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0eedbfe873448b1f2b3c1581c057c6a14b6df2d6cb7d2218b26cfb1d301286eb +size 463513 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000071.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000071.png new file mode 100644 index 0000000000000000000000000000000000000000..b40408c55758f581a9c84747bfe5d0bd5c51920a --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000071.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c1b10aca601231c207c0ea51ed9b71b1bb1bc7503360a51c25c00e126c8f08c +size 463706 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000072.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000072.png new file mode 100644 index 0000000000000000000000000000000000000000..80d0c74846dec70122fb0dbfccb0a14d8fff038b --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000072.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b8e0d7d5a890d1146ade97222636b25e880eb810844195337d096d192951083 +size 462696 diff --git a/reconstruction/runs/20200709_143340_836212060125/all_frames/000073.png b/reconstruction/runs/20200709_143340_836212060125/all_frames/000073.png new file mode 100644 index 0000000000000000000000000000000000000000..31c183bd1b61b4abc4c55a26a0752b3828daa007 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/all_frames/000073.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a13195b0e3c36bf9a45568095b7290d623b2a4e47ad03047673f49e7bc1cbb70 +size 463083 diff --git a/reconstruction/runs/20200709_143340_836212060125/box.json b/reconstruction/runs/20200709_143340_836212060125/box.json new file mode 100644 index 0000000000000000000000000000000000000000..2bc46a307df5b269284fe90839f35f298001c5e3 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/box.json @@ -0,0 +1,13 @@ +{ + "image": "all_frames/000000.png", + "width": 640, + "height": 480, + "boxes": [ + { + "xmin": 340, + "ymin": 354, + "xmax": 502, + "ymax": 445 + } + ] +} diff --git a/reconstruction/runs/20200709_143340_836212060125/clip.mp4 b/reconstruction/runs/20200709_143340_836212060125/clip.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..33df268857febdd4583bc66232143282176e93b4 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/clip.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c29ed7a2c358c450dfe5f7eb820944da35766b6efca19fe4e4fb608dd9f41e34 +size 199540 diff --git a/reconstruction/runs/20200709_143340_836212060125/config.json b/reconstruction/runs/20200709_143340_836212060125/config.json new file mode 100644 index 0000000000000000000000000000000000000000..1b20a4788917725badfd3f57310d1f53aa83a567 --- /dev/null +++ b/reconstruction/runs/20200709_143340_836212060125/config.json @@ -0,0 +1,9 @@ +{ + "source": "/scratch/users/create/smrvmdo/projects/v2d/data/dexycb/20200709-subject-01/20200709_143340/836212060125", + "frame_number": 0, + "object_names": [ + "mustard_bottle" + ], + "anchor_hand": "right", + "num_frames": 74 +} diff --git a/reconstruction/scripts/.gradio/certificate.pem b/reconstruction/scripts/.gradio/certificate.pem new file mode 100644 index 0000000000000000000000000000000000000000..b85c8037f6b60976b2546fdbae88312c5246d9a3 --- /dev/null +++ b/reconstruction/scripts/.gradio/certificate.pem @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- diff --git a/reconstruction/scripts/__pycache__/get_pointmap_dir.cpython-310.pyc b/reconstruction/scripts/__pycache__/get_pointmap_dir.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36efede38c350c9b86fb4f302698dc58668eb51e Binary files /dev/null and b/reconstruction/scripts/__pycache__/get_pointmap_dir.cpython-310.pyc differ diff --git a/reconstruction/scripts/__pycache__/prepare_dexycb.cpython-310.pyc b/reconstruction/scripts/__pycache__/prepare_dexycb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f21a2ca2bfca452fac46ec3d4aa91d353c98d205 Binary files /dev/null and b/reconstruction/scripts/__pycache__/prepare_dexycb.cpython-310.pyc differ diff --git a/reconstruction/scripts/__pycache__/run_project_mesh_combined.cpython-310.pyc b/reconstruction/scripts/__pycache__/run_project_mesh_combined.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45a9a931421efb8f278efe75e9b811635e960f2c Binary files /dev/null and b/reconstruction/scripts/__pycache__/run_project_mesh_combined.cpython-310.pyc differ diff --git a/reconstruction/scripts/__pycache__/run_sam3_video.cpython-310.pyc b/reconstruction/scripts/__pycache__/run_sam3_video.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eefe0a106a834a865e26499281b7f2701e77208b Binary files /dev/null and b/reconstruction/scripts/__pycache__/run_sam3_video.cpython-310.pyc differ diff --git a/reconstruction/scripts/convert_layout_to_camera_frame.py b/reconstruction/scripts/convert_layout_to_camera_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..ba4171217e5f90a0a19f23c4946d23a21923bedf --- /dev/null +++ b/reconstruction/scripts/convert_layout_to_camera_frame.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +""" +Convert a per-frame layout JSON from pose frame to camera frame. + +Applies the same transformation as visualize_mesh_3d_video.py: + 1. Reorder translation [tx,ty,tz] -> [tz,tx,ty] and scale by --translation-scale + 2. Convert rotation and translation from pose frame (x-fwd, y-left, z-up) + to camera frame (x-right, y-down, z-fwd) + +Usage: + python convert_layout_to_camera_frame.py \ + --input /path/to/video_dir/obj_tracking_out//combined_visualization/layout.json \ + --output /path/to/video_dir/obj_tracking_out//combined_visualization/layout_camera_frame.json +""" + +import argparse +import json +import numpy as np +from scipy.spatial.transform import Rotation as R + + +# Pose frame -> Camera frame rotation matrix (for row vectors: v_cam = v_pose @ P) +# x_cam = -y_pose, y_cam = -z_pose, z_cam = x_pose +P = np.array([ + [0, 0, 1], + [-1, 0, 0], + [0, -1, 0], +], dtype=np.float64) + + +def convert_translation(tx, ty, tz, translation_scale): + """Reorder and scale translation, then convert to camera frame.""" + # Reorder as done in visualize_mesh_3d_video.py + t_pose = np.array([tz * translation_scale, tx * translation_scale, ty * translation_scale]) + # Convert to camera frame: v_cam = v_pose @ P + t_cam = t_pose @ P + return t_cam.tolist() + + +def convert_rotation(quat_wxyz): + """Convert rotation from pose frame to camera frame.""" + # new_quat is wxyz + quat_xyzw = [quat_wxyz[1], quat_wxyz[2], quat_wxyz[3], quat_wxyz[0]] + R_pose = R.from_quat(quat_xyzw).as_matrix() + # R_cam = P.T @ R_pose (change of basis) + R_cam = P.T @ R_pose + quat_cam_xyzw = R.from_matrix(R_cam).as_quat() # returns xyzw + quat_cam_wxyz = [float(quat_cam_xyzw[3]), float(quat_cam_xyzw[0]), + float(quat_cam_xyzw[1]), float(quat_cam_xyzw[2])] + return quat_cam_wxyz + + +def main(): + parser = argparse.ArgumentParser( + description='Convert layout JSON poses from pose frame to camera frame.', + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument('--input', type=str, required=True, help='Input layout JSON') + parser.add_argument('--output', type=str, required=True, help='Output layout JSON') + parser.add_argument('--scale', type=float, default=None, + help='Mesh scale (written to output for reference, does not affect transform)') + parser.add_argument('--translation-scale', type=float, default=1.0, + help='Scale factor for translation values') + args = parser.parse_args() + + with open(args.input) as f: + data = json.load(f) + + for obj in data["objects"]: + pose = obj["local_to_scene"] + tx, ty, tz = pose["translation"] + quat_wxyz = pose["new_quat"] + + t_cam = convert_translation(tx, ty, tz, args.translation_scale) + q_cam = convert_rotation(quat_wxyz) + + pose["translation_camera_frame"] = t_cam + pose["quat_wxyz_camera_frame"] = q_cam + + data["frame"] = "camera_frame" + data["note"] = ( + "Poses converted to camera frame (x-right, y-down, z-fwd). " + f"translation_scale={args.translation_scale}. " + "Original pose-frame values preserved." + ) + if args.scale is not None: + data["mesh_scale"] = args.scale + + with open(args.output, 'w') as f: + json.dump(data, f, indent=2) + + num = len([o for o in data["objects"] if "frame_idx" in o or "frame_index" in o]) + print(f"Converted {num} frames to camera frame -> {args.output}") + + +if __name__ == "__main__": + main() diff --git a/reconstruction/scripts/get_pointmap_dir.py b/reconstruction/scripts/get_pointmap_dir.py new file mode 100644 index 0000000000000000000000000000000000000000..f8f5aaa6198a4011f852a252c1ca9700fee70e8a --- /dev/null +++ b/reconstruction/scripts/get_pointmap_dir.py @@ -0,0 +1,179 @@ +""" +Compute MoGe pointmaps (+ camera intrinsics) for one image or a whole directory. + +Uses the local checkpoint at checkpoints/moge when MOGE_CHECKPOINT is set +(or the Fast-SAM3D pipeline.yaml depth_model as a fallback). + +Single image: + python get_pointmap_dir.py --image /path/to/0028.png --output /path/to/0028_pointmap.npy + +Batch: + python get_pointmap_dir.py --image_dir /path/to/all_frames +""" + +import argparse +import glob +import os +import sys + +import numpy as np +import torch +from PIL import Image + +_RECON_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +_PROJECT_ROOT = os.path.dirname(_RECON_ROOT) + + +def _default_moge_ckpt(): + env = os.environ.get("MOGE_CHECKPOINT") + if env: + return env + local = os.path.join(_PROJECT_ROOT, "checkpoints", "moge", "model.pt") + return local if os.path.isfile(local) else None + + +def _moge_version_from_checkpoint(ckpt_path: str) -> str: + """Local model.pt can be v1 (encoder name str), v2 (encoder dict), or v3 (has refiner).""" + blob = torch.load(ckpt_path, map_location="cpu", weights_only=True) + if isinstance(blob.get("model_version"), str): + return blob["model_version"] + cfg = blob.get("model_config") or {} + if "refiner" in cfg or cfg.get("refiner_depth_resolution") is not None: + return "v3" + enc = cfg.get("encoder") + if isinstance(enc, dict): + return "v2" + return "v1" + + +def load_model(): + """Load MoGe from a local checkpoint, else Fast-SAM3D pipeline.yaml.""" + ckpt = _default_moge_ckpt() + if ckpt: + from moge.model import import_model_class_by_version + + device = "cuda" if torch.cuda.is_available() else "cpu" + version = _moge_version_from_checkpoint(ckpt) + print(f"Loading MoGe {version} from {ckpt}") + cls = import_model_class_by_version(version) + model = cls.from_pretrained(ckpt).to(device).eval() + return ("moge", model) + + SAM3D_REPO_ROOT = os.environ.get( + "SAM3D_REPO_ROOT", os.path.join(_RECON_ROOT, "modules", "Fast-SAM3D") + ) + if SAM3D_REPO_ROOT not in sys.path: + sys.path.insert(0, SAM3D_REPO_ROOT) + from hydra.utils import instantiate + from omegaconf import OmegaConf + + config_path = os.path.join(SAM3D_REPO_ROOT, "checkpoints", "hf", "pipeline.yaml") + cfg = OmegaConf.load(config_path) + device = "cuda" if torch.cuda.is_available() else "cpu" + depth_model = instantiate(cfg.depth_model, device=device) + return ("sam3d", depth_model) + + +def _run_moge(model, rgb_chw: torch.Tensor): + """Normalize MoGe / SAM3D depth wrappers to pointmaps + intrinsics.""" + if hasattr(model, "infer"): + out = model.infer(rgb_chw) + else: + out = model(rgb_chw) + + if isinstance(out, dict): + points = out.get("pointmaps", out.get("points")) + intrinsics = out.get("intrinsics") + else: + points, intrinsics = out, None + + if points is None: + raise RuntimeError("MoGe output missing pointmaps/points") + return points, intrinsics + + +def run_pointmap(bundle, image_path: str, output_path: str, intrinsics_format: str = "npy"): + kind, depth_model = bundle + img = np.array(Image.open(image_path).convert("RGB")).astype(np.uint8) + loaded_rgb = torch.from_numpy((img / 255.0).astype(np.float32)).permute(2, 0, 1).contiguous() + + dtype = torch.float16 if torch.cuda.is_available() else torch.float32 + with torch.no_grad(): + if torch.cuda.is_available(): + with torch.autocast(device_type="cuda", dtype=dtype): + points, intrinsics = _run_moge(depth_model, loaded_rgb) + else: + points, intrinsics = _run_moge(depth_model, loaded_rgb) + + pointmap_np = points.detach().cpu().numpy() if torch.is_tensor(points) else np.asarray(points) + np.save(output_path, pointmap_np) + print(f"Saved pointmap to: {output_path}") + + H, W = img.shape[:2] + if intrinsics is None: + print("No intrinsics in MoGe output; skipping") + return + + intrinsics = intrinsics.detach().cpu().numpy().copy() if torch.is_tensor(intrinsics) else np.asarray(intrinsics).copy() + # Some MoGe builds return normalized fx/fy; scale when values look like [0,1]. + if np.nanmax(np.abs(intrinsics[:2, :2])) <= 2.0: + intrinsics[0, 0] *= W + intrinsics[1, 1] *= H + intrinsics[0, 2] *= W + intrinsics[1, 2] *= H + + if intrinsics_format == "txt": + fx, fy = float(intrinsics[0, 0]), float(intrinsics[1, 1]) + cx, cy = float(intrinsics[0, 2]), float(intrinsics[1, 2]) + intrinsics_txt_path = output_path.replace("_pointmap.npy", "_intrinsics.txt") + with open(intrinsics_txt_path, "w") as f: + f.write(f"{fx}\n{fy}\n{cx}\n{cy}\n") + print(f"Saved intrinsics to: {intrinsics_txt_path}") + else: + intrinsics_path = output_path.replace("_pointmap.npy", "_intrinsics.npy") + np.save(intrinsics_path, intrinsics) + print(f"Saved intrinsics to: {intrinsics_path}") + + +def _list_images(image_dir: str): + paths = [] + for ext in ("*.png", "*.jpg", "*.jpeg"): + paths.extend(glob.glob(os.path.join(image_dir, ext))) + return sorted(paths) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--image", type=str, default=None) + parser.add_argument("--image_dir", type=str, default=None) + parser.add_argument("--output", type=str, default=None) + parser.add_argument("--overwrite", action="store_true") + args = parser.parse_args() + + if args.image_dir is not None: + image_paths = _list_images(args.image_dir) + if not image_paths: + print(f"No images found in {args.image_dir}") + sys.exit(1) + print(f"Found {len(image_paths)} images in {args.image_dir}") + bundle = load_model() + for i, image_path in enumerate(image_paths): + base, _ = os.path.splitext(image_path) + output_path = f"{base}_pointmap.npy" + if os.path.exists(output_path) and not args.overwrite: + print(f"\n[{i+1}/{len(image_paths)}] skip {os.path.basename(output_path)}") + continue + print(f"\n[{i+1}/{len(image_paths)}] {os.path.basename(image_path)}") + run_pointmap(bundle, image_path, output_path, intrinsics_format="npy") + print(f"\nDone! Processed {len(image_paths)} images.") + elif args.image is not None: + if args.output is None: + base, _ = os.path.splitext(args.image) + args.output = f"{base}_pointmap.npy" + if os.path.exists(args.output) and not args.overwrite: + print(f"skip {args.output} (already exists)") + else: + bundle = load_model() + run_pointmap(bundle, args.image, args.output, intrinsics_format="txt") + else: + parser.error("Must specify either --image or --image_dir") diff --git a/reconstruction/scripts/optimize_translation_scale.py b/reconstruction/scripts/optimize_translation_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..8e4b0b8065a5b58405215f56eb79cfe2b8417d12 --- /dev/null +++ b/reconstruction/scripts/optimize_translation_scale.py @@ -0,0 +1,681 @@ +#!/usr/bin/env python3 +""" +Per-frame translation scale optimization via hand-anchored pointmap alignment. + +The anchor hand mesh from HaWoR is treated as ground truth. The pointmap (MoGe) +gives the relative 3D offset between hand and object, but has its own global +scale. We compute the pointmap-to-real scale factor per frame by comparing the +anchor hand's depth in the pointmap vs HaWoR, then use the scaled hand-to-object +vector from the pointmap to place the object relative to the hand. + +For each frame: + 1. h_real = anchor hand centroid from HaWoR (ground truth) + 2. h_pm = pointmap sampled at anchor hand projected pixels + 3. o_pm = pointmap median at object mask pixels + 4. k = h_real_z / h_pm_z (pointmap-to-real depth scale) + 5. obj_pos = h_real + k * (o_pm - h_pm) + 6. Solve for translation_scale s: mesh_center(s) ≈ obj_pos + +Usage (simplified — most paths inferred from --video-dir and --layout-json): + python optimize_translation_scale.py \ + --video-dir /path/to/video_dir \ + --layout-json /path/to/video_dir/obj_tracking_out/bowl/combined_visualization/layout_camera_frame.json \ + --anchor-hand left \ + --ref-frame 0 + +All other arguments (--mesh, --scale, --pointmap-dir, --mask-dir, --mask-name, +--hand-meshes, --output, --viz-dir, --frames-dir) are inferred but can be +overridden explicitly. +""" + +import argparse +import copy +import json +import os +import sys + +import cv2 +import numpy as np +import trimesh +from scipy.spatial.transform import Rotation as R + +MAX_HAND_RAYS = 2000 + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Per-frame translation scale optimization via hand-anchored pointmap alignment.', + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument('--video-dir', type=str, default=None, + help='Video directory root. When provided, most other paths are inferred automatically.') + parser.add_argument('--layout-json', type=str, required=True, + help='Camera-frame layout JSON (with translation_camera_frame and quat_wxyz_camera_frame)') + parser.add_argument('--mesh', type=str, default=None, + help='Object mesh (.obj)') + parser.add_argument('--scale', type=float, default=None, + help='Mesh scale factor') + parser.add_argument('--pointmap-dir', type=str, default=None, + help='Directory with per-frame pointmaps (NNNN_pointmap.npy) and intrinsics') + parser.add_argument('--mask-dir', type=str, default=None, + help='Directory with per-frame masks (frame_NNNNNN_masks/.png)') + parser.add_argument('--mask-name', type=str, default=None, + help='Name of the object mask file (without .png)') + parser.add_argument('--hand-meshes', type=str, default=None, + help='Hand meshes NPZ (already in camera frame, from HaWoR)') + parser.add_argument('--anchor-hand', type=str, default='left', + choices=['left', 'right'], + help='Which hand to use as the anchor for pointmap scale calibration') + parser.add_argument('--output', type=str, default=None, + help='Output JSON path') + parser.add_argument('--ref-frame', type=int, default=None, + help='Preferred frame for pointmap scale k. If that frame has no visible ' + 'anchor hand (common when --frame 0 is object-only), the first later ' + 'frame with hand+object is used.') + parser.add_argument('--min-mask-pixels', type=int, default=100, + help='Skip frames with fewer mask pixels than this') + parser.add_argument('--viz-dir', type=str, default=None, + help='If set, save per-frame debug visualizations to this directory') + parser.add_argument('--frames-dir', type=str, default=None, + help='Directory with frame images (NNNNNN.png) for visualization (required if --viz-dir is set)') + args = parser.parse_args() + resolve_args(args) + return args + + +def _find_hand_meshes_npz(video_dir): + """HaWoR writes //all_hand_meshes.npz (e.g. clip/).""" + hits = [] + try: + for name in os.listdir(video_dir): + path = os.path.join(video_dir, name, "all_hand_meshes.npz") + if os.path.isfile(path): + hits.append(path) + except FileNotFoundError: + hits = [] + if hits: + hits.sort() + clip = os.path.join(video_dir, "clip", "all_hand_meshes.npz") + if clip in hits: + return clip + return hits[0] + return os.path.join( + video_dir, + os.path.basename(os.path.normpath(video_dir)), + "all_hand_meshes.npz", + ) + + +def resolve_args(args): + """Infer missing arguments from --video-dir and --layout-json.""" + import re + + # Infer mask-name from layout-json path + if args.mask_name is None: + m = re.search(r'(?:tracking_output_every_frame|guided_pose_prediction|sweep_k2_50samples|obj_tracking_out)/([^/]+)/combined_visualization/', + args.layout_json) + if m: + args.mask_name = m.group(1) + print(f"[inferred] --mask-name = {args.mask_name}") + else: + print("[error] Cannot infer --mask-name from layout-json path. " + "Expected '.../tracking_output_every_frame//combined_visualization/...' or " + "'.../guided_pose_prediction//combined_visualization/...'") + sys.exit(1) + + # Infer scale from layout JSON + if args.scale is None: + with open(args.layout_json) as f: + layout = json.load(f) + args.scale = float(layout["objects"][0]["local_to_scene"]["scale"][0]) + print(f"[inferred] --scale = {args.scale}") + + video_dir = args.video_dir + + if video_dir is not None: + if args.pointmap_dir is None: + args.pointmap_dir = os.path.join(video_dir, "all_frames") + print(f"[inferred] --pointmap-dir = {args.pointmap_dir}") + + if args.mask_dir is None: + args.mask_dir = os.path.join(video_dir, "video_segmentation", "masks") + print(f"[inferred] --mask-dir = {args.mask_dir}") + + if args.hand_meshes is None: + args.hand_meshes = _find_hand_meshes_npz(video_dir) + print(f"[inferred] --hand-meshes = {args.hand_meshes}") + + if args.mesh is None: + if args.ref_frame is None: + print("[error] Cannot infer --mesh without --ref-frame. Provide --mesh or --ref-frame.") + sys.exit(1) + args.mesh = os.path.join(video_dir, "video_segmentation", "masks", + f"frame_{args.ref_frame:06d}_masks", + args.mask_name, f"{args.mask_name}.obj") + print(f"[inferred] --mesh = {args.mesh}") + if not os.path.exists(args.mesh): + print(f"[error] Mesh not found: {args.mesh}") + sys.exit(1) + + # Auto-enable viz when --video-dir is provided + if args.viz_dir is None: + args.viz_dir = os.path.join(os.path.dirname(args.layout_json), "viz") + print(f"[inferred] --viz-dir = {args.viz_dir}") + if args.frames_dir is None: + args.frames_dir = os.path.join(video_dir, "all_frames") + print(f"[inferred] --frames-dir = {args.frames_dir}") + + if args.output is None: + args.output = args.layout_json.replace(".json", "_optimized.json") + print(f"[inferred] --output = {args.output}") + + # Final validation: all required values must be set + required = {'mesh': args.mesh, 'scale': args.scale, 'pointmap_dir': args.pointmap_dir, + 'mask_dir': args.mask_dir, 'mask_name': args.mask_name, + 'hand_meshes': args.hand_meshes, 'output': args.output} + missing = [k for k, v in required.items() if v is None] + if missing: + print(f"[error] Missing required arguments (provide --video-dir or set explicitly): " + f"{', '.join('--' + k.replace('_', '-') for k in missing)}") + sys.exit(1) + + +def load_layout_camera_frame(json_path): + """Load camera-frame layout JSON. Returns (data, frames_list).""" + with open(json_path) as f: + data = json.load(f) + + frames = [] + for i, obj in enumerate(data["objects"]): + frame_idx = obj.get("frame_index", obj.get("frame_idx")) + if frame_idx is None: + continue + pose = obj["local_to_scene"] + if "translation_camera_frame" not in pose or "quat_wxyz_camera_frame" not in pose: + print(f"[warn] frame {frame_idx}: missing camera-frame fields, skipping") + continue + frames.append({ + "obj_index": i, + "frame_idx": frame_idx, + "t_cam": np.array(pose["translation_camera_frame"]), + "quat_wxyz_cam": pose["quat_wxyz_camera_frame"], + }) + + frames.sort(key=lambda x: x["frame_idx"]) + return data, frames + + +def get_rot_matrix(quat_wxyz): + """Convert wxyz quaternion to 3x3 rotation matrix.""" + w, x, y, z = quat_wxyz + return R.from_quat([x, y, z, w]).as_matrix() + + +def load_pointmap_and_intrinsics(pointmap_dir, frame_idx): + """Load pointmap and intrinsics for a given frame index.""" + pm_path = os.path.join(pointmap_dir, f"{frame_idx:06d}_pointmap.npy") + intr_path = os.path.join(pointmap_dir, f"{frame_idx:06d}_intrinsics.npy") + if not os.path.exists(pm_path) or not os.path.exists(intr_path): + return None, None + return np.load(pm_path), np.load(intr_path) + + +def load_mask(mask_dir, frame_idx, mask_name): + """Load binary object mask for a given frame index.""" + path = os.path.join(mask_dir, f"frame_{frame_idx:06d}_masks", f"{mask_name}.png") + if not os.path.exists(path): + return None + mask = cv2.imread(path, cv2.IMREAD_GRAYSCALE) + return mask > 127 + + +def try_hand_pointmap_k(fr, args, hand_data, anchor, n_hand_frames, rng, min_hits=10): + """Compute MoGe/HaWoR depth scale k on one frame. Returns dict or None.""" + fidx = fr["frame_idx"] + pointmap, intrinsics = load_pointmap_and_intrinsics(args.pointmap_dir, fidx) + if pointmap is None: + return None, "no pointmap" + pm_h, pm_w = pointmap.shape[:2] + fx, fy = intrinsics[0, 0], intrinsics[1, 1] + cx, cy = intrinsics[0, 2], intrinsics[1, 2] + hi = min(fidx, n_hand_frames - 1) + hand_mask = load_mask(args.mask_dir, fidx, f"{anchor}_hand_0") + if hand_mask is None: + return None, "no hand mask" + if hand_mask.shape != (pm_h, pm_w): + hand_mask = cv2.resize( + hand_mask.astype(np.uint8), (pm_w, pm_h), interpolation=cv2.INTER_NEAREST + ).astype(bool) + n_px = int(hand_mask.sum()) + if n_px < min_hits: + return None, f"empty hand mask ({n_px} px)" + obj_mask = load_mask(args.mask_dir, fidx, args.mask_name) + if obj_mask is None: + return None, "no object mask" + if obj_mask.shape != (pm_h, pm_w): + obj_mask = cv2.resize( + obj_mask.astype(np.uint8), (pm_w, pm_h), interpolation=cv2.INTER_NEAREST + ).astype(bool) + if int(obj_mask.sum()) < args.min_mask_pixels: + return None, "object mask too small" + hits, hu, hv = raycast_first_hits( + hand_data[f"{anchor}_vertices"][hi], + np.asarray(hand_data[f"{anchor}_faces"]), + hand_mask, fx, fy, cx, cy, + max_rays=MAX_HAND_RAYS, rng=rng, + ) + if len(hits) < min_hits: + return None, f"too few raycast hits ({len(hits)})" + h_real = hits.mean(axis=0) + h_pm = pointmap[hv, hu].mean(axis=0) + if abs(h_pm[2]) < 1e-6: + return None, "hand pointmap depth ~0" + k = float(h_real[2] / h_pm[2]) + return { + "k": k, + "frame_idx": fidx, + "fx": fx, "fy": fy, "cx": cx, "cy": cy, + "pm_w": pm_w, "pm_h": pm_h, + "n_hits": len(hits), + "n_hand_px": n_px, + }, None + + +def project_to_pixels(verts_cam, fx, fy, cx, cy, w, h): + """Project 3D camera-frame vertices to pixel coordinates, clipped to image bounds.""" + u = (fx * verts_cam[:, 0] / verts_cam[:, 2] + cx).astype(int).clip(0, w - 1) + v = (fy * verts_cam[:, 1] / verts_cam[:, 2] + cy).astype(int).clip(0, h - 1) + return u, v + + +def raycast_first_hits(verts, faces, mask, fx, fy, cx, cy, max_rays=MAX_HAND_RAYS, rng=None): + """Shoot a ray from the camera origin through each True pixel in `mask` and return the + first intersection on the mesh (verts, faces). Rays that miss are dropped. + + Used to recover *front-surface* samples: averaging hits gives a centroid that + excludes back-facing geometry, which a 2D silhouette filter cannot do. + + Args: + verts: (V, 3) camera-frame vertices. + faces: (F, 3) face indices. + mask: (H, W) bool mask of pixels to raycast from. + fx, fy, cx, cy: pinhole intrinsics matching mask's pixel grid. + max_rays: subsample mask pixels down to this many rays (uniform random). + rng: optional np.random.Generator for the subsample. + + Returns: + hits: (M, 3) first-hit 3D points in camera frame. + hit_u: (M,) pixel u of rays that hit. + hit_v: (M,) pixel v of rays that hit. + """ + ys, xs = np.where(mask) + if len(xs) == 0: + return np.empty((0, 3)), np.empty(0, dtype=int), np.empty(0, dtype=int) + if max_rays is not None and len(xs) > max_rays: + if rng is None: + rng = np.random.default_rng(0) + idx = rng.choice(len(xs), size=max_rays, replace=False) + xs, ys = xs[idx], ys[idx] + dirs = np.stack([(xs - cx) / fx, (ys - cy) / fy, np.ones_like(xs, dtype=np.float64)], axis=1) + dirs /= np.linalg.norm(dirs, axis=1, keepdims=True) + origins = np.zeros_like(dirs) + tm = trimesh.Trimesh(vertices=np.asarray(verts, dtype=np.float64), + faces=np.asarray(faces), process=False) + locations, index_ray, _ = tm.ray.intersects_location(origins, dirs, multiple_hits=False) + return locations, xs[index_ray], ys[index_ray] + + +def compute_optimal_scale(c_rot, t_cam, target_3d): + """ + Find translation_scale s that minimizes ||c_rot + t_cam * s - target||^2. + + s* = t_cam . (target - c_rot) / (t_cam . t_cam) + """ + residual = target_3d - c_rot + s = np.dot(t_cam, residual) / np.dot(t_cam, t_cam) + return s + + +def main(): + args = parse_args() + + # Validate paths + for path, name in [(args.layout_json, "Layout JSON"), (args.mesh, "Mesh"), + (args.pointmap_dir, "Pointmap dir"), (args.mask_dir, "Mask dir"), + (args.hand_meshes, "Hand meshes")]: + if not os.path.exists(path): + print(f"[error] {name} not found: {path}") + sys.exit(1) + + # Load layout + print("Loading layout JSON...") + layout_data, frames = load_layout_camera_frame(args.layout_json) + print(f" {len(frames)} frames with camera-frame poses") + + # Load mesh + print("Loading mesh...") + mesh = trimesh.load_mesh(args.mesh) + if not isinstance(mesh, trimesh.Trimesh): + mesh = mesh.dump(concatenate=True) + mesh_verts = np.array(mesh.vertices, dtype=np.float64) + print(f" {len(mesh_verts)} vertices, {len(mesh.faces)} faces") + + # Load hand meshes + print(f"Loading hand meshes (anchor: {args.anchor_hand})...") + hand_data = np.load(args.hand_meshes) + anchor = args.anchor_hand + n_hand_frames = hand_data[f'{anchor}_vertices'].shape[0] + hand_faces = np.asarray(hand_data[f'{anchor}_faces']) + print(f" {anchor} hand: {n_hand_frames} frames, {hand_data[f'{anchor}_vertices'].shape[1]} vertices, " + f"{len(hand_faces)} faces") + + rng = np.random.default_rng(0) + + # Visualization setup + viz_dir = args.viz_dir + if viz_dir: + if not args.frames_dir: + print("[error] --frames-dir is required when --viz-dir is set") + sys.exit(1) + os.makedirs(viz_dir, exist_ok=True) + print(f"Saving visualizations to {viz_dir}") + + # --ref-frame is preferred (object mesh frame) but often has no hand in view; fall back. + mesh_scale = args.scale + ref_k = None + if args.ref_frame is not None: + by_idx = {fr["frame_idx"]: fr for fr in frames} + ordered = [] + if args.ref_frame in by_idx: + ordered.append(by_idx[args.ref_frame]) + else: + print(f"[warn] --ref-frame {args.ref_frame} not in layout; searching other frames") + ordered.extend(fr for fr in frames if fr["frame_idx"] != args.ref_frame) + + chosen = None + last_reason = "no frames" + for fr in ordered: + result, last_reason = try_hand_pointmap_k( + fr, args, hand_data, anchor, n_hand_frames, rng, + ) + if result is None: + if fr["frame_idx"] == args.ref_frame: + print( + f"[warn] ref frame {args.ref_frame} cannot compute k ({last_reason}); " + "searching later frames with a visible hand" + ) + continue + chosen = result + if fr["frame_idx"] != args.ref_frame: + print(f"[warn] using frame {chosen['frame_idx']} for hand scale k") + break + + if chosen is None: + print(f"[error] no frame with enough hand raycast hits to compute k ({last_reason})") + sys.exit(1) + + print(f"\nComputing pointmap scale k from frame {chosen['frame_idx']}...") + ref_k = chosen["k"] + hand_fx, hand_fy = chosen["fx"], chosen["fy"] + hand_cx, hand_cy = chosen["cx"], chosen["cy"] + hand_proj_w, hand_proj_h = chosen["pm_w"], chosen["pm_h"] + print(f" hand mask {chosen['n_hand_px']} px, {chosen['n_hits']} ray hits") + print( + f" using this frame's intrinsics for hand projection: " + f"fx={hand_fx:.1f} fy={hand_fy:.1f} cx={hand_cx:.1f} cy={hand_cy:.1f}" + ) + + mesh_scale = args.scale * ref_k + print(f" ref k: {ref_k:.6f}") + print(f" new mesh_scale: {args.scale} * {ref_k:.6f} = {mesh_scale:.6f}") + + for fr in frames: + fr["t_cam_orig"] = fr["t_cam"].copy() + fr["t_cam"] = fr["t_cam"] * ref_k + print(f" scaled all t_cam by {ref_k:.6f}") + + # Process each frame + print(f"\nOptimizing translation_scale per frame (mesh_scale={mesh_scale:.6f})...") + output_data = copy.deepcopy(layout_data) + per_frame_scales = [] + skipped = 0 + + for i, fr in enumerate(frames): + fidx = fr["frame_idx"] + rot_matrix = get_rot_matrix(fr["quat_wxyz_cam"]) + t_cam = fr["t_cam"] + + # Load pointmap and intrinsics + pointmap, intrinsics = load_pointmap_and_intrinsics(args.pointmap_dir, fidx) + if pointmap is None: + print(f" frame {fidx:3d}: pointmap/intrinsics not found, skipping") + skipped += 1 + continue + + # Load object mask + mask = load_mask(args.mask_dir, fidx, args.mask_name) + if mask is None: + print(f" frame {fidx:3d}: mask not found, skipping") + skipped += 1 + continue + + # Resize mask if needed + pm_h, pm_w = pointmap.shape[:2] + if mask.shape != (pm_h, pm_w): + mask = cv2.resize(mask.astype(np.uint8), (pm_w, pm_h), + interpolation=cv2.INTER_NEAREST).astype(bool) + + n_pixels = mask.sum() + if n_pixels < args.min_mask_pixels: # TODO: handle this case better + print(f" frame {fidx:3d}: mask too small ({n_pixels} px), skipping") + skipped += 1 + continue + + fx, fy = intrinsics[0, 0], intrinsics[1, 1] + cx, cy = intrinsics[0, 2], intrinsics[1, 2] + + # Intrinsics for hand projection: ref frame intrinsics if available, else per-frame + hfx = hand_fx if ref_k is not None else fx + hfy = hand_fy if ref_k is not None else fy + hcx = hand_cx if ref_k is not None else cx + hcy = hand_cy if ref_k is not None else cy + + if i == 0: + print(f" hand proj intrinsics: fx={hfx:.1f} fy={hfy:.1f} cx={hcx:.1f} cy={hcy:.1f}") + print(f" frame pointmap intr: fx={fx:.1f} fy={fy:.1f} cx={cx:.1f} cy={cy:.1f}") + + # Anchor hand vertices from HaWoR (this frame's pose) + hi = min(fidx, n_hand_frames - 1) + anchor_verts = hand_data[f'{anchor}_vertices'][hi] + + # Hand mask, resized to pointmap resolution + hand_mask_name = f"{anchor}_hand_0" + hand_mask = load_mask(args.mask_dir, fidx, hand_mask_name) + if hand_mask is None: + print(f" frame {fidx:3d}: hand mask missing, skipping (frame keeps ref-scaled translation)") + skipped += 1 + continue + if hand_mask.shape != (pm_h, pm_w): + hand_mask = cv2.resize(hand_mask.astype(np.uint8), (pm_w, pm_h), + interpolation=cv2.INTER_NEAREST).astype(bool) + + # Front-surface centroid via raycasting: each hand-mask pixel shoots a ray from the + # camera and we keep the first hit on the HaWoR mesh. h_real and h_pm are averaged + # over the same hit-pixel set, so k = h_real_z / h_pm_z compares the same physical + # region front-surface-only (no back-facing-vertex bias). + hand_hits, hand_hit_u, hand_hit_v = raycast_first_hits( + anchor_verts, hand_faces, hand_mask, hfx, hfy, hcx, hcy, + max_rays=MAX_HAND_RAYS, rng=rng, + ) + if len(hand_hits) < 10: + print(f" frame {fidx:3d}: too few hand raycast hits ({len(hand_hits)}), skipping") + skipped += 1 + continue + h_real = hand_hits.mean(axis=0) + h_pm = pointmap[hand_hit_v, hand_hit_u].mean(axis=0) + + # Object centroid from pointmap + o_pm = np.mean(pointmap[mask], axis=0) + + # Pointmap-to-real scale factor (from hand depth comparison) + if abs(h_pm[2]) < 1e-6: + print(f" frame {fidx:3d}: hand pointmap depth ~0, skipping") + skipped += 1 + continue + k = h_real[2] / h_pm[2] + + # Object target position: hand anchor + scaled relative offset + obj_target = h_real + k * (o_pm - h_pm) + + # Compute visible-surface centroid of the rotated mesh (filtered by object mask) + verts_rotated = (mesh_verts * mesh_scale) @ rot_matrix.T + verts_with_t = verts_rotated + t_cam + mesh_u, mesh_v = project_to_pixels(verts_with_t, fx, fy, cx, cy, pm_w, pm_h) + mesh_in_mask = mask[mesh_v, mesh_u] + if mesh_in_mask.sum() < 10: + print(f" frame {fidx:3d}: too few mesh pixels in object mask ({mesh_in_mask.sum()}), skipping") + skipped += 1 + continue + c_rot = verts_rotated[mesh_in_mask].mean(axis=0) + + # Solve for translation_scale + opt_scale = compute_optimal_scale(c_rot, t_cam, obj_target) + + # Errors before/after + pos_before = c_rot + t_cam * 1.0 + pos_after = c_rot + t_cam * opt_scale + err_before = np.linalg.norm(pos_before - obj_target) + err_after = np.linalg.norm(pos_after - obj_target) + + print(f" frame {fidx:3d} [{i+1}/{len(frames)}] " + f"scale: {opt_scale:.4f} pm_k: {k:.4f} " + f"err: {err_before:.4f} -> {err_after:.4f}") + + # Visualization + if viz_dir: + img_path = os.path.join(args.frames_dir, f"{fidx:06d}.png") + if not os.path.exists(img_path): + img_path = os.path.join(args.frames_dir, f"{fidx:06d}.jpg") + if os.path.exists(img_path): + img = cv2.imread(img_path) + img_h, img_w = img.shape[:2] + vis = img.copy() + + # Object mask overlay (green) + mask_full = load_mask(args.mask_dir, fidx, args.mask_name) + if mask_full is not None: + if mask_full.shape != (img_h, img_w): + mask_full = cv2.resize(mask_full.astype(np.uint8), (img_w, img_h), + interpolation=cv2.INTER_NEAREST).astype(bool) + overlay = np.zeros_like(vis) + overlay[mask_full] = [0, 200, 0] + vis = cv2.addWeighted(vis, 0.7, overlay, 0.3, 0) + + # Hand mask overlay (orange) + hand_mask_full = load_mask(args.mask_dir, fidx, f"{anchor}_hand_0") + if hand_mask_full is not None: + if hand_mask_full.shape != (img_h, img_w): + hand_mask_full = cv2.resize(hand_mask_full.astype(np.uint8), (img_w, img_h), + interpolation=cv2.INTER_NEAREST).astype(bool) + overlay = np.zeros_like(vis) + overlay[hand_mask_full] = [0, 140, 255] + vis = cv2.addWeighted(vis, 0.85, overlay, 0.15, 0) + + # Use full-res intrinsics for visualization projection + sx_viz, sy_viz = img_w / pm_w, img_h / pm_h + fx_viz, fy_viz = fx * sx_viz, fy * sy_viz + cx_viz, cy_viz = cx * sx_viz, cy * sy_viz + + # Hand projection uses ref-frame intrinsics (matching the computation) + hfx_viz, hfy_viz = hfx * (img_w / hand_proj_w if ref_k is not None else sx_viz), hfy * (img_h / hand_proj_h if ref_k is not None else sy_viz) + hcx_viz, hcy_viz = hcx * (img_w / hand_proj_w if ref_k is not None else sx_viz), hcy * (img_h / hand_proj_h if ref_k is not None else sy_viz) + + # Projected hand vertices (cyan = all HaWoR verts) + all_hand_verts = hand_data[f'{anchor}_vertices'][hi] + hu_all, hv_all = project_to_pixels(all_hand_verts, hfx_viz, hfy_viz, hcx_viz, hcy_viz, img_w, img_h) + for pu, pv in zip(hu_all, hv_all): + cv2.circle(vis, (pu, pv), 2, (200, 200, 0), -1) + # Raycast hits on the HaWoR mesh used for h_real (bright yellow) + hu_hit, hv_hit = project_to_pixels(hand_hits, hfx_viz, hfy_viz, hcx_viz, hcy_viz, img_w, img_h) + for pu, pv in zip(hu_hit, hv_hit): + cv2.circle(vis, (pu, pv), 3, (0, 255, 255), -1) + + # Projected mesh: original (blue) and optimized (red) + t_cam_orig = fr.get("t_cam_orig", t_cam) + verts_orig_scale = (mesh_verts * args.scale) @ rot_matrix.T + t_cam_orig + ou, ov = project_to_pixels(verts_orig_scale, fx_viz, fy_viz, cx_viz, cy_viz, img_w, img_h) + for pu, pv in zip(ou, ov): + cv2.circle(vis, (pu, pv), 1, (255, 0, 0), -1) + + verts_opt = verts_rotated + t_cam * opt_scale + ou2, ov2 = project_to_pixels(verts_opt, fx_viz, fy_viz, cx_viz, cy_viz, img_w, img_h) + for pu, pv in zip(ou2, ov2): + cv2.circle(vis, (pu, pv), 2, (0, 0, 255), -1) + + # Target point (magenta cross) + if obj_target[2] > 0: + tx = int(fx_viz * obj_target[0] / obj_target[2] + cx_viz) + ty = int(fy_viz * obj_target[1] / obj_target[2] + cy_viz) + tx = np.clip(tx, 0, img_w - 1) + ty = np.clip(ty, 0, img_h - 1) + cv2.drawMarker(vis, (tx, ty), (255, 0, 255), cv2.MARKER_CROSS, 20, 2) + + # Legend + cv2.putText(vis, f"frame {fidx} s={opt_scale:.3f} k={k:.3f} err={err_before:.3f}->{err_after:.3f}", + (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2) + cv2.putText(vis, "blue=orig red=opt cyan=hand_verts yellow=raycast_hits green=obj_mask X=target", + (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255, 255, 255), 1) + + cv2.imwrite(os.path.join(viz_dir, f"frame_{fidx:06d}.png"), vis) + + # Update output layout + obj = output_data["objects"][fr["obj_index"]] + optimized_t = (t_cam * opt_scale).tolist() + obj["local_to_scene"]["translation_camera_frame"] = optimized_t + obj["local_to_scene"]["translation_scale_optimized"] = float(opt_scale) + + per_frame_scales.append({ + "frame_idx": fidx, + "translation_scale": float(opt_scale), + "pointmap_scale": float(k), + "error_before": float(err_before), + "error_after": float(err_after), + "obj_target": obj_target.tolist(), + "mask_pixels": int(n_pixels), + }) + + # Store summary in output + output_data["translation_scale_optimization"] = { + "method": "hand_anchored_pointmap", + "mesh_scale_original": args.scale, + "mesh_scale": mesh_scale, + "ref_frame": args.ref_frame, + "ref_frame_k": ref_k, + "mask_name": args.mask_name, + "anchor_hand": args.anchor_hand, + "per_frame": per_frame_scales, + } + + # Write output + os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True) + with open(args.output, 'w') as f: + json.dump(output_data, f, indent=2) + + # Summary + if per_frame_scales: + scales = [s["translation_scale"] for s in per_frame_scales] + ks = [s["pointmap_scale"] for s in per_frame_scales] + errs_before = [s["error_before"] for s in per_frame_scales] + errs_after = [s["error_after"] for s in per_frame_scales] + print(f"\nDone. Optimized {len(per_frame_scales)} frames ({skipped} skipped).") + print(f" Scale range: [{min(scales):.4f}, {max(scales):.4f}]") + print(f" Scale mean: {np.mean(scales):.4f} std: {np.std(scales):.4f}") + print(f" PM scale mean: {np.mean(ks):.4f} std: {np.std(ks):.4f}") + print(f" Error mean: {np.mean(errs_before):.4f} -> {np.mean(errs_after):.4f}") + else: + print(f"\nNo frames optimized ({skipped} skipped).") + print(f"Output: {args.output}") + + +if __name__ == "__main__": + main() diff --git a/reconstruction/scripts/predict_video_gravity.py b/reconstruction/scripts/predict_video_gravity.py new file mode 100644 index 0000000000000000000000000000000000000000..b659f6654d7731532020c1c68a97534be4a11025 --- /dev/null +++ b/reconstruction/scripts/predict_video_gravity.py @@ -0,0 +1,233 @@ +"""Predict gravity for a static-camera video given a directory of frames. + +Runs GeoCalib per-frame, then aggregates using confidence-weighted spherical +mean with MAD-based outlier rejection. + +Usage: + python predict_video_gravity.py [--camera_model pinhole|simple_radial|simple_divisional] +""" + +import argparse +import json +import math +from pathlib import Path + +import torch +import numpy as np + +from geocalib import GeoCalib +from geocalib.gravity import Gravity +from geocalib.utils import print_calibration + + +IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"} + + +def angle_between(v1: torch.Tensor, v2: torch.Tensor) -> torch.Tensor: + """Angular distance (radians) between two unit vectors.""" + dot = (v1 * v2).sum(dim=-1).clamp(-1.0, 1.0) + return torch.acos(dot) + + +def spherical_mean(vecs: torch.Tensor, weights: torch.Tensor | None = None) -> torch.Tensor: + """Compute the weighted spherical mean of unit vectors.""" + if weights is not None: + weights = weights / weights.sum() + mean = (vecs * weights.unsqueeze(-1)).sum(dim=0) + else: + mean = vecs.mean(dim=0) + return torch.nn.functional.normalize(mean, dim=-1) + + +def predict_video_gravity( + frames_dir: str, + camera_model: str = "pinhole", + mad_threshold: float = 3.0, + max_frames: int | None = None, + device: str | None = None, +) -> dict: + """Predict gravity for a static-camera video. + + Args: + frames_dir: Directory containing image frames. + camera_model: GeoCalib camera model ('pinhole', 'simple_radial', 'simple_divisional'). + mad_threshold: Outlier rejection threshold in units of MAD (higher = less aggressive). + max_frames: If set, subsample at most this many frames. + device: Torch device string. Defaults to CUDA if available. + + Returns: + dict with keys: + gravity: Gravity object (final estimate) + roll_deg, pitch_deg: angles in degrees + n_frames: total frames processed + n_inliers: frames kept after outlier rejection + per_frame: list of per-frame dicts + """ + if device is None: + device = "cuda" if torch.cuda.is_available() else "cpu" + + frames_dir = Path(frames_dir) + image_paths = sorted(p for p in frames_dir.iterdir() if p.suffix.lower() in IMAGE_EXTS) + + if not image_paths: + raise ValueError(f"No images found in {frames_dir}") + + if max_frames is not None and len(image_paths) > max_frames: + # Uniformly subsample + indices = np.round(np.linspace(0, len(image_paths) - 1, max_frames)).astype(int) + image_paths = [image_paths[i] for i in indices] + + weights = "pinhole" if camera_model == "pinhole" else "distorted" + model = GeoCalib(weights=weights).to(device) + model.eval() + + print(f"Running GeoCalib on {len(image_paths)} frames...") + + gravity_vecs = [] # [N, 3] unit vectors + confidences = [] # [N] scalar confidence per frame + per_frame = [] + + with torch.no_grad(): + for i, path in enumerate(image_paths): + try: + img = model.load_image(str(path)).to(device) + results = model.calibrate(img, camera_model=camera_model) + + grav = results["gravity"] # Gravity object, shape [1] + vec = grav.vec3d.squeeze(0).cpu() # [3] + + # Use mean of up- and latitude-confidence as frame weight + up_conf = results["up_confidence"].mean().item() + lat_conf = results["latitude_confidence"].mean().item() + conf = (up_conf + lat_conf) / 2.0 + + gravity_vecs.append(vec) + confidences.append(conf) + per_frame.append({ + "path": str(path), + "vec": vec, + "roll_deg": math.degrees(grav.roll.item()), + "pitch_deg": math.degrees(grav.pitch.item()), + "confidence": conf, + "outlier": False, + }) + + if (i + 1) % 10 == 0 or i == len(image_paths) - 1: + print(f" [{i+1}/{len(image_paths)}] roll={per_frame[-1]['roll_deg']:.1f}° " + f"pitch={per_frame[-1]['pitch_deg']:.1f}° conf={conf:.3f}") + + except Exception as e: + print(f" Warning: failed on {path.name}: {e}") + + if not gravity_vecs: + raise RuntimeError("No frames successfully processed.") + + vecs = torch.stack(gravity_vecs) # [N, 3] + confs = torch.tensor(confidences) # [N] + + # --- Step 1: Compute initial unweighted spherical mean --- + mean_vec = spherical_mean(vecs) + + # --- Step 2: Compute per-frame angle to the mean --- + angles = angle_between(vecs, mean_vec.unsqueeze(0).expand_as(vecs)) # [N] + + # --- Step 3: MAD-based outlier rejection --- + median_angle = angles.median() + mad = (angles - median_angle).abs().median() + mad = mad.clamp(min=1e-6) # avoid division by zero + + threshold = median_angle + mad_threshold * mad + inlier_mask = angles <= threshold + + n_inliers = inlier_mask.sum().item() + print(f"\nOutlier rejection: {n_inliers}/{len(vecs)} frames kept " + f"(threshold={math.degrees(threshold.item()):.2f}°, " + f"median angle={math.degrees(median_angle.item()):.2f}°, " + f"MAD={math.degrees(mad.item()):.2f}°)") + + for i, is_outlier in enumerate((~inlier_mask).tolist()): + per_frame[i]["outlier"] = is_outlier + + # --- Step 4: Confidence-weighted spherical mean over inliers --- + inlier_vecs = vecs[inlier_mask] + inlier_confs = confs[inlier_mask] + + final_vec = spherical_mean(inlier_vecs, weights=inlier_confs) + final_gravity = Gravity(final_vec.unsqueeze(0).to(device)) + + roll_deg = math.degrees(final_gravity.roll.item()) + pitch_deg = math.degrees(final_gravity.pitch.item()) + + return { + "gravity": final_gravity, + "vec": final_vec, + "roll_deg": roll_deg, + "pitch_deg": pitch_deg, + "n_frames": len(vecs), + "n_inliers": n_inliers, + "per_frame": per_frame, + } + + +def main(): + parser = argparse.ArgumentParser(description="Predict gravity for a static-camera video.") + parser.add_argument("frames_dir", help="Directory of image frames.") + parser.add_argument( + "--camera_model", + default="pinhole", + choices=["pinhole", "simple_radial", "simple_divisional"], + ) + parser.add_argument( + "--mad_threshold", + type=float, + default=3.0, + help="MAD multiplier for outlier rejection (default: 3.0).", + ) + parser.add_argument( + "--max_frames", + type=int, + default=None, + help="Uniformly subsample to at most this many frames.", + ) + parser.add_argument("--device", default=None, help="Torch device (default: auto).") + parser.add_argument("--output_path", default=None, help="Save results as JSON to this path.") + args = parser.parse_args() + + result = predict_video_gravity( + args.frames_dir, + camera_model=args.camera_model, + mad_threshold=args.mad_threshold, + max_frames=args.max_frames, + device=args.device, + ) + + print("\n=== Final Gravity Estimate ===") + print(f" Roll: {result['roll_deg']:+.2f}°") + print(f" Pitch: {result['pitch_deg']:+.2f}°") + print(f" Vec3D: {result['vec'].tolist()}") + print(f" Frames: {result['n_inliers']} inliers / {result['n_frames']} total") + + if args.output_path is not None: + output = { + "roll_deg": result["roll_deg"], + "pitch_deg": result["pitch_deg"], + "vec3d": result["vec"].tolist(), + "n_frames": result["n_frames"], + "n_inliers": result["n_inliers"], + "per_frame": [ + { + "path": f["path"], + "roll_deg": f["roll_deg"], + "pitch_deg": f["pitch_deg"], + "confidence": f["confidence"], + "outlier": f["outlier"], + } + for f in result["per_frame"] + ], + } + Path(args.output_path).write_text(json.dumps(output, indent=2)) + print(f"\nSaved to {args.output_path}") + + +if __name__ == "__main__": + main() diff --git a/reconstruction/scripts/prepare_dexycb.py b/reconstruction/scripts/prepare_dexycb.py new file mode 100644 index 0000000000000000000000000000000000000000..4339138b2e57cfca26ae8a5977684aca28cec630 --- /dev/null +++ b/reconstruction/scripts/prepare_dexycb.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Pack a DexYCB camera folder (color_XXXXXX.jpg) into a reconstruction clip. + +Writes: + /all_frames/%06d.png + /clip.mp4 + /config.json +""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +_RECON_ROOT = Path(__file__).resolve().parents[1] + + +def find_ffmpeg() -> str: + env = os.environ.get("FFMPEG") + if env and Path(env).is_file(): + return env + which = shutil.which("ffmpeg") + if which: + return which + bundled = _RECON_ROOT / ".venv" / "bin" / "ffmpeg" + if bundled.is_file() or bundled.is_symlink(): + return str(bundled) + try: + import imageio_ffmpeg + + return imageio_ffmpeg.get_ffmpeg_exe() + except Exception as exc: + raise FileNotFoundError( + "ffmpeg not found. From reconstruction/ run: ./setup.sh" + ) from exc + +YCB_NAMES = { + 1: "master chef can", + 2: "cracker box", + 3: "sugar box", + 4: "tomato soup can", + 5: "mustard bottle", + 6: "tuna fish can", + 7: "pudding box", + 8: "gelatin box", + 9: "potted meat can", + 10: "banana", + 11: "pitcher", + 12: "bleach cleanser", + 13: "bowl", + 14: "mug", + 15: "power drill", + 16: "wood block", + 17: "scissors", + 18: "large marker", + 19: "extra large clamp", + 20: "foam brick", +} + + +def _sorted_color_frames(cam_dir: Path) -> list[Path]: + frames = sorted(cam_dir.glob("color_*.jpg")) + if not frames: + frames = sorted(cam_dir.glob("color_*.png")) + return frames + + +def _infer_object_and_hand(cam_dir: Path) -> tuple[str | None, str | None]: + try: + import numpy as np + except ImportError: + return None, None + labels = sorted(cam_dir.glob("labels_*.npz")) + if not labels: + return None, None + data = np.load(labels[0], allow_pickle=True) + obj = None + hand = None + if "ycb_ids" in data.files: + ids = np.array(data["ycb_ids"]).reshape(-1) + if len(ids): + obj = YCB_NAMES.get(int(ids[0]), f"object {int(ids[0])}") + if "ycb_grasp_ind" in data.files and "ycb_ids" in data.files: + ids = np.array(data["ycb_ids"]).reshape(-1) + gi = int(np.array(data["ycb_grasp_ind"]).reshape(-1)[0]) + if 0 <= gi < len(ids): + obj = YCB_NAMES.get(int(ids[gi]), obj) + if "mano_side" in data.files: + side = data["mano_side"] + if hasattr(side, "item"): + side = side.item() + hand = str(side) + return obj, hand + + +def main() -> int: + p = argparse.ArgumentParser(description="Prepare a DexYCB camera sequence for reconstruction") + p.add_argument("--camera-dir", required=True, help=".../YYYYMMDD-subject-XX/seq/SERIAL") + p.add_argument("--out", required=True, help="Output clip directory") + p.add_argument("--object", default=None, help="Object text prompt (overrides labels)") + p.add_argument("--hand", default=None, choices=["left", "right"], help="Anchor hand") + p.add_argument("--frame", type=int, default=0, help="Reference frame index") + p.add_argument("--fps", type=float, default=30.0) + args = p.parse_args() + + cam_dir = Path(args.camera_dir).resolve() + if not cam_dir.is_dir(): + print(f"not a directory: {cam_dir}", file=sys.stderr) + return 1 + frames = _sorted_color_frames(cam_dir) + if not frames: + print(f"no color_*.jpg in {cam_dir}", file=sys.stderr) + return 1 + + inferred_obj, inferred_hand = _infer_object_and_hand(cam_dir) + obj = args.object or inferred_obj or "object" + hand = args.hand or inferred_hand or "right" + + out = Path(args.out).resolve() + frames_dir = out / "all_frames" + frames_dir.mkdir(parents=True, exist_ok=True) + + from PIL import Image + + for i, src in enumerate(frames): + dst = frames_dir / f"{i:06d}.png" + if dst.exists(): + continue + Image.open(src).convert("RGB").save(dst) + + clip = out / "clip.mp4" + if clip.exists(): + print(f"skip ffmpeg encode ({clip} already exists)") + else: + cmd = [ + find_ffmpeg(), "-y", + "-framerate", str(args.fps), + "-i", str(frames_dir / "%06d.png"), + "-c:v", "libx264", "-pix_fmt", "yuv420p", + str(clip), + ] + subprocess.run(cmd, check=True) + + n = max(0, min(args.frame, len(frames) - 1)) + shutil.copy2(frames_dir / f"{n:06d}.png", out / f"{n:04d}.png") + + cfg = { + "source": str(cam_dir), + "frame_number": n, + "object_names": [obj], + "anchor_hand": hand, + "num_frames": len(frames), + } + (out / "config.json").write_text(json.dumps(cfg, indent=2) + "\n") + print(f"wrote {clip} ({len(frames)} frames), object={obj!r}, hand={hand!r}, ref={n}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/reconstruction/scripts/run_interformer.py b/reconstruction/scripts/run_interformer.py new file mode 100644 index 0000000000000000000000000000000000000000..34f8640c5322cfee75ed6fb9dd8b9e1b9c08bbcd --- /dev/null +++ b/reconstruction/scripts/run_interformer.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +"""Run InterFormer (egocentric hand–object parsing) on every frame of a clip. + +Does not import third-party/do-as-i-do. Uses reconstruction/modules/InterFormer. + +Output (default: /video_segmentation/interformer/): + masks/frame_XXXXXX_masks/.png + overlays/frame_XXXXXX.png + semantic/frame_XXXXXX.png + tracked_interformer.mp4 + +6-class EgoHOS names (config_interformer.py num_classes=6): + background, left_hand, right_hand, left_object, right_object, two_object + +Union object mask is also written as .png (default: object). +""" + +from __future__ import annotations + +import argparse +import os +import subprocess +import sys +from pathlib import Path + +import cv2 +import numpy as np + +_RECON_ROOT = Path(__file__).resolve().parents[1] +_IF_DIR = Path(os.environ.get("INTERFORMER_DIR", _RECON_ROOT / "modules" / "InterFormer")) +sys.path.insert(0, str(_IF_DIR)) + + +def _raise_mmdet_mmcv_cap() -> None: + """mmdet 3.x asserts mmcv<2.2.0; source-built mmcv for torch 2.11 is 2.2.0.""" + try: + import site + + paths = [] + try: + paths.extend(site.getsitepackages()) + except Exception: + pass + try: + paths.append(site.getusersitepackages()) + except Exception: + pass + for sp in paths: + init = Path(sp) / "mmdet" / "__init__.py" + if not init.is_file(): + continue + text = init.read_text() + if "mmcv_maximum_version = '2.2.0'" in text: + init.write_text( + text.replace( + "mmcv_maximum_version = '2.2.0'", + "mmcv_maximum_version = '2.3.0'", + ) + ) + except OSError: + pass + + +_raise_mmdet_mmcv_cap() + +EGOHOS6 = [ + "background", + "left_hand", + "right_hand", + "left_object", + "right_object", + "two_object", +] +EGOHOS9 = [ + "background", + "left_hand", + "right_hand", + "left_object", + "right_object", + "two_object", + "left_object2", + "right_object2", + "two_object2", +] +PALETTE = np.array( + [ + [0, 0, 0], + [255, 0, 0], + [0, 0, 255], + [255, 0, 255], + [0, 255, 255], + [0, 255, 0], + [255, 204, 255], + [204, 255, 255], + [204, 255, 204], + ], + dtype=np.uint8, +) +OBJECT_CLASSES = { + "left_object", + "right_object", + "two_object", + "left_object2", + "right_object2", + "two_object2", +} + + +def _find_checkpoint(explicit: str | None) -> Path: + if explicit: + p = Path(explicit) + if not p.is_file(): + raise FileNotFoundError(f"checkpoint not found: {p}") + return p + env = os.environ.get("INTERFORMER_CHECKPOINT") + if env: + p = Path(env) + if p.is_file(): + return p + ckpt_dir = Path( + os.environ.get( + "INTERFORMER_CKPT_DIR", + _RECON_ROOT.parent / "checkpoints" / "interformer", + ) + ) + if ckpt_dir.is_file(): + return ckpt_dir + hits: list[Path] = [] + if ckpt_dir.is_dir(): + for pat in ("*.pth", "*.pt", "*.ckpt"): + hits.extend(sorted(ckpt_dir.glob(pat))) + hits.extend(sorted(ckpt_dir.glob(f"**/{pat}"))) + hits = [h for h in hits if h.is_file() and "backbone" not in h.name.lower()] + if hits: + return hits[0] + raise FileNotFoundError( + "No InterFormer weights under checkpoints/interformer.\n" + "Put the trained .pth there (README: Google Drive " + "https://drive.google.com/file/d/172Hi0jTTijEnbroYSUZgOfpsyue_HHxg )." + ) + + +def _list_frames(video: str, frames_dir: str | None) -> list[Path]: + if frames_dir: + d = Path(frames_dir) + frames = sorted(d.glob("*.png")) + sorted(d.glob("*.jpg")) + if not frames: + raise FileNotFoundError(f"no images in {d}") + return frames + vp = Path(video) + if vp.is_dir(): + frames = sorted(vp.glob("*.png")) + sorted(vp.glob("*.jpg")) + if frames: + return frames + raise FileNotFoundError(f"no images in {vp}") + sibling = vp.parent / "all_frames" + if sibling.is_dir(): + frames = sorted(sibling.glob("*.png")) + if frames: + return frames + cap = cv2.VideoCapture(str(vp)) + if not cap.isOpened(): + raise FileNotFoundError(f"cannot open {vp}") + tmp = vp.parent / "all_frames" + tmp.mkdir(parents=True, exist_ok=True) + i = 0 + while True: + ok, bgr = cap.read() + if not ok: + break + out = tmp / f"{i:06d}.png" + if not out.exists(): + cv2.imwrite(str(out), bgr) + i += 1 + cap.release() + return sorted(tmp.glob("*.png")) + + +def _colorize(sem: np.ndarray) -> np.ndarray: + h, w = sem.shape + rgb = np.zeros((h, w, 3), dtype=np.uint8) + for i in range(min(len(PALETTE), int(sem.max()) + 1)): + rgb[sem == i] = PALETTE[i] + return rgb + + +def main() -> int: + p = argparse.ArgumentParser(description="InterFormer HOI segmentation on all frames") + p.add_argument("--video", type=str, default=None, help="clip.mp4 or a frames directory") + p.add_argument("--frames-dir", type=str, default=None, help="directory of PNG/JPG frames") + p.add_argument("--output-dir", type=str, default=None) + p.add_argument("--checkpoint", type=str, default=None) + p.add_argument( + "--config", + type=str, + default=None, + help="default: modules/InterFormer/mmseg/configs/config_interformer.py", + ) + p.add_argument("--object-id", type=str, default="object", help="filename for union object mask") + p.add_argument("--device", type=str, default=None) + p.add_argument("--skip-existing", action="store_true") + args = p.parse_args() + + if not args.video and not args.frames_dir: + p.error("pass --video or --frames-dir") + + ckpt = _find_checkpoint(args.checkpoint) + cfg_path = Path( + args.config + or os.environ.get( + "INTERFORMER_CONFIG", + _IF_DIR / "mmseg" / "configs" / "config_interformer.py", + ) + ) + if not cfg_path.is_file(): + raise FileNotFoundError(f"InterFormer config missing: {cfg_path}") + + frames = _list_frames(args.video or "", args.frames_dir) + if args.output_dir: + out_root = Path(args.output_dir) + else: + base = Path(args.video).resolve().parent if args.video else frames[0].parent.parent + if (base / "clip.mp4").exists() or (base / "all_frames").exists(): + out_root = base / "video_segmentation" / "interformer" + else: + out_root = base / "interformer" + masks_root = out_root / "masks" + overlay_dir = out_root / "overlays" + semantic_dir = out_root / "semantic" + overlay_dir.mkdir(parents=True, exist_ok=True) + semantic_dir.mkdir(parents=True, exist_ok=True) + + device = args.device or ("cuda:0" if os.environ.get("CUDA_VISIBLE_DEVICES") is not None else "cuda:0") + try: + import torch + + if not torch.cuda.is_available(): + device = "cpu" + except ImportError: + pass + + print(f"InterFormer config: {cfg_path}") + print(f"checkpoint: {ckpt}") + print(f"frames: {len(frames)} out: {out_root}") + + from mmseg.apis import inference_model, init_model + + model = init_model(str(cfg_path), str(ckpt), device=device) + ncls = int(model.decode_head.num_classes) + names = EGOHOS6 if ncls <= 6 else EGOHOS9 + names = names[:ncls] + print(f"classes ({ncls}): {names}") + + nonempty = {n: 0 for n in names} + for i, fpath in enumerate(frames): + frame_i = i + stem_digits = "".join(ch for ch in fpath.stem if ch.isdigit()) + if stem_digits: + frame_i = int(stem_digits) + frame_dir = masks_root / f"frame_{frame_i:06d}_masks" + obj_png = frame_dir / f"{args.object_id}.png" + if args.skip_existing and obj_png.is_file(): + m = cv2.imread(str(obj_png), cv2.IMREAD_GRAYSCALE) + if m is not None and int(m.max()) > 0: + print(f"[{i+1}/{len(frames)}] skip {fpath.name}") + continue + + bgr = cv2.imread(str(fpath), cv2.IMREAD_COLOR) + if bgr is None: + print(f"skip unreadable {fpath}", file=sys.stderr) + continue + h0, w0 = bgr.shape[:2] + result = inference_model(model, str(fpath)) + sem = result.pred_sem_seg.data.cpu().numpy() + if sem.ndim == 3: + sem = sem[0] + if sem.shape[0] != h0 or sem.shape[1] != w0: + sem = cv2.resize(sem.astype(np.uint8), (w0, h0), interpolation=cv2.INTER_NEAREST) + + frame_dir.mkdir(parents=True, exist_ok=True) + union_obj = np.zeros((h0, w0), dtype=np.uint8) + for cid, cname in enumerate(names): + if cname == "background": + continue + binm = (sem == cid).astype(np.uint8) * 255 + if binm.max() > 0: + nonempty[cname] += 1 + cv2.imwrite(str(frame_dir / f"{cname}.png"), binm) + if cname in OBJECT_CLASSES: + union_obj = np.maximum(union_obj, binm) + if cname == "right_hand": + cv2.imwrite(str(frame_dir / "right_hand_0.png"), binm) + if cname == "left_hand": + cv2.imwrite(str(frame_dir / "left_hand_0.png"), binm) + cv2.imwrite(str(obj_png), union_obj) + + color = _colorize(sem) + overlay = cv2.addWeighted(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB), 0.55, color, 0.45, 0) + cv2.imwrite( + str(overlay_dir / f"frame_{frame_i:06d}.png"), + cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR), + ) + cv2.imwrite(str(semantic_dir / f"frame_{frame_i:06d}.png"), cv2.cvtColor(color, cv2.COLOR_RGB2BGR)) + cov = 100.0 * (union_obj > 0).mean() + print(f"[{i+1}/{len(frames)}] {fpath.name} object_cov={cov:.2f}%") + + ffmpeg = os.environ.get("FFMPEG") or shutil_which("ffmpeg") + if ffmpeg and overlay_dir.glob("frame_*.png"): + mp4 = out_root / "tracked_interformer.mp4" + subprocess.run( + [ + ffmpeg, "-y", "-framerate", "24", + "-i", str(overlay_dir / "frame_%06d.png"), + "-c:v", "libx264", "-pix_fmt", "yuv420p", str(mp4), + ], + check=False, + ) + print(f"video: {mp4}") + + print("nonempty frames per class:") + for n, c in nonempty.items(): + if n == "background": + continue + print(f" {n}: {c}/{len(frames)}") + print(f"done: {out_root}") + return 0 + + +def shutil_which(name: str) -> str | None: + import shutil + + return shutil.which(name) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/reconstruction/scripts/run_project_mesh_combined.py b/reconstruction/scripts/run_project_mesh_combined.py new file mode 100644 index 0000000000000000000000000000000000000000..eaa95740c869dcd836544d471b94b39b37762d0e --- /dev/null +++ b/reconstruction/scripts/run_project_mesh_combined.py @@ -0,0 +1,530 @@ +""" +Project meshes for all frames in a layout JSON, in-process (no subprocesses). + +Scale and intrinsics are read from the layout JSON itself (no CLI args needed). +Uses new_quat + manual pose-to-camera frame conversion pipeline. + +Usage: +python run_project_mesh_combined.py \ + --video /path/to/video.mp4 \ + --mesh /path/to/video_dir/video_segmentation/masks/frame_000010_masks//.obj \ + --json /path/to/video_dir/obj_tracking_out//combined_visualization/layout.json \ + --output-base /path/to/video_dir/obj_tracking_out//combined_visualization/projected +""" + +import argparse +import glob +import json +import os +import re +import subprocess +import sys + +import cv2 +import numpy as np +import torch +from scipy.spatial.transform import Rotation as R + +from pytorch3d.renderer import ( + PerspectiveCameras, + PointLights, + RasterizationSettings, + MeshRenderer, + MeshRasterizer, + SoftPhongShader, + TexturesVertex, +) +from pytorch3d.io import load_objs_as_meshes +from pytorch3d.structures import Meshes + + +def parse_args(): + parser = argparse.ArgumentParser( + description="Project meshes for all frames in a layout JSON (single process).", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument("--video", required=True, + help="Path to input video (MP4 file) OR directory of " + "0-indexed PNG frames named NNNNNN.png.") + parser.add_argument("--mesh", required=True, help="Path to object mesh (.obj)") + parser.add_argument("--json", required=True, help="Path to layout JSON") + parser.add_argument("--output-base", required=True, help="Output directory for frames") + parser.add_argument("--hand-meshes", default=None, help="Path to hand meshes NPZ file") + parser.add_argument("--hands", default="both", choices=["left", "right", "both"], + help="Which hand(s) to render") + parser.add_argument("--layer-order", default="hand_front", + choices=["object_front", "hand_front"], + help="Which layer appears in front") + parser.add_argument("--device", default="auto", choices=["auto", "cpu", "cuda"], + help="Device to use for rendering") + parser.add_argument("--object-color", default=None, + help="Solid RGB color (0-1) for the object as 'r,g,b' " + "(e.g. '0.6,0.9,0.6'). If set, overrides the mesh's " + "loaded textures.") + parser.add_argument("--left-hand-color", default="0.8,0.5,0.5", + help="Solid RGB color (0-1) for the left hand as 'r,g,b'.") + parser.add_argument("--right-hand-color", default="0.5,0.5,0.8", + help="Solid RGB color (0-1) for the right hand as 'r,g,b'.") + parser.add_argument("--use-optimized-mesh-scale", action="store_true", + help="Use top-level translation_scale_optimization.mesh_scale " + "(optimized) instead of per-frame local_to_scene.scale " + "(== mesh_scale_original).") + return parser.parse_args() + + +def _parse_rgb(s): + parts = [float(x) for x in s.split(',')] + if len(parts) != 3: + raise ValueError(f"Expected 'r,g,b'; got {s!r}") + return tuple(parts) + + +def cam_to_pytorch3d(verts_cam): + """Convert vertices from camera frame (x-right, y-down, z-fwd) to PyTorch3D frame (x-left, y-up, z-fwd).""" + verts_p3d = torch.zeros_like(verts_cam) + verts_p3d[:, 0] = -verts_cam[:, 0] + verts_p3d[:, 1] = -verts_cam[:, 1] + verts_p3d[:, 2] = verts_cam[:, 2] + return verts_p3d + + +def make_renderer(fx, fy, cx, cy, width, height, device): + """Create a PyTorch3D renderer with given camera intrinsics.""" + focal_length = torch.tensor([[fx, fy]], dtype=torch.float32, device=device) + principal_point = torch.tensor([[cx, cy]], dtype=torch.float32, device=device) + + cameras = PerspectiveCameras( + focal_length=focal_length, + principal_point=principal_point, + image_size=((height, width),), + in_ndc=False, + device=device, + ) + + # bin_size=None lets pytorch3d auto-pick the coarse-to-fine binning, which + # avoids the sub-pixel coverage gaps ("speckles") that bin_size=0 (naive + # rasterization) produces on dense meshes. faces_per_pixel>1 + tiny blur + # also fill gaps when small faces fall between pixel centers. + # max_faces_per_bin is generous so dense reconstructed meshes (~36k faces + # observed in the wild) don't silently truncate with "Bin size was too small + # in the coarse rasterization phase" overflow warnings. + raster_settings = RasterizationSettings( + image_size=(height, width), + blur_radius=1e-5, + faces_per_pixel=8, + bin_size=None, + max_faces_per_bin=200000, + ) + + lights = PointLights(device=device, location=[[0.0, 0.0, -3.0]]) + + return MeshRenderer( + rasterizer=MeshRasterizer(cameras=cameras, raster_settings=raster_settings), + shader=SoftPhongShader(device=device, cameras=cameras, lights=lights), + ) + + +def transform_to_camera_frame(verts, rot_matrix, translation, scale, device, + camera_frame=False): + """Apply scale + rotation + translation to vertices and return them in the + camera frame (x-right, y-down, z-fwd). If camera_frame=True, the rotation + and translation are already camera-frame and the axis swap is skipped.""" + verts_scaled = verts * scale + R_torch = torch.tensor(rot_matrix, dtype=torch.float32, device=device) + T_torch = torch.tensor(translation, dtype=torch.float32, device=device) + verts_pose = verts_scaled @ R_torch.T + T_torch + + if camera_frame: + return verts_pose + # Pose frame (x-fwd, y-left, z-up) -> camera frame (x-right, y-down, z-fwd) + verts_cam = torch.zeros_like(verts_pose) + verts_cam[:, 0] = -verts_pose[:, 1] + verts_cam[:, 1] = -verts_pose[:, 2] + verts_cam[:, 2] = verts_pose[:, 0] + return verts_cam + + +def render_mesh(mesh, rot_matrix, translation, scale, renderer, device, + camera_frame=False): + """Render mesh with given pose. Returns rgb (H,W,3) float [0,1] and alpha (H,W) float [0,1]. + + If camera_frame=True, (rot_matrix, translation) are interpreted as already in + the camera frame and the pose->camera axis swap is skipped. + """ + verts_cam = transform_to_camera_frame( + mesh.verts_packed(), rot_matrix, translation, scale, device, camera_frame, + ) + verts_p3d = cam_to_pytorch3d(verts_cam) + + mesh_transformed = mesh.clone() + mesh_transformed = mesh_transformed.update_padded(verts_p3d.unsqueeze(0)) + + images = renderer(mesh_transformed) + return images[0, ..., :3].cpu().numpy(), images[0, ..., 3].cpu().numpy() + + +def render_hand_mesh(vertices, faces, renderer, device, color=(0.8, 0.7, 0.6)): + """Render a hand mesh. Vertices are already in camera frame.""" + verts_cam = torch.tensor(vertices, dtype=torch.float32, device=device) + verts_p3d = cam_to_pytorch3d(verts_cam) + + faces_torch = torch.tensor(faces, dtype=torch.int64, device=device) + textures = TexturesVertex( + verts_features=torch.tensor([[color]], dtype=torch.float32, device=device).expand(-1, verts_p3d.shape[0], -1) + ) + hand_mesh = Meshes(verts=[verts_p3d], faces=[faces_torch], textures=textures) + + images = renderer(hand_mesh) + return images[0, ..., :3].cpu().numpy(), images[0, ..., 3].cpu().numpy() + + +def render_combined(meshes_data, renderer, device): + """Render multiple meshes in one pass so the rasterizer's z-buffer handles + inter-mesh occlusion correctly. + + meshes_data: list of (verts_cam, faces, color) tuples. + verts_cam: (V, 3) torch.Tensor already in camera frame (x-right, y-down, z-fwd). + faces: (F, 3) torch.Tensor int64 (on any device; moved to `device`). + color: (r, g, b) float tuple in [0, 1]. + Returns (rgb, alpha) numpy arrays in [0, 1]. + """ + verts_p3d_list = [] + faces_list = [] + feats_list = [] + offset = 0 + for verts_cam, faces, color in meshes_data: + verts_p3d = cam_to_pytorch3d(verts_cam) + n = verts_p3d.shape[0] + verts_p3d_list.append(verts_p3d) + faces_list.append(faces.to(device=device, dtype=torch.int64) + offset) + color_t = torch.tensor(color, dtype=torch.float32, device=device) + feats_list.append(color_t.expand(n, 3)) + offset += n + + verts_cat = torch.cat(verts_p3d_list, dim=0) + faces_cat = torch.cat(faces_list, dim=0) + feats_cat = torch.cat(feats_list, dim=0).unsqueeze(0) # (1, V, 3) + combined = Meshes( + verts=[verts_cat], + faces=[faces_cat], + textures=TexturesVertex(verts_features=feats_cat), + ) + images = renderer(combined) + return images[0, ..., :3].cpu().numpy(), images[0, ..., 3].cpu().numpy() + + +def read_video_frame(cap, frame_idx, last_read_idx): + """Read a specific frame from the video capture, seeking only if necessary. + Returns (frame_rgb, new_last_read_idx) or (None, last_read_idx) on failure.""" + if frame_idx != last_read_idx + 1: + cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx) + ret, frame_bgr = cap.read() + if not ret: + return None, last_read_idx + frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB) + return frame_rgb, frame_idx + + +class DirectoryVideoReader: + """Drop-in replacement for cv2.VideoCapture when the 'video' is a directory + of PNG/JPG frames named NNNNNN.png (0-indexed). Exposes read_frame(idx) and + .width / .height, plus a no-op release() so calling code can stay uniform. + """ + + _EXTS = (".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".webp") + + def __init__(self, frames_dir): + self.dir = frames_dir + paths = {} + for name in os.listdir(frames_dir): + stem, ext = os.path.splitext(name) + if ext.lower() not in self._EXTS: + continue + try: + idx = int(stem) + except ValueError: + continue + paths[idx] = os.path.join(frames_dir, name) + if not paths: + raise FileNotFoundError( + f"No numerically-named frame images found in {frames_dir}") + self.paths = paths + first = cv2.imread(paths[min(paths)]) + if first is None: + raise IOError(f"Could not read first frame in {frames_dir}") + self.height, self.width = first.shape[:2] + + def read_frame(self, frame_idx): + p = self.paths.get(frame_idx) + if p is None: + return None + bgr = cv2.imread(p) + if bgr is None: + return None + return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) + + def release(self): + pass + + +def main(): + args = parse_args() + + # Device + if args.device == "auto": + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + else: + device = torch.device(args.device) + print(f"Using device: {device}") + + # Load layout JSON + with open(args.json) as f: + data = json.load(f) + + objects = [obj for obj in data["objects"] if "frame_idx" in obj] + if not objects: + print("No objects with frame_idx found in layout JSON.") + return + print(f"Loaded layout.json with {len(objects)} objects to render") + + # Sort by frame_idx for sequential video reading + objects.sort(key=lambda o: o["frame_idx"]) + + # Pre-compute fallback intrinsics: first frame that has intrinsics_normalized + fallback_intr = None + for obj in objects: + if "intrinsics_normalized" in obj: + fallback_intr = obj["intrinsics_normalized"] + print(f"Fallback intrinsics from frame {obj['frame_idx']}: " + f"fx_norm={fallback_intr['fx_norm']:.5f}, fy_norm={fallback_intr['fy_norm']:.5f}") + break + if fallback_intr is None: + print("[error] No frame in layout JSON has intrinsics_normalized.") + sys.exit(1) + + # Auto-detect camera-frame layout (output of camera-frame optimization). + # In that mode the optimized pose lives in *_camera_frame fields and the + # top-level translation_scale_optimization.mesh_scale supersedes per-frame scale. + is_camera_frame_layout = data.get("frame") == "camera_frame" + if is_camera_frame_layout: + print("Detected camera-frame layout — using " + "translation_camera_frame + quat_wxyz_camera_frame " + "and skipping pose->camera axis swap.") + + # Optionally swap to the top-level optimized mesh_scale (uniform across frames) + override_scale = None + if args.use_optimized_mesh_scale or is_camera_frame_layout: + try: + override_scale = float( + data["translation_scale_optimization"]["mesh_scale"] + ) + except (KeyError, TypeError) as e: + if args.use_optimized_mesh_scale: + print(f"[error] --use-optimized-mesh-scale set but " + f"data['translation_scale_optimization']['mesh_scale'] not found: {e}") + sys.exit(1) + else: + print(f"[warn] camera-frame layout but no mesh_scale found; " + f"falling back to per-frame local_to_scene.scale ({e})") + if override_scale is not None: + orig = data["translation_scale_optimization"].get("mesh_scale_original") + print(f"Using optimized mesh_scale={override_scale:.6f} " + f"(was mesh_scale_original={orig})") + + # Open video source. Accepts either a directory of 0-indexed PNG frames + # (e.g. $CLIP_DIR/all_frames) or an MP4 file. + if not os.path.exists(args.video): + print(f"[error] Video not found: {args.video}") + sys.exit(1) + if os.path.isdir(args.video): + frame_source = DirectoryVideoReader(args.video) + width, height = frame_source.width, frame_source.height + cap = None + print(f"Frame dir source: {args.video} ({len(frame_source.paths)} frames, {width}x{height})") + else: + cap = cv2.VideoCapture(args.video) + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + frame_source = None + print(f"MP4 source: {args.video} ({width}x{height})") + + # Load mesh once + if not os.path.exists(args.mesh): + print(f"[error] Mesh not found: {args.mesh}") + sys.exit(1) + print("Loading mesh...") + mesh = load_objs_as_meshes([args.mesh], device=device) + + if args.object_color is not None: + rgb = _parse_rgb(args.object_color) + verts_list = mesh.verts_list() + faces_list = mesh.faces_list() + n_verts = verts_list[0].shape[0] + color_t = torch.tensor(rgb, dtype=torch.float32, device=device) + verts_features = color_t.expand(n_verts, 3).unsqueeze(0) + mesh = Meshes( + verts=verts_list, faces=faces_list, + textures=TexturesVertex(verts_features=verts_features), + ) + print(f"Object mesh re-colored to solid RGB={rgb}") + + # Load hand data once + hand_data = None + hands_to_render = [] + hand_colors = { + "left": _parse_rgb(args.left_hand_color), + "right": _parse_rgb(args.right_hand_color), + } + if args.hand_meshes: + if not os.path.exists(args.hand_meshes): + print(f"[error] Hand meshes not found: {args.hand_meshes}") + sys.exit(1) + hand_data = np.load(args.hand_meshes) + hands_to_render = ["left", "right"] if args.hands == "both" else [args.hands] + print(f"Loaded hand meshes, rendering: {hands_to_render}") + + os.makedirs(args.output_base, exist_ok=True) + + # Renderer cache: avoid recreating for identical intrinsics + renderer_cache = {} + + def get_renderer(intr, W, H): + fx = intr["fx_norm"] * W + fy = intr["fy_norm"] * H + cx = intr.get("cx_norm", 0.5) * W + cy = intr.get("cy_norm", 0.5) * H + key = (round(fx, 4), round(fy, 4), round(cx, 4), round(cy, 4), W, H) + if key not in renderer_cache: + renderer_cache[key] = make_renderer(fx, fy, cx, cy, W, H, device) + return renderer_cache[key] + + # Process all frames + last_read_idx = -1 + for i, obj in enumerate(objects): + frame_idx = obj["frame_idx"] + lts = obj["local_to_scene"] + + scale = override_scale if override_scale is not None else lts["scale"][0] + if is_camera_frame_layout: + quat = lts["quat_wxyz_camera_frame"] + translation = list(lts["translation_camera_frame"]) # already camera-frame + else: + quat = lts["new_quat"] + tx, ty, tz = lts["translation"] + translation = [tz, tx, ty] + + intr = obj.get("intrinsics_normalized", fallback_intr) + renderer = get_renderer(intr, width, height) + + # Read video frame (dir or MP4) + if frame_source is not None: + frame_rgb = frame_source.read_frame(frame_idx) + else: + frame_rgb, last_read_idx = read_video_frame(cap, frame_idx, last_read_idx) + if frame_rgb is None: + print(f" Skipping frame {frame_idx} (could not read from source)") + continue + + # Convert quaternion to rotation matrix + quat_xyzw = np.array([quat[1], quat[2], quat[3], quat[0]]) # wxyz -> xyzw + rot_matrix = R.from_quat(quat_xyzw).as_matrix() + + # Joint render path: when the object has an explicit solid color and we + # also have hand meshes for this frame, render everything in a single + # rasterization pass so the rasterizer's z-buffer resolves occlusion + # correctly. Falls back to the separate-render + 2D alpha composite below. + use_joint = ( + args.object_color is not None + and hand_data is not None + and frame_idx < hand_data["right_vertices"].shape[0] + and len(hands_to_render) > 0 + ) + + if use_joint: + obj_verts_cam = transform_to_camera_frame( + mesh.verts_packed(), rot_matrix, translation, scale, device, + camera_frame=is_camera_frame_layout, + ) + meshes_data = [( + obj_verts_cam, + mesh.faces_packed(), + _parse_rgb(args.object_color), + )] + for hand in hands_to_render: + hand_verts = torch.tensor( + hand_data[f"{hand}_vertices"][frame_idx], + dtype=torch.float32, device=device, + ) + hand_faces = torch.tensor( + hand_data[f"{hand}_faces"], dtype=torch.int64, device=device, + ) + meshes_data.append((hand_verts, hand_faces, hand_colors[hand])) + + render_rgb, render_alpha = render_combined(meshes_data, renderer, device) + render_rgb = (render_rgb * 255).clip(0, 255).astype(np.uint8) + mask = render_alpha > 0.5 + result = frame_rgb.copy() + result[mask] = render_rgb[mask] + else: + # Separate-render fallback (textured object or no hands this frame) + render_rgb, render_alpha = render_mesh( + mesh, rot_matrix, translation, scale, renderer, device, + camera_frame=is_camera_frame_layout, + ) + render_rgb = (render_rgb * 255).clip(0, 255).astype(np.uint8) + mask = render_alpha > 0.5 + + hand_rgb_list = [] + hand_mask_list = [] + if hand_data is not None: + num_frames = hand_data["right_vertices"].shape[0] + if frame_idx < num_frames: + for hand in hands_to_render: + verts = hand_data[f"{hand}_vertices"][frame_idx] + faces = hand_data[f"{hand}_faces"] + h_rgb, h_alpha = render_hand_mesh(verts, faces, renderer, device, color=hand_colors[hand]) + h_rgb = (h_rgb * 255).clip(0, 255).astype(np.uint8) + hand_rgb_list.append(h_rgb) + hand_mask_list.append(h_alpha > 0.5) + else: + print(f" Warning: frame {frame_idx} out of range for hand meshes ({num_frames} frames)") + + result = frame_rgb.copy() + if args.layer_order == "object_front": + for h_rgb, h_mask in zip(hand_rgb_list, hand_mask_list): + result[h_mask] = h_rgb[h_mask] + result[mask] = render_rgb[mask] + else: + result[mask] = render_rgb[mask] + for h_rgb, h_mask in zip(hand_rgb_list, hand_mask_list): + result[h_mask] = h_rgb[h_mask] + + # Save frame + output_path = os.path.join(args.output_base, f"frame_{frame_idx}.png") + result_bgr = cv2.cvtColor(result, cv2.COLOR_RGB2BGR) + cv2.imwrite(output_path, result_bgr) + print(f" [{i+1}/{len(objects)}] Saved frame {frame_idx} scale={scale:.4f}") + + if cap is not None: + cap.release() + + # Save frames as MP4 video + files = glob.glob(os.path.join(args.output_base, "frame_*.png")) + files.sort(key=lambda f: int(re.search(r"frame_(\d+)", f).group(1))) + if files: + video_path = os.path.join(args.output_base, "video.mp4") + frame_pattern = os.path.join(args.output_base, "frame_%d.png") + subprocess.run( + [ + "ffmpeg", "-y", "-framerate", "30", + "-i", frame_pattern, + "-c:v", "libx264", "-pix_fmt", "yuv420p", + video_path, + ], + check=True, + ) + print(f"Saved video ({len(files)} frames) to {video_path}") + + +if __name__ == "__main__": + main() diff --git a/reconstruction/scripts/run_sam3_video.py b/reconstruction/scripts/run_sam3_video.py new file mode 100644 index 0000000000000000000000000000000000000000..7745ac3383cef05effbdf06ad38c2601916e0078 --- /dev/null +++ b/reconstruction/scripts/run_sam3_video.py @@ -0,0 +1,604 @@ +#!/usr/bin/env python3 +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +""" +Run SAM3 video segmentation with a text, point, or interactive click prompt. + +Output structure (in /video_segmentation/ by default): + masks/frame_000000_masks/.png - binary masks per frame per object + overlays/ - overlay visualizations as frame_000000.png, ... + tracked_.mp4 - overlay video + +Usage examples: + # Text prompt (output: video_segmentation/tracked_person.mp4) + python run_sam3_video.py --video /path/to/video.mp4 --text "left hand" --obj_id left_hand_0 + + # Text prompt with custom output directory + python run_sam3_video.py --video video.mp4 --text "dog" --output_dir output/ + + # Point prompt (x,y in pixels, label 1=positive 0=negative) + python run_sam3_video.py --video video.mp4 --points 210,350 --point_labels 1 --obj_id 1 + + # Interactive click mode - opens a window to click points on a frame + python run_sam3_video.py --video /path/to/video.mp4 --click --obj_id scooper_0 --frame_idx 6 + + # Headless box: pixel xyxy, or a box.json with boxes[{xmin,ymin,xmax,ymax}] + python run_sam3_video.py --video video.mp4 --box 120,80,400,360 --obj_id coffee_can + python run_sam3_video.py --video video.mp4 --box /path/to/box.json --obj_id coffee_can + # Optional extra clicks with the box: --points x,y --point_labels 1 +""" + +import argparse +import os +import subprocess + +import cv2 +import numpy as np + +import sys +sys.path.append( + os.environ.get( + "SAM3_PKG_DIR", + os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "modules", "sam3"), + ) +) + + +def parse_args(): + parser = argparse.ArgumentParser(description="Run SAM3 video segmentation") + parser.add_argument( + "--video", + type=str, + required=True, + help="Path to video (MP4 file or directory of JPEG frames)", + ) + parser.add_argument("--text", type=str, default=None, help="Text prompt") + parser.add_argument( + "--points", + type=str, + default=None, + help="Point prompts as 'x1,y1;x2,y2;...' in pixel coords", + ) + parser.add_argument( + "--point_labels", + type=str, + default=None, + help="Point labels as '1;0;1;...' (1=positive, 0=negative)", + ) + parser.add_argument( + "--obj_id", + type=str, + required=True, + help="Object ID used for naming saved masks (e.g. 'flower', 'hand')", + ) + parser.add_argument( + "--frame_idx", + type=int, + default=0, + help="Frame index to add prompt on (default: 0)", + ) + parser.add_argument( + "--output_dir", + type=str, + default=None, + help="Directory to save output masks (default: same as video path)", + ) + parser.add_argument( + "--checkpoint", + type=str, + default=None, + help="Path to model checkpoint (default: auto-download from HF)", + ) + parser.add_argument( + "--click", + action="store_true", + help="Interactive OpenCV points (needs a display; not for GPU nodes).", + ) + parser.add_argument( + "--box", + type=str, + default=None, + help="Pixel xyxy 'xmin,ymin,xmax,ymax' or path to box.json " + "(boxes[{xmin,ymin,xmax,ymax}])", + ) + return parser.parse_args() + + +def box_xyxy_from_json(data): + """First box as (xmin, ymin, xmax, ymax) pixels.""" + box = None + if isinstance(data, dict) and data.get("boxes"): + box = data["boxes"][0] + elif isinstance(data, dict): + box = data + elif isinstance(data, list) and data: + box = data[0] + if isinstance(box, dict): + keys = ("xmin", "ymin", "xmax", "ymax") + alt = ("x1", "y1", "x2", "y2") + if all(k in box for k in keys): + x0, y0, x1, y1 = (box[k] for k in keys) + elif all(k in box for k in alt): + x0, y0, x1, y1 = (box[k] for k in alt) + else: + raise ValueError("box JSON needs xmin/ymin/xmax/ymax (or x1/y1/x2/y2)") + elif isinstance(box, (list, tuple)) and len(box) == 4: + x0, y0, x1, y1 = box + else: + raise ValueError("unrecognized box JSON; expected boxes: [{xmin, ymin, xmax, ymax}]") + return ( + int(min(x0, x1)), + int(min(y0, y1)), + int(max(x0, x1)), + int(max(y0, y1)), + ) + + +def points_from_box_json(data): + """Optional extra clicks in box.json: points: [{x,y,label}] or [[x,y], ...].""" + pts, labs = [], [] + for p in data.get("points") or []: + if isinstance(p, dict): + pts.append([float(p["x"]), float(p["y"])]) + labs.append(int(p.get("label", 1))) + else: + pts.append([float(p[0]), float(p[1])]) + labs.append(int(p[2]) if len(p) > 2 else 1) + return pts, labs + + +def parse_box_spec(spec): + """Return (xyxy, extra_points, extra_labels) from JSON path or xmin,ymin,xmax,ymax.""" + spec = spec.strip() + if os.path.isfile(spec): + import json + + with open(spec, encoding="utf-8") as f: + data = json.load(f) + xyxy = box_xyxy_from_json(data) + extra_pts, extra_labs = points_from_box_json(data) + print(f"Loaded box from {spec}: xyxy={xyxy}") + return xyxy, extra_pts, extra_labs + parts = [float(x) for x in spec.replace(" ", "").split(",")] + if len(parts) != 4: + raise SystemExit( + "--box must be xmin,ymin,xmax,ymax in pixels or a path to box.json" + ) + x0, y0, x1, y1 = parts + xyxy = ( + int(min(x0, x1)), + int(min(y0, y1)), + int(max(x0, x1)), + int(max(y0, y1)), + ) + return xyxy, [], [] + + +def load_video_frames(video_path): + """Load video frames for visualization.""" + if isinstance(video_path, str) and video_path.endswith(".mp4"): + cap = cv2.VideoCapture(video_path) + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) + cap.release() + return frames + else: + IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".webp") + frame_paths = [ + os.path.join(video_path, p) + for p in os.listdir(video_path) + if os.path.splitext(p)[-1].lower() in IMAGE_EXTS + ] + try: + frame_paths.sort( + key=lambda p: int( + "".join(ch for ch in os.path.splitext(os.path.basename(p))[0] if ch.isdigit()) + or "0" + ) + ) + except ValueError: + frame_paths.sort() + return [cv2.cvtColor(cv2.imread(p), cv2.COLOR_BGR2RGB) for p in frame_paths] + + +def get_highest_score_obj(outputs): + """From a frame output dict, return the obj_id and mask with the highest score.""" + obj_ids = outputs["out_obj_ids"] + probs = outputs["out_probs"] + masks = outputs["out_binary_masks"] + + if len(obj_ids) == 0: + return None, None, None + + best_idx = np.argmax(probs) + return obj_ids[best_idx], probs[best_idx], masks[best_idx] + + +def interactive_click_prompt(frame, obj_id=""): + """ + Open a window showing `frame` (RGB array). The user can: + - Left-click to add a positive point (green dot) + - Right-click to add a negative point (red dot) + - Press Enter or Space to confirm + - Press 'u' to undo the last point + - Press Esc to abort + + Returns (points, labels) as numpy arrays, or (None, None) if cancelled. + """ + points = [] + labels = [] + window_name = f"SAM3 [{obj_id}] - Click to add points (Enter=confirm, U=undo, Esc=cancel)" + + def _redraw(): + img = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR).copy() + for (x, y), lbl in zip(points, labels): + color = (0, 255, 0) if lbl == 1 else (0, 0, 255) + cv2.circle(img, (int(x), int(y)), 6, color, -1) + cv2.circle(img, (int(x), int(y)), 6, (255, 255, 255), 1) + return img + + def _on_mouse(event, x, y, _flags, _param): + if event == cv2.EVENT_LBUTTONDOWN: + points.append((x, y)) + labels.append(1) + elif event == cv2.EVENT_RBUTTONDOWN: + points.append((x, y)) + labels.append(0) + + cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) + cv2.resizeWindow(window_name, min(frame.shape[1], 1280), min(frame.shape[0], 720)) + cv2.setMouseCallback(window_name, _on_mouse) + + print("Left-click = positive point (green), Right-click = negative point (red)") + print("Press Enter/Space to confirm, 'u' to undo, Esc to cancel") + + while True: + cv2.imshow(window_name, _redraw()) + key = cv2.waitKey(30) & 0xFF + if key in (13, 32): # Enter or Space + break + elif key == 27: # Esc + points, labels = None, None + break + elif key == ord("u") and points: # Undo + points.pop() + labels.pop() + + cv2.destroyWindow(window_name) + + if points is None or len(points) == 0: + return None, None + + return np.array(points, dtype=np.float32), np.array(labels, dtype=np.int32) + + +def overlay_mask_on_frame(frame, mask, color=(30, 144, 255), alpha=0.5): + """Overlay a binary mask on a frame with the given color and alpha.""" + overlay = frame.copy() + overlay[mask] = ( + (1 - alpha) * overlay[mask] + alpha * np.array(color, dtype=np.uint8) + ).astype(np.uint8) + # Draw contours + contours, _ = cv2.findContours( + mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE + ) + cv2.drawContours(overlay, contours, -1, color, 2) + return overlay + + +def main(): + args = parse_args() + + assert ( + args.text is not None + or args.points is not None + or args.click + or args.box + ), "Must provide --text, --points, --click, or --box" + + if args.output_dir is None: + if args.video.endswith(".mp4"): + video_dir = os.path.dirname(args.video) or "." + else: + video_dir = args.video + args.output_dir = os.path.join(video_dir, "video_segmentation") + + if args.text is not None: + prompt_name = args.text.replace(" ", "_") + elif args.box: + prompt_name = "box" + elif args.click: + prompt_name = "click" + else: + prompt_name = "points" + + masks_base_dir = os.path.join(args.output_dir, "masks") + overlay_dir = os.path.join(args.output_dir, "overlays", args.obj_id) + os.makedirs(masks_base_dir, exist_ok=True) + os.makedirs(overlay_dir, exist_ok=True) + + # Interactive click mode: collect clicks BEFORE loading the model, because + # CUDA/PyTorch initialization can corrupt the Qt libraries that cv2 uses + # for its GUI, causing a segfault. + click_points = None + click_labels = None + box_xyxy = None + box_extra_pts = [] + box_extra_labs = [] + if args.click: + video_frames = load_video_frames(args.video) + frame = video_frames[args.frame_idx] + print(f"Opening frame {args.frame_idx} for interactive clicking...") + click_points, click_labels = interactive_click_prompt(frame, obj_id=args.obj_id) + if click_points is None: + print("Cancelled. Exiting.") + return + elif args.box: + box_xyxy, box_extra_pts, box_extra_labs = parse_box_spec(args.box) + print(f"Using pixel box xyxy={box_xyxy}") + + # Import torch and SAM3 after any cv2 GUI work, because sam3's imports + # load libraries that conflict with cv2's Qt backend and cause segfaults. + import inspect + import torch + from sam3.model_builder import build_sam3_video_predictor + + ckpt = args.checkpoint or os.environ.get("SAM3_CHECKPOINT") + print("Loading SAM3 model...") + build_kwargs = {} + params = inspect.signature(build_sam3_video_predictor).parameters + if ckpt: + for key in ("checkpoint_path", "checkpoint", "ckpt_path"): + if key in params: + build_kwargs[key] = ckpt + print(f" checkpoint: {ckpt}") + break + else: + print(f" warning: SAM3 builder has no checkpoint arg; ignoring {ckpt}") + predictor = build_sam3_video_predictor(**build_kwargs) + + # Start session + print(f"Starting session on: {args.video}") + response = predictor.handle_request( + request=dict( + type="start_session", + resource_path=args.video, + ) + ) + session_id = response["session_id"] + + # SAM3 requires an integer obj_id; use 1 internally, keep string for naming + sam3_obj_id = 1 + + # Add prompt + if args.click: + h, w = video_frames[0].shape[:2] + + rel_points = [[x / w, y / h] for x, y in click_points.tolist()] + points_tensor = torch.tensor(rel_points, dtype=torch.float32) + labels_tensor = torch.tensor(click_labels.tolist(), dtype=torch.int32) + + print( + f"Adding {len(click_points)} clicked point(s) on frame {args.frame_idx}: " + f"points={click_points.tolist()}, labels={click_labels.tolist()}" + ) + response = predictor.handle_request( + request=dict( + type="add_prompt", + session_id=session_id, + frame_index=args.frame_idx, + points=points_tensor, + point_labels=labels_tensor, + obj_id=sam3_obj_id, + ) + ) + elif args.box: + # Instance tracker prompt (SAM2-style), not detector visual-exemplar + # bounding_boxes. The detector path searches for similar objects and + # often returns empty masks on DexYCB. Tracker encodes a box as two + # corner clicks (labels 2 and 3) plus a positive center click (1). + if "video_frames" not in locals(): + video_frames = load_video_frames(args.video) + h, w = video_frames[0].shape[:2] + xmin, ymin, xmax, ymax = box_xyxy + cx = (xmin + xmax) / 2.0 + cy = (ymin + ymax) / 2.0 + pixel_pts = [[xmin, ymin], [xmax, ymax], [cx, cy]] + pixel_labs = [2, 3, 1] + if args.points: + extra = [[float(c) for c in pt.split(",")] for pt in args.points.split(";")] + extra_labs = ( + [int(l) for l in args.point_labels.split(";")] + if args.point_labels + else [1] * len(extra) + ) + pixel_pts.extend(extra) + pixel_labs.extend(extra_labs) + pixel_pts.extend(box_extra_pts) + pixel_labs.extend(box_extra_labs) + rel_points = [[x / w, y / h] for x, y in pixel_pts] + points_tensor = torch.tensor(rel_points, dtype=torch.float32) + labels_tensor = torch.tensor(pixel_labs, dtype=torch.int32) + print( + f"Adding instance box+point prompt on frame {args.frame_idx}: " + f"xyxy={box_xyxy} center=({cx:.1f},{cy:.1f}) " + f"points={pixel_pts} labels={pixel_labs}" + ) + response = predictor.handle_request( + request=dict( + type="add_prompt", + session_id=session_id, + frame_index=args.frame_idx, + points=points_tensor, + point_labels=labels_tensor, + obj_id=sam3_obj_id, + ) + ) + box_path = os.path.join(os.path.dirname(args.output_dir), "sam3_object_box.json") + try: + import json + + with open(box_path, "w") as f: + json.dump( + { + "xyxy_px": list(box_xyxy), + "center_px": [cx, cy], + "points_px": pixel_pts, + "labels": pixel_labs, + "frame_idx": args.frame_idx, + }, + f, + indent=2, + ) + print(f"Saved box to {box_path}") + except OSError: + pass + elif args.text is not None: + print(f"Adding text prompt: '{args.text}' on frame {args.frame_idx}") + response = predictor.handle_request( + request=dict( + type="add_prompt", + session_id=session_id, + frame_index=args.frame_idx, + text=args.text, + obj_id=sam3_obj_id, + ) + ) + else: + # Parse point prompts + points_list = [ + [float(c) for c in pt.split(",")] for pt in args.points.split(";") + ] + labels_list = [int(l) for l in args.point_labels.split(";")] + assert len(points_list) == len(labels_list), ( + "Number of points must match number of labels" + ) + + # Load a frame to get dimensions for coordinate normalization + video_frames = load_video_frames(args.video) + h, w = video_frames[0].shape[:2] + rel_points = [[x / w, y / h] for x, y in points_list] + + points_tensor = torch.tensor(rel_points, dtype=torch.float32) + labels_tensor = torch.tensor(labels_list, dtype=torch.int32) + + print( + f"Adding point prompt on frame {args.frame_idx}: " + f"points={points_list}, labels={labels_list}" + ) + response = predictor.handle_request( + request=dict( + type="add_prompt", + session_id=session_id, + frame_index=args.frame_idx, + points=points_tensor, + point_labels=labels_tensor, + obj_id=sam3_obj_id, + ) + ) + + # Show prompt frame results + prompt_out = response["outputs"] + best_obj_id, best_score, best_mask = get_highest_score_obj(prompt_out) + if best_obj_id is not None: + print( + f"Prompt frame {args.frame_idx}: best obj_id={best_obj_id}, score={best_score:.4f}" + ) + if best_mask is not None: + print(f" prompt-frame mask coverage: {100.0 * best_mask.mean():.2f}%") + else: + print( + "No objects detected on the prompt frame. " + + ( + f"Text prompt likely does not match anything (prompt={args.text!r}). " + if args.text + else "Box/point prompt produced no mask. " + ) + + "Masks will be empty." + ) + + # Propagate through video + print("Propagating through video...") + outputs_per_frame = {} + for resp in predictor.handle_stream_request( + request=dict( + type="propagate_in_video", + session_id=session_id, + ) + ): + outputs_per_frame[resp["frame_index"]] = resp["outputs"] + + # Load video frames for overlays and video + if "video_frames" not in locals(): + video_frames = load_video_frames(args.video) + + # Save masks, overlays, and tracked video + sorted_frames = sorted(outputs_per_frame.keys()) + h, w = video_frames[0].shape[:2] + out_video_path = os.path.join(args.output_dir, f"tracked_{args.obj_id}_{prompt_name}.mp4") + + nonempty = 0 + print(f"Saving {len(sorted_frames)} frames to {args.output_dir}/...") + for frame_idx in sorted_frames: + out = outputs_per_frame[frame_idx] + _, _, best_mask = get_highest_score_obj(out) + + # Save mask into per-frame directory as .png + frame_mask_dir = os.path.join(masks_base_dir, f"frame_{frame_idx:06d}_masks") + os.makedirs(frame_mask_dir, exist_ok=True) + if best_mask is not None: + mask_uint8 = (best_mask.astype(np.uint8) * 255) + if mask_uint8.max() > 0: + nonempty += 1 + else: + mask_uint8 = np.zeros((h, w), dtype=np.uint8) + cv2.imwrite( + os.path.join(frame_mask_dir, f"{args.obj_id}.png"), mask_uint8 + ) + + # Save overlay + if frame_idx < len(video_frames): + frame = video_frames[frame_idx] + if best_mask is not None: + overlay = overlay_mask_on_frame(frame, best_mask) + else: + overlay = frame + cv2.imwrite( + os.path.join(overlay_dir, f"frame_{frame_idx:06d}.png"), + cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR), + ) + + # Encode overlay frames to H264 video using ffmpeg + print(f"Encoding tracked video with H264: {out_video_path}") + subprocess.run( + [ + "ffmpeg", "-y", + "-framerate", "24", + "-i", os.path.join(overlay_dir, "frame_%06d.png"), + "-c:v", "libx264", + "-pix_fmt", "yuv420p", + out_video_path, + ], + check=True, + ) + + # Cleanup + predictor.handle_request( + request=dict(type="close_session", session_id=session_id) + ) + predictor.shutdown() + + print(f" nonempty {args.obj_id} masks: {nonempty}/{len(sorted_frames)}") + if nonempty == 0: + print( + f"WARNING: every {args.obj_id} mask is empty. " + "Check --box / box.json (instance box+center click); do not continue the mesh stage." + ) + + +if __name__ == "__main__": + main() diff --git a/reconstruction/scripts/smooth_trajectory.py b/reconstruction/scripts/smooth_trajectory.py new file mode 100644 index 0000000000000000000000000000000000000000..a09d8df6c46b034ce0d9fad1007810ad53de6dd2 --- /dev/null +++ b/reconstruction/scripts/smooth_trajectory.py @@ -0,0 +1,201 @@ +"""Smooth per-frame object trajectory from an optimized layout JSON. + +Filters out OOD frames (jump-and-jump-back outliers) via interpolation, +then applies Savitzky-Golay filtering to the translation and rotation +(quaternion, wxyz) fields. Only those two fields are modified; every other +field in the layout is passed through unchanged. + +By default this operates on the camera-frame pose produced by +`convert_layout_to_camera_frame.py` + `optimize_translation_scale.py` +(`translation_camera_frame` / `quat_wxyz_camera_frame`), which is what the +downstream visualizer/retargeter consumes. Use --trans-key / --quat-key to +smooth the pose-frame fields (`translation` / `new_quat`) instead. +""" + +import argparse +import json +import copy +import os +import numpy as np +from pathlib import Path +from scipy.signal import savgol_filter +from scipy.spatial.transform import Rotation, Slerp + +# --- Defaults --- +WINDOW_SIZE = 7 # must be odd +POLY_ORDER = 3 +# OOD detection: frame is outlier if both its incoming and outgoing velocity +# exceed this many times the median velocity +OOD_MULTIPLIER = 3.0 +# Field keys (camera-frame pose is the pipeline's final consumed pose) +DEFAULT_TRANS_KEY = "translation_camera_frame" +DEFAULT_QUAT_KEY = "quat_wxyz_camera_frame" + + +def detect_ood_frames(values: np.ndarray, threshold_mult: float) -> list[int]: + """Detect frames that jump out and back (OOD spikes). + + A frame i is OOD if the change from i-1->i AND i->i+1 are both + above threshold_mult * median change. + """ + deltas = np.linalg.norm(np.diff(values, axis=0), axis=1) + median_delta = np.median(deltas) + threshold = max(threshold_mult * median_delta, 1e-6) + ood = [] + for i in range(len(deltas) - 1): + if deltas[i] > threshold and deltas[i + 1] > threshold: + ood.append(i + 1) # the frame that jumped + return ood + + +def interpolate_ood_translation(trans: np.ndarray, ood_frames: list[int]) -> np.ndarray: + """Replace OOD frames with linearly interpolated values.""" + result = trans.copy() + for i in ood_frames: + # Find nearest non-OOD neighbors + lo = i - 1 + while lo in ood_frames and lo > 0: + lo -= 1 + hi = i + 1 + while hi in ood_frames and hi < len(trans) - 1: + hi += 1 + if lo == hi: + continue + t = (i - lo) / (hi - lo) + result[i] = (1 - t) * result[lo] + t * result[hi] + return result + + +def interpolate_ood_rotation(quats_xyzw: np.ndarray, ood_frames: list[int]) -> np.ndarray: + """Replace OOD frames with SLERP-interpolated rotations.""" + result = quats_xyzw.copy() + ood_set = set(ood_frames) + for i in ood_frames: + lo = i - 1 + while lo in ood_set and lo > 0: + lo -= 1 + hi = i + 1 + while hi in ood_set and hi < len(quats_xyzw) - 1: + hi += 1 + if lo == hi: + continue + rots = Rotation.from_quat([result[lo], result[hi]]) + slerp = Slerp([0, 1], rots) + t = (i - lo) / (hi - lo) + result[i] = slerp([t]).as_quat()[0] + return result + + +def smooth_trajectory(input_path: Path, output_path: Path, trans_key: str, quat_key: str): + with open(input_path) as f: + data = json.load(f) + + def get_frame_idx(o): + return o.get("frame_index", o.get("frame_idx")) + + # Separate dynamic (has a frame index) and static objects + dynamic = [o for o in data["objects"] if get_frame_idx(o) is not None] + static = [o for o in data["objects"] if get_frame_idx(o) is None] + + # Sort by frame index + dynamic.sort(key=get_frame_idx) + n = len(dynamic) + print(f"Dynamic frames: {n}, Static objects: {len(static)}") + print(f"Smoothing fields: translation='{trans_key}', quaternion='{quat_key}'") + + # Extract arrays + trans = np.array([o["local_to_scene"][trans_key] for o in dynamic]) # (N, 3) + quats_wxyz = np.array([o["local_to_scene"][quat_key] for o in dynamic]) # (N, 4) wxyz + + # Convert quat wxyz -> scipy xyzw + quats_xyzw = quats_wxyz[:, [1, 2, 3, 0]] + + # Ensure quaternion continuity + for i in range(1, n): + if np.dot(quats_xyzw[i], quats_xyzw[i - 1]) < 0: + quats_xyzw[i] = -quats_xyzw[i] + + # --- Detect OOD frames --- + rotvec = Rotation.from_quat(quats_xyzw).as_rotvec() + ood_trans = detect_ood_frames(trans, OOD_MULTIPLIER) + ood_rot = detect_ood_frames(rotvec, OOD_MULTIPLIER) + ood_all = sorted(set(ood_trans + ood_rot)) + print(f"OOD translation frames: {ood_trans}") + print(f"OOD rotation frames: {ood_rot}") + print(f"Combined OOD frames: {ood_all}") + + # --- Replace OOD frames with interpolated values --- + trans_clean = interpolate_ood_translation(trans, ood_all) + quats_clean = interpolate_ood_rotation(quats_xyzw, ood_all) + + # --- Smooth translation --- + trans_smooth = np.zeros_like(trans_clean) + for i in range(3): + trans_smooth[:, i] = savgol_filter(trans_clean[:, i], WINDOW_SIZE, POLY_ORDER) + + # --- Smooth quaternion directly in R^4 and renormalize --- + # Works because sign-continuity is enforced above; no angle-wrap issues. + quats_smooth = np.zeros_like(quats_clean) + for i in range(4): + quats_smooth[:, i] = savgol_filter(quats_clean[:, i], WINDOW_SIZE, POLY_ORDER) + quats_smooth /= np.linalg.norm(quats_smooth, axis=1, keepdims=True) + + quats_xyzw_smooth = quats_smooth + quats_wxyz_smooth = quats_xyzw_smooth[:, [3, 0, 1, 2]] + + # --- Build output (only modify the translation and quaternion fields) --- + output = copy.deepcopy(data) + smoothed_dynamic = copy.deepcopy(dynamic) + for i, obj in enumerate(smoothed_dynamic): + pose = obj["local_to_scene"] + pose[trans_key] = trans_smooth[i].tolist() + pose[quat_key] = quats_wxyz_smooth[i].tolist() + + output["objects"] = smoothed_dynamic + copy.deepcopy(static) + + os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True) + with open(output_path, "w") as f: + json.dump(output, f, indent=2) + print(f"\nWrote smoothed trajectory to {output_path}") + + # --- Summary statistics --- + trans_diff = np.abs(trans_smooth - trans) + print(f"\nTranslation smoothing (mean abs change per axis):") + print(f" x: {trans_diff[:, 0].mean():.6f} y: {trans_diff[:, 1].mean():.6f} z: {trans_diff[:, 2].mean():.6f}") + print(f" max change: {trans_diff.max():.6f}") + + angle_diff = [ + (Rotation.from_quat(quats_xyzw[i]).inv() * Rotation.from_quat(quats_xyzw_smooth[i])).magnitude() + for i in range(n) + ] + angle_diff = np.array(angle_diff) + print(f"\nQuaternion smoothing (angle change in radians):") + print(f" mean: {angle_diff.mean():.6f} max: {angle_diff.max():.6f}") + + print(f"\nSample translations (frame: original -> smoothed):") + for idx in [0, n // 4, n // 2, 3 * n // 4, n - 1]: + print(f" frame {get_frame_idx(dynamic[idx])}: " + f"{trans[idx].tolist()} -> {trans_smooth[idx].tolist()}") + + +def parse_args(): + p = argparse.ArgumentParser(description="Smooth per-frame object trajectory") + p.add_argument("--input", type=str, required=True, help="Input layout JSON path") + p.add_argument("--output", type=str, default=None, + help="Output smoothed layout JSON path (default: _smooth.json)") + p.add_argument("--trans-key", type=str, default=DEFAULT_TRANS_KEY, + help="local_to_scene translation field to smooth " + f"(default: {DEFAULT_TRANS_KEY}; use 'translation' for pose frame)") + p.add_argument("--quat-key", type=str, default=DEFAULT_QUAT_KEY, + help="local_to_scene quaternion (wxyz) field to smooth " + f"(default: {DEFAULT_QUAT_KEY}; use 'new_quat' for pose frame)") + return p.parse_args() + + +if __name__ == "__main__": + args = parse_args() + output = args.output + if output is None: + stem, ext = os.path.splitext(args.input) + output = f"{stem}_smooth{ext}" + smooth_trajectory(args.input, output, args.trans_key, args.quat_key) diff --git a/reconstruction/scripts/tapir_velocity_tracking.py b/reconstruction/scripts/tapir_velocity_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..29af40ea259a6bf50d418150e25480aa0793e559 --- /dev/null +++ b/reconstruction/scripts/tapir_velocity_tracking.py @@ -0,0 +1,601 @@ +#!/usr/bin/env python3 +"""BootsTAPIR per-frame velocity tracking. + +Tracks an object across video frames using per-frame mask re-sampling, +estimates translation + rotation velocity via SVD rigid fitting. + +Usage: + python tapir_velocity_tracking.py \ + --video /path/to/video.mp4 \ + --mask-dir /path/to/video_dir/video_segmentation/masks \ + --object mug +""" + +import argparse +import glob +import json +import os +import time + +import mediapy as media +import numpy as np +import torch +import torch.nn.functional as F + +from tapnet.torch import tapir_model +from tapnet.utils import transforms +from tapnet.utils import viz_utils + +# NOTE: do NOT sys.path.append("…/tapnet-src/tapnet") here — that dir contains a +# `torch/` subdir which shadows the real PyTorch package and breaks all torch +# imports. The pip-editable install of tapnet (from tapnet-src/tapnet) makes +# `tapnet.torch` importable as a submodule with no path hackery required. + + +def sample_points_from_mask( + frame_idx: int, + mask_path: str, + num_points: int, +) -> np.ndarray: + """Sample query points uniformly along the mask's principal axis.""" + from PIL import Image + + mask = np.array(Image.open(mask_path).convert("L")) + ys, xs = np.where(mask > 128) + if len(ys) == 0: + raise ValueError(f"No foreground pixels found in mask: {mask_path}") + + coords = np.stack([xs, ys], axis=1).astype(np.float64) + centroid = coords.mean(axis=0) + centered = coords - centroid + _, _, Vt = np.linalg.svd(centered, full_matrices=False) + projections = centered @ Vt[0] + order = np.argsort(projections) + indices = np.linspace(0, len(order) - 1, min(num_points, len(order))).astype(np.int32) + sel_x, sel_y = xs[order[indices]], ys[order[indices]] + + n = len(sel_x) + t = np.full((n, 1), frame_idx, dtype=np.int32) + y = sel_y.reshape(-1, 1) + x = sel_x.reshape(-1, 1) + return np.concatenate((t, y, x), axis=-1).astype(np.float32) + + +def find_first_mask_frame(mask_dir: str, object_name: str) -> int: + """Find the first frame that has a mask for the given object.""" + pattern = os.path.join(mask_dir, f"frame_*_masks/{object_name}.png") + matches = sorted(glob.glob(pattern)) + if not matches: + raise ValueError(f"No masks found for object '{object_name}' in {mask_dir}") + frame_dir = os.path.basename(os.path.dirname(matches[0])) + return int(frame_dir.split("_")[1]) + + +def print_motion_stats(stats: dict, fps: float = 10.0): + """Print summary of motion statistics.""" + tv = stats["translation_speed"] + rv = np.abs(stats["rotation_vel"]) + valid_tv = tv[~np.isnan(tv)] + valid_rv = rv[~np.isnan(rv)] + n_total = len(tv) + n_valid = len(valid_tv) + + print(f"\nMotion statistics ({n_valid}/{n_total} valid frame transitions):") + if n_valid > 0: + print(f" Translation speed (px/frame): " + f"mean={valid_tv.mean():.2f}, max={valid_tv.max():.2f}, std={valid_tv.std():.2f}") + print(f" Translation speed (px/sec): " + f"mean={valid_tv.mean()*fps:.1f}, max={valid_tv.max()*fps:.1f}") + print(f" Rotation speed (deg/frame): " + f"mean={np.degrees(valid_rv.mean()):.3f}, max={np.degrees(valid_rv.max()):.3f}") + print(f" Rotation speed (deg/sec): " + f"mean={np.degrees(valid_rv.mean())*fps:.2f}, max={np.degrees(valid_rv.max())*fps:.2f}") + else: + print(" Not enough visible points for reliable estimates.") + print(f" Visible points: min={stats['num_visible'].min()}, " + f"max={stats['num_visible'].max()}") + + +def save_motion_plot(stats: dict, output_path: str, fps: float = 10.0): + """Save a plot of translation and rotation velocity over time.""" + import matplotlib.pyplot as plt + + fig, axes = plt.subplots(3, 1, figsize=(12, 8), sharex=True) + + frames = np.arange(len(stats["translation_speed"])) + + axes[0].plot(frames, stats["translation_speed"], "b-", linewidth=1.5) + axes[0].set_ylabel("Translation\nspeed (px/frame)") + axes[0].grid(True, alpha=0.3) + + axes[1].plot(frames, np.degrees(stats["rotation_vel"]), "r-", linewidth=1.5) + axes[1].set_ylabel("Rotation\nvelocity (deg/frame)") + axes[1].grid(True, alpha=0.3) + + axes[2].plot(np.arange(len(stats["num_visible"])), stats["num_visible"], "g-", linewidth=1.5) + axes[2].set_ylabel("Visible\npoints") + axes[2].set_xlabel("Frame") + axes[2].grid(True, alpha=0.3) + + fig.suptitle("Object Motion Stats from Point Tracks") + fig.tight_layout() + fig.savefig(output_path, dpi=150) + plt.close(fig) + print(f" Saved motion plot to {output_path}") + + +def overlay_motion_stats( + video: np.ndarray, stats: dict, alpha: float = 0.6 +) -> np.ndarray: + """Overlay motion stats plots onto the bottom of each video frame.""" + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from io import BytesIO + + num_frames, vid_h, vid_w, _ = video.shape + chart_h = vid_h // 3 + chart_w = vid_w + dpi = 150 + + trans_speed = stats["translation_speed"] + rot_vel = stats["rotation_vel"] + + def render_chart_frame(current_frame): + fig, axes = plt.subplots( + 2, 1, figsize=(chart_w / dpi, chart_h / dpi), dpi=dpi, + gridspec_kw={"hspace": 0.4}, + ) + fig.patch.set_alpha(0.0) + + frames_x = np.arange(len(trans_speed)) + + ax = axes[0] + ax.set_facecolor((0, 0, 0, 0.5)) + ax.fill_between(frames_x, trans_speed, alpha=0.3, color="cyan") + ax.plot(frames_x, trans_speed, "c-", linewidth=1.5) + ax.axvline(x=current_frame, color="yellow", linewidth=2, alpha=0.9) + ax.set_ylabel("Translation\n(px/frame)", fontsize=9, color="white", fontweight="bold") + ax.tick_params(colors="white", labelsize=7) + ax.set_xticklabels([]) + for spine in ax.spines.values(): + spine.set_color("white") + spine.set_alpha(0.4) + ax.set_xlim(0, len(trans_speed)) + valid = trans_speed[~np.isnan(trans_speed)] + if len(valid) > 0: + ax.set_ylim(0, np.nanmax(valid) * 1.2 + 1) + + ax = axes[1] + ax.set_facecolor((0, 0, 0, 0.5)) + rot_deg = np.degrees(rot_vel) + ax.fill_between(frames_x, rot_deg, alpha=0.3, color="magenta") + ax.plot(frames_x, rot_deg, "m-", linewidth=1.5) + ax.axvline(x=current_frame, color="yellow", linewidth=2, alpha=0.9) + ax.axhline(y=0, color="white", linewidth=0.5, alpha=0.3) + ax.set_ylabel("Rotation\n(deg/frame)", fontsize=9, color="white", fontweight="bold") + ax.set_xlabel("Frame", fontsize=9, color="white") + ax.tick_params(colors="white", labelsize=7) + for spine in ax.spines.values(): + spine.set_color("white") + spine.set_alpha(0.4) + ax.set_xlim(0, len(rot_vel)) + valid = np.degrees(rot_vel[~np.isnan(rot_vel)]) + if len(valid) > 0: + margin = max(np.nanmax(np.abs(valid)) * 1.2, 1) + ax.set_ylim(-margin, margin) + + import warnings + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + fig.tight_layout(pad=0.8) + + buf = BytesIO() + fig.savefig(buf, format="png", dpi=dpi, transparent=True, + bbox_inches="tight", pad_inches=0.1) + plt.close(fig) + buf.seek(0) + + from PIL import Image + chart_img = np.array(Image.open(buf).convert("RGBA")) + chart_img_pil = Image.fromarray(chart_img).resize((chart_w, chart_h), Image.LANCZOS) + return np.array(chart_img_pil) + + output = video.copy() + for t in range(num_frames): + chart_rgba = render_chart_frame(t) + chart_rgb = chart_rgba[:, :, :3].astype(np.float32) + chart_alpha = (chart_rgba[:, :, 3:4].astype(np.float32) / 255.0) * alpha + + region = output[t, vid_h - chart_h:vid_h, :chart_w, :].astype(np.float32) + blended = region * (1 - chart_alpha) + chart_rgb * chart_alpha + output[t, vid_h - chart_h:vid_h, :chart_w, :] = blended.astype(np.uint8) + + return output + + +def _save_pair_viz( + frame_a: np.ndarray, + frame_b: np.ndarray, + tracks_pair: np.ndarray, + vis: np.ndarray, + vis_both: np.ndarray, + frame_idx: int, + output_path: str, +): + """Save a side-by-side visualization of a 2-frame tracking pair.""" + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, axes = plt.subplots(1, 2, figsize=(16, 6)) + colormap = viz_utils.get_colors(len(tracks_pair)) + + for ax_idx, (frame, fidx_label) in enumerate( + [(frame_a, f"Frame {frame_idx}"), (frame_b, f"Frame {frame_idx + 1}")] + ): + ax = axes[ax_idx] + ax.imshow(frame) + ax.set_title(fidx_label, fontsize=12, color="white", fontweight="bold", + bbox=dict(boxstyle="round", facecolor="black", alpha=0.7)) + ax.axis("off") + + for i in range(len(tracks_pair)): + x, y = tracks_pair[i, ax_idx] + color = tuple(np.array(colormap[i]) / 255.0) + if vis_both[i]: + ax.plot(x, y, "o", color=color, markersize=6, markeredgecolor="white", + markeredgewidth=0.5) + elif vis[i, ax_idx]: + ax.plot(x, y, "x", color=color, markersize=6, alpha=0.5) + + n_vis = vis_both.sum() + axes[0].set_title( + f"Frame {frame_idx} ({n_vis} matched)", fontsize=12, color="white", + fontweight="bold", bbox=dict(boxstyle="round", facecolor="black", alpha=0.7) + ) + + fig.tight_layout(pad=1) + fig.savefig(output_path, dpi=100, bbox_inches="tight", + facecolor="black", edgecolor="none") + plt.close(fig) + + +def compute_perframe_motion_stats( + video_path: str, + mask_dir: str, + mask_name: str, + model: torch.nn.Module, + device: torch.device, + num_points: int = 20, + resize_hw: tuple = (256, 256), + threshold: float = 0.5, + min_visible: int = 5, + save_dir: str = None, +) -> dict: + """Estimate motion by re-sampling points from per-frame masks. + + For each consecutive frame pair (t, t+1): + 1. Load mask at frame t, sample points on the object + 2. Run 2-frame TAPIR inference + 3. Fit rigid transform (SVD) to get translation + rotation + """ + from PIL import Image + + video = media.read_video(video_path) + num_frames, vid_h, vid_w = video.shape[:3] + resize_h, resize_w = resize_hw + frames_resized = media.resize_video(video, (resize_h, resize_w)) + frames_preprocessed = torch.tensor(frames_resized).float().to(device) + frames_preprocessed = frames_preprocessed / 255 * 2 - 1 + + if save_dir: + viz_dir = os.path.join(save_dir, "pair_visualizations") + os.makedirs(viz_dir, exist_ok=True) + + centroids = np.full((num_frames, 2), np.nan) + translation_vel = np.full((num_frames - 1, 2), np.nan) + rotation_vel = np.full(num_frames - 1, np.nan) + num_visible = np.zeros(num_frames, dtype=np.int32) + per_frame_data = [] + + t_start = time.time() + + for t in range(num_frames - 1): + mask_path = os.path.join(mask_dir, f"frame_{t:06d}_masks", mask_name) + if not os.path.exists(mask_path): + per_frame_data.append({ + "frame": t, "status": "no_mask", + "num_sampled": 0, "num_visible_both": 0, + "translation_dx": None, "translation_dy": None, + "translation_speed": None, "rotation_deg": None, + }) + continue + + mask = np.array(Image.open(mask_path).convert("L")) + ys, xs = np.where(mask > 128) + if len(ys) < min_visible: + per_frame_data.append({ + "frame": t, "status": "mask_too_small", + "num_sampled": 0, "num_visible_both": 0, + "translation_dx": None, "translation_dy": None, + "translation_speed": None, "rotation_deg": None, + }) + continue + + qp = sample_points_from_mask(t, mask_path, num_points) + n_sampled = len(qp) + if n_sampled < min_visible: + per_frame_data.append({ + "frame": t, "status": "too_few_sampled", + "num_sampled": n_sampled, "num_visible_both": 0, + "translation_dx": None, "translation_dy": None, + "translation_speed": None, "rotation_deg": None, + }) + continue + + qp_resized = transforms.convert_grid_coordinates( + qp, (1, vid_h, vid_w), (1, resize_h, resize_w), + coordinate_format="tyx", + ) + + pair = frames_preprocessed[t:t + 2][None] + qp_tensor = torch.tensor(qp_resized).float().to(device) + qp_tensor[:, 0] = 0 + qp_tensor = qp_tensor[None] + + with torch.no_grad(): + outputs = model(pair, qp_tensor) + + tracks_pair = outputs["tracks"][0].cpu().numpy() + occ = outputs["occlusion"][0] + exp_dist = outputs["expected_dist"][0] + vis = ((1 - F.sigmoid(occ)) * (1 - F.sigmoid(exp_dist)) > threshold).cpu().numpy() + + tracks_pair = transforms.convert_grid_coordinates( + tracks_pair, (resize_w, resize_h), (vid_w, vid_h) + ) + + mask_next_path = os.path.join(mask_dir, f"frame_{t+1:06d}_masks", mask_name) + if os.path.exists(mask_next_path): + mask_next = np.array(Image.open(mask_next_path).convert("L")) + on_mask_next = np.array([ + mask_next[ + int(np.clip(tracks_pair[i, 1, 1], 0, vid_h - 1)), + int(np.clip(tracks_pair[i, 1, 0], 0, vid_w - 1)), + ] > 128 + for i in range(len(tracks_pair)) + ]) + else: + on_mask_next = np.ones(len(tracks_pair), dtype=bool) + + vis_both = vis[:, 0] & vis[:, 1] & on_mask_next + n_vis = vis_both.sum() + num_visible[t] = max(num_visible[t], vis[:, 0].sum()) + + if save_dir: + _save_pair_viz( + video[t], video[t + 1], tracks_pair, vis, vis_both, + t, os.path.join(viz_dir, f"pair_{t:04d}_{t+1:04d}.png"), + ) + + if n_vis < min_visible: + per_frame_data.append({ + "frame": t, "status": "too_few_visible", + "num_sampled": n_sampled, "num_visible_both": int(n_vis), + "translation_dx": None, "translation_dy": None, + "translation_speed": None, "rotation_deg": None, + }) + continue + + pts_a = tracks_pair[vis_both, 0, :] + pts_b = tracks_pair[vis_both, 1, :] + + centroid_a = pts_a.mean(axis=0) + centroid_b = pts_b.mean(axis=0) + centroids[t] = centroid_a + if t == num_frames - 2: + centroids[t + 1] = centroid_b + + translation_vel[t] = centroid_b - centroid_a + + pa = pts_a - centroid_a + pb = pts_b - centroid_b + H = pa.T @ pb + U, _, Vt = np.linalg.svd(H) + R = Vt.T @ U.T + if np.linalg.det(R) < 0: + Vt[-1, :] *= -1 + R = Vt.T @ U.T + rotation_vel[t] = np.arctan2(R[1, 0], R[0, 0]) + + t_speed = float(np.linalg.norm(translation_vel[t])) + per_frame_data.append({ + "frame": t, "status": "ok", + "num_sampled": n_sampled, "num_visible_both": int(n_vis), + "translation_dx": float(translation_vel[t, 0]), + "translation_dy": float(translation_vel[t, 1]), + "translation_speed": t_speed, + "rotation_deg": float(np.degrees(rotation_vel[t])), + }) + + last_mask = os.path.join(mask_dir, f"frame_{num_frames-1:06d}_masks", mask_name) + if os.path.exists(last_mask): + m = np.array(Image.open(last_mask).convert("L")) + num_visible[num_frames - 1] = (m > 128).sum() > 0 + + elapsed = time.time() - t_start + + # Interpolate failed frames from neighbors + n_interpolated = 0 + for i, entry in enumerate(per_frame_data): + if entry["status"] == "ok": + continue + prev_val = next_val = None + for j in range(i - 1, -1, -1): + if per_frame_data[j]["status"] in ("ok", "interpolated"): + prev_val = per_frame_data[j] + break + for j in range(i + 1, len(per_frame_data)): + if per_frame_data[j]["status"] == "ok": + next_val = per_frame_data[j] + break + + if prev_val and next_val: + alpha = (entry["frame"] - prev_val["frame"]) / (next_val["frame"] - prev_val["frame"]) + for key in ("translation_dx", "translation_dy", "translation_speed", "rotation_deg"): + entry[key] = prev_val[key] * (1 - alpha) + next_val[key] * alpha + elif prev_val: + for key in ("translation_dx", "translation_dy", "translation_speed", "rotation_deg"): + entry[key] = prev_val[key] + elif next_val: + for key in ("translation_dx", "translation_dy", "translation_speed", "rotation_deg"): + entry[key] = next_val[key] + else: + continue + + entry["status"] = "interpolated" + t = entry["frame"] + translation_vel[t] = [entry["translation_dx"], entry["translation_dy"]] + rotation_vel[t] = np.radians(entry["rotation_deg"]) + n_interpolated += 1 + + translation_speed = np.linalg.norm(translation_vel, axis=1) + + if n_interpolated > 0: + print(f" Interpolated {n_interpolated} failed frame(s)") + + print(f" Per-frame motion estimation: {elapsed:.2f}s " + f"({elapsed/(num_frames-1)*1000:.1f}ms/pair)") + + if save_dir: + json_path = os.path.join(save_dir, "motion_stats.json") + with open(json_path, "w") as f: + json.dump(per_frame_data, f, indent=2) + print(f" Saved motion JSON to {json_path}") + print(f" Saved {len(os.listdir(viz_dir))} pair visualizations to {viz_dir}/") + + return { + "centroids": centroids, + "translation_vel": translation_vel, + "rotation_vel": rotation_vel, + "translation_speed": translation_speed, + "num_visible": num_visible, + } + + +def load_model(checkpoint: str, device: torch.device) -> torch.nn.Module: + model = tapir_model.TAPIR(pyramid_level=1) + model.load_state_dict(torch.load(checkpoint, map_location=device)) + model = model.to(device).eval() + return model + + +def main(): + parser = argparse.ArgumentParser( + description="BootsTAPIR per-frame velocity tracking" + ) + parser.add_argument("--video", required=True, help="Path to input video") + parser.add_argument("--mask-dir", required=True, + help="Directory with per-frame masks (frame_NNNNNN_masks/ subdirs)") + parser.add_argument("--object", required=True, + help="Object name (matches .png masks in each frame subdir)") + parser.add_argument("--num-points", type=int, default=20, + help="Number of query points (default: 20)") + parser.add_argument("--min-visible", type=int, default=5, + help="Min visible points for reliable motion estimates (default: 5)") + parser.add_argument( + "--checkpoint", + default=os.environ.get( + "TAPNET_CKPT", + os.path.join( + os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), + "checkpoints", + "tapir", + "bootstapir_checkpoint_v2.pt", + ), + ), + help="Path to BootsTAPIR checkpoint", + ) + parser.add_argument("--resize", type=int, nargs=2, default=[256, 256], + metavar=("H", "W"), + help="Resize resolution for inference (default: 256 256)") + parser.add_argument("--vis-threshold", type=float, default=0.5, + help="Visibility threshold (default: 0.5)") + parser.add_argument("--fps", type=float, default=10.0, + help="Video FPS for per-second conversion (default: 10)") + args = parser.parse_args() + + # Infer paths from video + object name + video_dir = os.path.dirname(args.video) + mask_name = f"{args.object}.png" + output = os.path.join(video_dir, f"output_tapir_{args.object}.mp4") + save_dir = os.path.join(video_dir, f"perframe_tracking_{args.object}") + + # Find the first frame with a mask for this object + first_frame = find_first_mask_frame(args.mask_dir, args.object) + first_mask = os.path.join(args.mask_dir, f"frame_{first_frame:06d}_masks", mask_name) + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + print(f"Using device: {device}") + + model = load_model(args.checkpoint, device) + + # Full-video tracking visualization + video = media.read_video(args.video) + height, width = video.shape[1:3] + resize_h, resize_w = args.resize + + query_points = sample_points_from_mask(first_frame, first_mask, args.num_points) + query_points = transforms.convert_grid_coordinates( + query_points, (1, height, width), (1, resize_h, resize_w), + coordinate_format="tyx", + ) + print(f"Sampled {args.num_points} points from mask: {first_mask}") + + frames = media.resize_video(video, (resize_h, resize_w)) + frames_t = torch.tensor(frames).to(device) + query_points_t = torch.tensor(query_points).to(device) + + with torch.no_grad(): + frames_pre = frames_t.float() / 255 * 2 - 1 + outputs = model(frames_pre[None], query_points_t.float()[None]) + tracks = outputs["tracks"][0] + occ = outputs["occlusion"][0] + exp_dist = outputs["expected_dist"][0] + visibles = ((1 - F.sigmoid(occ)) * (1 - F.sigmoid(exp_dist)) > args.vis_threshold) + + tracks = tracks.cpu().numpy() + visibles = visibles.cpu().numpy() + tracks = transforms.convert_grid_coordinates( + tracks, (resize_w, resize_h), (width, height) + ) + + video_viz = viz_utils.paint_point_track(video, tracks, visibles) + media.write_video(output, video_viz, fps=10) + print(f"Saved visualization to {output}") + print(f" Video: {video.shape[0]} frames, {height}x{width}") + print(f" Tracked {args.num_points} points") + + # Per-frame motion stats + print("Computing per-frame motion stats (re-sampling points each frame)...") + stats = compute_perframe_motion_stats( + args.video, args.mask_dir, mask_name, model, device, + num_points=args.num_points, resize_hw=tuple(args.resize), + threshold=args.vis_threshold, min_visible=args.min_visible, + save_dir=save_dir, + ) + print_motion_stats(stats, fps=args.fps) + + plot_path = output.rsplit(".", 1)[0] + "_motion.png" + save_motion_plot(stats, plot_path, fps=args.fps) + + print("Rendering overlay video...") + overlay_vid = overlay_motion_stats(video, stats) + overlay_path = output.rsplit(".", 1)[0] + "_overlay.mp4" + media.write_video(overlay_path, overlay_vid, fps=10) + print(f" Saved overlay video to {overlay_path}") + + +if __name__ == "__main__": + main() diff --git a/reconstruction/scripts/visualize_3d.py b/reconstruction/scripts/visualize_3d.py new file mode 100644 index 0000000000000000000000000000000000000000..a7d4e9b6610bfa88e6dabb60a4036546e065062d --- /dev/null +++ b/reconstruction/scripts/visualize_3d.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +""" +Interactive video mesh visualization with viser. + +Opens a 3D viewer with a frame slider to step through video frames, +updating the object mesh pose and hand meshes per frame. + +Usage: + python visualize_3d.py \ + --frames-dir /path/to/video_dir/all_frames \ + --layout-json /path/to/video_dir/obj_tracking_out//combined_visualization/layout_camera_frame_optimized.json \ + --mesh /path/to/video_dir/video_segmentation/masks/frame_000081_masks//.obj \ + --hand-meshes /path/to/video_dir//all_hand_meshes.npz \ + --scale 0.10970 \ + --translation-scale 1.0 \ + --port 8080 + +Example usage for clip 0641, drink task, blender_lid object: + + python visualize_3d.py \ + --frames-dir /path/to/video_dir/all_frames \ + --layout-json /path/to/video_dir/obj_tracking_out//combined_visualization/layout_camera_frame_optimized.json \ + --mesh /path/to/video_dir/obj_tracking_out//frame_000048//.obj \ + --hand-meshes /path/to/video_dir//all_hand_meshes.npz \ + --scale 0.4638 \ + --translation-scale 1.0 \ + --port 8080 + +""" + +import argparse +import math +import os +import sys +import time +import threading + +import cv2 +import numpy as np +from scipy.spatial.transform import Rotation as R + +import viser +import trimesh + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Interactive video mesh visualization with viser.', + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument('--frames-dir', type=str, required=True, + help='Directory containing frame images (e.g. 000000.png)') + parser.add_argument('--layout-json', type=str, required=True, + help='Path to layout JSON with per-frame poses') + parser.add_argument('--mesh', type=str, required=True, + help='Path to object mesh (.obj)') + parser.add_argument('--hand-meshes', type=str, default=None, + help='Path to hand meshes NPZ file') + parser.add_argument('--hands', type=str, default='both', + choices=['left', 'right', 'both'], + help='Which hand(s) to render') + parser.add_argument('--scale', type=float, default=0.19408, + help='Mesh scale factor') + parser.add_argument('--translation-scale', type=float, default=1.0, + help='Scale factor for translation values from JSON') + parser.add_argument('--fx', type=float, default=1346.4437866210938) + parser.add_argument('--fy', type=float, default=1346.4437866210938) + parser.add_argument('--cx', type=float, default=640.0) + parser.add_argument('--cy', type=float, default=360.0) + parser.add_argument('--width', type=int, default=1280) + parser.add_argument('--height', type=int, default=720) + parser.add_argument('--port', type=int, default=8080, + help='Viser server port') + parser.add_argument('--frustum-scale', type=float, default=0.2, + help='Scale of camera frustum visualization') + parser.add_argument('--fps', type=float, default=30.0, + help='Playback FPS for auto-play') + return parser.parse_args() + + +def pose_to_camera_frame(verts_pose): + """Convert vertices from pose frame (x-fwd, y-left, z-up) to camera frame (x-right, y-down, z-fwd).""" + verts_cam = np.zeros_like(verts_pose) + verts_cam[:, 0] = -verts_pose[:, 1] + verts_cam[:, 1] = -verts_pose[:, 2] + verts_cam[:, 2] = verts_pose[:, 0] + return verts_cam + + +def transform_mesh_to_camera_frame(vertices, rot_matrix, translation, scale): + """Apply scale, rotation, translation in pose frame, then convert to camera frame.""" + verts = vertices * scale + verts_pose = verts @ rot_matrix.T + translation + return pose_to_camera_frame(verts_pose) + + +def load_layout(json_path): + """Parse layout JSON into dict[frame_idx -> {quat, translation, scale, camera_frame}]. + + Auto-detects camera-frame layouts (with translation_camera_frame / quat_wxyz_camera_frame). + For camera-frame layouts, translation and quat are already in camera frame and need no conversion. + """ + import json + with open(json_path) as f: + data = json.load(f) + + is_camera_frame = data.get("frame") == "camera_frame" + + layout = {} + for obj in data["objects"]: + if "frame_index" not in obj and "frame_idx" not in obj: + continue + frame_idx = obj.get("frame_index", obj.get("frame_idx")) + pose = obj["local_to_scene"] + + if is_camera_frame and "translation_camera_frame" in pose and "quat_wxyz_camera_frame" in pose: + layout[frame_idx] = { + "quat": pose["quat_wxyz_camera_frame"], + "translation": pose["translation_camera_frame"], + "scale": pose.get("scale", None), + "translation_scale_optimized": pose.get("translation_scale_optimized", None), + "camera_frame": True, + } + else: + layout[frame_idx] = { + "quat": pose["new_quat"], + "translation": pose["translation"], + "scale": pose.get("scale", None), + "camera_frame": False, + } + + if is_camera_frame: + print(" [info] Detected camera-frame layout, skipping pose-frame conversion") + + return layout + + +def main(): + args = parse_args() + + # Validate paths + if not os.path.isdir(args.frames_dir): + print(f"[error] Frames directory not found: {args.frames_dir}") + sys.exit(1) + if not os.path.exists(args.layout_json): + print(f"[error] Layout JSON not found: {args.layout_json}") + sys.exit(1) + if not os.path.exists(args.mesh): + print(f"[error] Mesh not found: {args.mesh}") + sys.exit(1) + + # Load layout + print("Loading layout JSON...") + layout = load_layout(args.layout_json) + frame_indices = sorted(layout.keys()) + num_frames = len(frame_indices) + max_frame = max(frame_indices) + print(f" {num_frames} frames, range [{min(frame_indices)}, {max_frame}]") + + # Load mesh (shared topology) + print("Loading mesh...") + mesh = trimesh.load_mesh(args.mesh) + if not isinstance(mesh, trimesh.Trimesh): + mesh = mesh.dump(concatenate=True) + mesh_verts = np.array(mesh.vertices) + mesh_faces = mesh.faces + mesh_visual = mesh.visual + print(f" {len(mesh_verts)} vertices, {len(mesh_faces)} faces") + + # Load hand meshes + hand_data = None + hands_to_render = [] + hand_colors = {'left': (204, 128, 128), 'right': (128, 128, 204)} + if args.hand_meshes: + if not os.path.exists(args.hand_meshes): + print(f"[error] Hand meshes not found: {args.hand_meshes}") + sys.exit(1) + print("Loading hand meshes...") + hand_data = np.load(args.hand_meshes) + hands_to_render = ['left', 'right'] if args.hands == 'both' else [args.hands] + for hand in hands_to_render: + n = hand_data[f'{hand}_vertices'].shape[0] + print(f" {hand} hand: {n} frames, {hand_data[f'{hand}_vertices'].shape[1]} vertices") + + # Camera intrinsics + fov_y = 2.0 * math.atan(args.height / (2.0 * args.fy)) + aspect = args.width / args.height + + # Start viser server + server = viser.ViserServer(port=args.port) + server.scene.set_up_direction("-y") + + # Even multi-directional lighting so side / back orbit views stay bright. + # Camera frame: +x right, +y down (so -y is up), +z forward. Directional + # lights shine from `position` toward the world origin. + server.scene.add_light_ambient("/lights/ambient", intensity=0.6) + server.scene.add_light_hemisphere( + "/lights/hemi", + sky_color=(255, 255, 255), + ground_color=(180, 180, 200), + intensity=0.5, + ) + server.scene.add_light_directional( + "/lights/key_front", position=(0.5, -1.5, -1.0), intensity=0.7, + ) + server.scene.add_light_directional( + "/lights/fill_back", position=(0.0, -1.0, 2.5), intensity=0.7, + ) + server.scene.add_light_directional( + "/lights/fill_left", position=(-2.0, -0.5, 1.0), intensity=0.5, + ) + server.scene.add_light_directional( + "/lights/fill_right", position=(2.0, -0.5, 1.0), intensity=0.5, + ) + server.scene.add_light_directional( + "/lights/top", position=(0.0, -2.5, 1.0), intensity=0.4, + ) + + # Add coordinate frame + server.scene.add_frame("/camera/axes", show_axes=True, axes_length=0.1, axes_radius=0.005) + + # GUI controls + frame_slider = server.gui.add_slider( + "Frame", min=0, max=max_frame, step=1, initial_value=0, + ) + play_button = server.gui.add_button("Play") + fps_slider = server.gui.add_slider( + "FPS", min=1, max=60, step=1, initial_value=int(args.fps), + ) + texture_checkbox = server.gui.add_checkbox("Enable Texture", initial_value=False) + + # Playback state + playing = False + play_lock = threading.Lock() + + def update_frame(frame_idx): + """Update the scene for the given frame index.""" + # Load frame image + img_path = os.path.join(args.frames_dir, f"{frame_idx:06d}.png") + if not os.path.exists(img_path): + img_path = os.path.join(args.frames_dir, f"{frame_idx:06d}.jpg") + if not os.path.exists(img_path): + return + + frame_bgr = cv2.imread(img_path) + if frame_bgr is None: + return + frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB) + + # Camera frustum with frame image + server.scene.add_camera_frustum( + "/camera", + fov=fov_y, + aspect=aspect, + scale=args.frustum_scale, + image=frame_rgb, + format="jpeg", + jpeg_quality=90, + color=(30, 30, 30), + ) + + # Get pose from layout + if frame_idx not in layout: + return + + pose = layout[frame_idx] + quat_wxyz = pose["quat"] + quat_xyzw = np.array([quat_wxyz[1], quat_wxyz[2], quat_wxyz[3], quat_wxyz[0]]) + rot_matrix = R.from_quat(quat_xyzw).as_matrix() + + if pose.get("camera_frame"): + # Already in camera frame — apply directly + translation = np.array(pose["translation"]) + verts_cam = (mesh_verts * args.scale) @ rot_matrix.T + translation + else: + # Pose frame — reorder translation and convert + tx, ty, tz = pose["translation"] + translation = np.array([ + tz * args.translation_scale, + tx * args.translation_scale, + ty * args.translation_scale, + ]) + verts_cam = transform_mesh_to_camera_frame( + mesh_verts, rot_matrix, translation, args.scale, + ) + + # Compute object frame position and orientation in camera frame + if pose.get("camera_frame"): + obj_translation = np.array(pose["translation"]) + obj_rotation = rot_matrix + else: + tx, ty, tz = pose["translation"] + translation_pose = np.array([ + tz * args.translation_scale, + tx * args.translation_scale, + ty * args.translation_scale, + ]) + # Pose-to-camera rotation: maps pose-frame axes to camera-frame axes + R_pose2cam = np.array([ + [0, -1, 0], + [0, 0, -1], + [1, 0, 0], + ], dtype=float) + obj_translation = R_pose2cam @ translation_pose + obj_rotation = R_pose2cam @ rot_matrix + + # Add coordinate frame at the object's origin + obj_quat_xyzw = R.from_matrix(obj_rotation).as_quat() # [x,y,z,w] + obj_quat_wxyz = (obj_quat_xyzw[3], obj_quat_xyzw[0], obj_quat_xyzw[1], obj_quat_xyzw[2]) + server.scene.add_frame( + "/object_frame", + show_axes=True, + axes_length=0.08, + axes_radius=0.004, + wxyz=obj_quat_wxyz, + position=obj_translation, + ) + + # Update object mesh + if texture_checkbox.value: + mesh_cam = trimesh.Trimesh(vertices=verts_cam, faces=mesh_faces, visual=mesh_visual) + server.scene.add_mesh_trimesh("/object_mesh", mesh=mesh_cam) + else: + server.scene.add_mesh_simple( + "/object_mesh", + vertices=verts_cam.astype(np.float32), + faces=mesh_faces.astype(np.uint32), + color=(180, 180, 180), + side="double", + ) + + # Update hand meshes + if hand_data is not None: + for hand in hands_to_render: + hand_verts = hand_data[f'{hand}_vertices'] + hand_faces = hand_data[f'{hand}_faces'] + # Clamp frame index to available hand frames + hi = min(frame_idx, hand_verts.shape[0] - 1) + server.scene.add_mesh_simple( + f"/hand_{hand}", + vertices=hand_verts[hi].astype(np.float32), + faces=hand_faces.astype(np.uint32), + color=hand_colors[hand], + side="double", + ) + + # Initial frame + update_frame(0) + + @frame_slider.on_update + def on_slider_change(_): + update_frame(int(frame_slider.value)) + + @texture_checkbox.on_update + def on_texture_change(_): + update_frame(int(frame_slider.value)) + + @play_button.on_click + def on_play_click(_): + nonlocal playing + with play_lock: + playing = not playing + play_button.name = "Pause" if playing else "Play" + + def playback_loop(): + nonlocal playing + while True: + if playing: + current = int(frame_slider.value) + next_frame = current + 1 + if next_frame > max_frame: + next_frame = 0 + frame_slider.value = next_frame + update_frame(next_frame) + time.sleep(1.0 / fps_slider.value) + else: + time.sleep(0.05) + + playback_thread = threading.Thread(target=playback_loop, daemon=True) + playback_thread.start() + + print(f"\nViewer running at http://localhost:{args.port}") + print(f"Frames: 0-{max_frame}, use slider or Play button to navigate") + print("Press Ctrl+C to exit") + + try: + while True: + time.sleep(1.0) + except KeyboardInterrupt: + print("\nShutting down.") + + +if __name__ == "__main__": + main() diff --git a/reconstruction/scripts/viz_object_motion.py b/reconstruction/scripts/viz_object_motion.py new file mode 100644 index 0000000000000000000000000000000000000000..b1b3d03778069207fb19d985007d471fe63be3bd --- /dev/null +++ b/reconstruction/scripts/viz_object_motion.py @@ -0,0 +1,392 @@ +#!/usr/bin/env python3 +"""Render one overlay video: tracked 3D object + HaWoR hands on the RGB clip. + +Uses the optimized camera-frame layout when present (hand-anchored scale), +otherwise the combined layout from Fast-SAM3D. + + python viz_object_motion.py --video-dir /path/to/runs/ + +Writes: /obj_tracking_out//object_motion.mp4 +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys + +import cv2 +import numpy as np +import torch +from scipy.spatial.transform import Rotation as R +from pytorch3d.io import load_objs_as_meshes +from pytorch3d.structures import Meshes +from pytorch3d.renderer import TexturesVertex + +from run_project_mesh_combined import ( + DirectoryVideoReader, + _parse_rgb, + make_renderer, + read_video_frame, + render_combined, + render_mesh, + transform_to_camera_frame, +) + + +def parse_args(): + p = argparse.ArgumentParser( + description="One MP4 of 3D object + hand motion overlaid on the demo video.", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + p.add_argument("--video-dir", required=True, help="Pipeline run directory") + p.add_argument("--object", default=None, help="Object id (default: config.json)") + p.add_argument("--video", default=None, help="RGB source (mp4 or all_frames/). Default: clip.mp4") + p.add_argument("--mesh", default=None, help="Object .obj (default: SAM-3D mesh on ref frame)") + p.add_argument("--json", default=None, help="Layout JSON (prefers optimized camera-frame)") + p.add_argument("--hand-meshes", default=None, help="HaWoR all_hand_meshes.npz") + p.add_argument( + "--hands", + default="auto", + choices=["auto", "left", "right", "both", "none"], + help="Hands to overlay. auto = config.json anchor_hand (one side). " + "both also drops near-camera ghost meshes (unused HaWoR side).", + ) + p.add_argument("--output", default=None, help="Output mp4 path") + p.add_argument("--fps", type=float, default=30.0) + p.add_argument( + "--object-color", + default="0.15,0.85,0.45", + help="Solid overlay RGB in 0-1 as r,g,b", + ) + p.add_argument("--left-hand-color", default="0.95,0.35,0.35") + p.add_argument("--right-hand-color", default="0.35,0.45,0.95") + p.add_argument( + "--alpha", + type=float, + default=0.72, + help="Mesh overlay opacity on the video", + ) + p.add_argument("--device", default="auto", choices=["auto", "cpu", "cuda"]) + return p.parse_args() + + +def _object_id(video_dir, explicit): + if explicit: + return explicit.replace(" ", "_") + cfg = os.path.join(video_dir, "config.json") + if os.path.isfile(cfg): + with open(cfg) as f: + names = json.load(f).get("object_names") or [] + if names: + return str(names[0]).replace(" ", "_") + print("[error] pass --object or put object_names in config.json") + sys.exit(1) + + +def _ref_frame(video_dir): + cfg = os.path.join(video_dir, "config.json") + if os.path.isfile(cfg): + with open(cfg) as f: + return int(json.load(f).get("frame_number", 0)) + return 0 + + +def _anchor_hand(video_dir): + cfg = os.path.join(video_dir, "config.json") + if os.path.isfile(cfg): + with open(cfg) as f: + h = json.load(f).get("anchor_hand") + if h in ("left", "right"): + return h + return "right" + + +def _layout_json(video_dir, obj_id, explicit): + if explicit: + return explicit + root = os.path.join(video_dir, "obj_tracking_out", obj_id, "combined_visualization") + for name in ( + "layout_camera_frame_optimized.json", + "layout_camera_frame.json", + "layout.json", + ): + path = os.path.join(root, name) + if os.path.isfile(path): + return path + print(f"[error] no layout JSON under {root}") + sys.exit(1) + + +def _mesh_path(video_dir, obj_id, explicit): + if explicit: + return explicit + n = _ref_frame(video_dir) + path = os.path.join( + video_dir, + "video_segmentation", + "masks", + f"frame_{n:06d}_masks", + obj_id, + f"{obj_id}.obj", + ) + return path + + +def _rgb_source(video_dir, explicit): + if explicit: + return explicit + clip = os.path.join(video_dir, "clip.mp4") + frames = os.path.join(video_dir, "all_frames") + if os.path.isfile(clip): + return clip + if os.path.isdir(frames): + return frames + print("[error] need clip.mp4 or all_frames/ (or pass --video)") + sys.exit(1) + + +def _hand_meshes_npz(video_dir, explicit): + if explicit: + return explicit + clip = os.path.join(video_dir, "clip", "all_hand_meshes.npz") + if os.path.isfile(clip): + return clip + try: + for name in os.listdir(video_dir): + path = os.path.join(video_dir, name, "all_hand_meshes.npz") + if os.path.isfile(path): + return path + except FileNotFoundError: + pass + return None + + +def _hand_valid(hand_data, hand, frame_idx): + key = f"{hand}_valid" + if key not in hand_data.files: + return True + v = np.asarray(hand_data[key]) + if frame_idx >= v.shape[0]: + return False + val = np.asarray(v[frame_idx]).reshape(-1) + if val.size == 0: + return True + return bool(val.flat[0]) + + +def _hand_depth_ok(verts, min_median_z=0.15): + """Skip unused HaWoR side: infiller parks that mesh at the camera (z~0).""" + z = np.asarray(verts)[:, 2] + if not np.isfinite(z).all(): + return False + return float(np.median(z)) >= min_median_z + + +def main(): + args = parse_args() + video_dir = os.path.abspath(args.video_dir) + obj_id = _object_id(video_dir, args.object) + layout_path = _layout_json(video_dir, obj_id, args.json) + mesh_path = _mesh_path(video_dir, obj_id, args.mesh) + video_path = _rgb_source(video_dir, args.video) + out_path = args.output or os.path.join( + video_dir, "obj_tracking_out", obj_id, "object_motion.mp4" + ) + + if args.device == "auto": + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + else: + device = torch.device(args.device) + + print(f"device: {device}", flush=True) + print(f"layout: {layout_path}", flush=True) + print(f"mesh: {mesh_path}", flush=True) + print(f"video: {video_path}", flush=True) + print(f"output: {out_path}", flush=True) + + hand_npz = None if args.hands == "none" else _hand_meshes_npz(video_dir, args.hand_meshes) + hand_data = None + hands_to_render = [] + if args.hands != "none": + if not hand_npz or not os.path.isfile(hand_npz): + print("[error] HaWoR all_hand_meshes.npz not found (pass --hand-meshes or --hands none)") + sys.exit(1) + hand_data = np.load(hand_npz) + if args.hands == "auto": + hands_to_render = [_anchor_hand(video_dir)] + elif args.hands == "both": + hands_to_render = ["left", "right"] + else: + hands_to_render = [args.hands] + print(f"hands: {hand_npz} ({', '.join(hands_to_render)})", flush=True) + hand_colors = { + "left": _parse_rgb(args.left_hand_color), + "right": _parse_rgb(args.right_hand_color), + } + + with open(layout_path) as f: + data = json.load(f) + objects = [o for o in data.get("objects", []) if "frame_idx" in o] + objects.sort(key=lambda o: o["frame_idx"]) + if not objects: + print("[error] layout has no frame_idx objects") + sys.exit(1) + + fallback_intr = None + for obj in objects: + if "intrinsics_normalized" in obj: + fallback_intr = obj["intrinsics_normalized"] + break + if fallback_intr is None: + print("[error] layout has no intrinsics_normalized") + sys.exit(1) + + is_camera_frame = data.get("frame") == "camera_frame" + override_scale = None + tso = data.get("translation_scale_optimization") or {} + if is_camera_frame and "mesh_scale" in tso: + override_scale = float(tso["mesh_scale"]) + print(f"using optimized mesh_scale={override_scale:.6f}") + + if not os.path.isfile(mesh_path): + print(f"[error] mesh not found: {mesh_path}") + sys.exit(1) + mesh = load_objs_as_meshes([mesh_path], device=device) + rgb = _parse_rgb(args.object_color) + verts_list = mesh.verts_list() + faces_list = mesh.faces_list() + n_verts = verts_list[0].shape[0] + color_t = torch.tensor(rgb, dtype=torch.float32, device=device) + mesh = Meshes( + verts=verts_list, + faces=faces_list, + textures=TexturesVertex(verts_features=color_t.expand(n_verts, 3).unsqueeze(0)), + ) + + if os.path.isdir(video_path): + frame_source = DirectoryVideoReader(video_path) + width, height = frame_source.width, frame_source.height + cap = None + else: + cap = cv2.VideoCapture(video_path) + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + frame_source = None + + renderer_cache = {} + + def get_renderer(intr, W, H): + fx = intr["fx_norm"] * W + fy = intr["fy_norm"] * H + cx = intr.get("cx_norm", 0.5) * W + cy = intr.get("cy_norm", 0.5) * H + key = (round(fx, 4), round(fy, 4), round(cx, 4), round(cy, 4), W, H) + if key not in renderer_cache: + renderer_cache[key] = make_renderer(fx, fy, cx, cy, W, H, device) + return renderer_cache[key] + + os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True) + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + tmp_avi = out_path + ".tmp.avi" + writer = cv2.VideoWriter(tmp_avi, fourcc, args.fps, (width, height)) + if not writer.isOpened(): + print("[error] could not open video writer") + sys.exit(1) + + last_read_idx = -1 + n_ok = 0 + blend = float(np.clip(args.alpha, 0.0, 1.0)) + for i, obj in enumerate(objects): + frame_idx = obj["frame_idx"] + lts = obj["local_to_scene"] + scale = override_scale if override_scale is not None else lts["scale"][0] + if is_camera_frame: + quat = lts["quat_wxyz_camera_frame"] + translation = list(lts["translation_camera_frame"]) + else: + quat = lts["new_quat"] + tx, ty, tz = lts["translation"] + translation = [tz, tx, ty] + + if frame_source is not None: + frame_rgb = frame_source.read_frame(frame_idx) + else: + frame_rgb, last_read_idx = read_video_frame(cap, frame_idx, last_read_idx) + if frame_rgb is None: + print(f" skip frame {frame_idx} (no RGB)") + continue + + renderer = get_renderer(obj.get("intrinsics_normalized", fallback_intr), width, height) + quat_xyzw = np.array([quat[1], quat[2], quat[3], quat[0]]) + rot_matrix = R.from_quat(quat_xyzw).as_matrix() + + obj_verts_cam = transform_to_camera_frame( + mesh.verts_packed(), rot_matrix, translation, scale, device, + camera_frame=is_camera_frame, + ) + meshes_data = [(obj_verts_cam, mesh.faces_packed(), rgb)] + n_hand_frames = None + if hand_data is not None: + n_hand_frames = int(hand_data["right_vertices"].shape[0]) + if frame_idx < n_hand_frames: + for hand in hands_to_render: + verts_np = np.asarray(hand_data[f"{hand}_vertices"][frame_idx]) + if not _hand_valid(hand_data, hand, frame_idx): + continue + if not _hand_depth_ok(verts_np): + continue + verts = torch.tensor(verts_np, dtype=torch.float32, device=device) + faces = torch.tensor( + hand_data[f"{hand}_faces"], dtype=torch.int64, device=device, + ) + meshes_data.append((verts, faces, hand_colors[hand])) + + if len(meshes_data) > 1: + render_rgb, render_alpha = render_combined(meshes_data, renderer, device) + else: + render_rgb, render_alpha = render_mesh( + mesh, rot_matrix, translation, scale, renderer, device, + camera_frame=is_camera_frame, + ) + render_u8 = (render_rgb * 255).clip(0, 255).astype(np.uint8) + mask = render_alpha > 0.5 + result = frame_rgb.copy() + result[mask] = ( + (1.0 - blend) * result[mask].astype(np.float32) + + blend * render_u8[mask].astype(np.float32) + ).clip(0, 255).astype(np.uint8) + cv2.putText( + result, + f"frame {frame_idx}", + (12, 28), + cv2.FONT_HERSHEY_SIMPLEX, + 0.7, + (255, 255, 255), + 2, + cv2.LINE_AA, + ) + writer.write(cv2.cvtColor(result, cv2.COLOR_RGB2BGR)) + n_ok += 1 + if (i + 1) % 10 == 0 or i == 0: + print(f" [{i+1}/{len(objects)}] frame {frame_idx}", flush=True) + + writer.release() + if cap is not None: + cap.release() + + # Re-encode to H.264 for browsers / players. + import subprocess + cmd = [ + "ffmpeg", "-y", "-i", tmp_avi, + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", + out_path, + ] + subprocess.run(cmd, check=True) + os.remove(tmp_avi) + print(f"Wrote {n_ok} frames -> {out_path}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/reconstruction/setup.sh b/reconstruction/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a1997449a3f5513f8f4ab121b6cad415a088e5f --- /dev/null +++ b/reconstruction/setup.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# Isolated setup (venv only, no conda): +# 1) clone ML modules into reconstruction/modules +# 2) create reconstruction/.venv and pip-install into it +# 3) symlink repo checkpoints/ +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +"$HERE/setup/00_init_modules.sh" +"$HERE/setup/02_create_venv.sh" +"$HERE/setup/05_install_spconv.sh" +"$HERE/setup/06_install_nvdiffrast.sh" || echo "[warn] nvdiffrast skipped; on a GPU node run: $HERE/setup/06_install_nvdiffrast.sh" +"$HERE/setup/07_install_gsplat.sh" || echo "[warn] gsplat skipped; on a GPU node run: $HERE/setup/07_install_gsplat.sh" +"$HERE/setup/01_link_checkpoints.sh" +echo +echo "activate with: source $HERE/.venv/bin/activate" +echo "run with: $HERE/run_pipeline.sh --dexycb ..." diff --git a/reconstruction/setup/00_init_modules.sh b/reconstruction/setup/00_init_modules.sh new file mode 100644 index 0000000000000000000000000000000000000000..7d12c765350b7e6e90f248425e8c96f20b61a2d2 --- /dev/null +++ b/reconstruction/setup/00_init_modules.sh @@ -0,0 +1,34 @@ +#!/bin/bash +# Clone ML forks into reconstruction/modules (not from do-as-i-do/reconstruction). +set -eo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT/modules" +export GIT_LFS_SKIP_SMUDGE=1 + +clone() { + local url="$1" dest="$2" + if [ -d "$dest/.git" ]; then + echo "exists: $dest" + return + fi + rm -rf "$dest" + git clone --depth 1 "$url" "$dest" +} + +clone https://github.com/malik-group/sam3.git sam3 +clone https://github.com/malik-group/sam-3d-objects.git sam-3d-objects +clone https://github.com/malik-group/Fast-SAM3D.git Fast-SAM3D +clone https://github.com/malik-group/HaWoR.git HaWoR +clone https://github.com/malik-group/tapnet.git tapnet + +# InterFormer is vendored from third-party/InterFormer (not do-as-i-do). +IF_SRC="$(cd "$ROOT/.." && pwd)/third-party/InterFormer" +if [ -d "$IF_SRC/mmseg" ]; then + echo "sync InterFormer from $IF_SRC" + mkdir -p InterFormer + rsync -a --exclude '.git' --exclude 'tests' --exclude 'docker' --exclude '*.egg-info' \ + "$IF_SRC/" InterFormer/ +else + echo "[warn] $IF_SRC missing; skip InterFormer" +fi +echo "[00] modules cloned under $ROOT/modules" diff --git a/reconstruction/setup/01_link_checkpoints.sh b/reconstruction/setup/01_link_checkpoints.sh new file mode 100644 index 0000000000000000000000000000000000000000..048215f6d3bddd5fc099dda42a4bd217355a8f22 --- /dev/null +++ b/reconstruction/setup/01_link_checkpoints.sh @@ -0,0 +1,74 @@ +#!/bin/bash +# Point cloned modules at repo-level checkpoints/ (no extra downloads). +set -eo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "$ROOT/config/paths.sh" + +link_hf() { + local dest="$1" + mkdir -p "$(dirname "$dest")" + rm -rf "$dest" + ln -sfn "$SAM3D_CKPT_DIR" "$dest" + echo "linked $dest -> $SAM3D_CKPT_DIR" +} + +if [ -d "$SAM3D_DIR" ]; then + link_hf "$SAM3D_DIR/checkpoints/hf" +fi +if [ -d "$FASTSAM3D_DIR" ]; then + link_hf "$FASTSAM3D_DIR/checkpoints/hf" +fi + +# Fast-SAM3D --enable_ss_cache / --enable_slat_carving load *_faster.yaml. +# Those files are not in facebook/sam-3d-objects; same ckpt, faster Hydra target. +ensure_faster_generator_yaml() { + local src="$1" dst="$2" old="$3" new="$4" + if [ ! -f "$src" ]; then + echo "[warn] missing $src (cannot write $dst)" + return + fi + python3 - "$src" "$dst" "$old" "$new" <<'PY' +import sys +from pathlib import Path +src, dst, old, new = sys.argv[1:5] +text = Path(src).read_text() +if old not in text: + raise SystemExit(f"{old!r} not in {src}") +Path(dst).write_text(text.replace(old, new, 1)) +print(f"wrote {dst}") +PY +} +if [ -d "$SAM3D_CKPT_DIR" ]; then + ensure_faster_generator_yaml \ + "$SAM3D_CKPT_DIR/ss_generator.yaml" \ + "$SAM3D_CKPT_DIR/ss_generator_faster.yaml" \ + "sam3d_objects.model.backbone.generator.shortcut.model.ShortCut" \ + "sam3d_objects.model.backbone.generator.shortcut.model.ShortCut_faster" + ensure_faster_generator_yaml \ + "$SAM3D_CKPT_DIR/slat_generator.yaml" \ + "$SAM3D_CKPT_DIR/slat_generator_faster.yaml" \ + "sam3d_objects.model.backbone.generator.flow_matching.model.FlowMatching" \ + "sam3d_objects.model.backbone.generator.flow_matching.model.FlowMatching_faster" +fi + +if [ -d "$HAWOR_DIR" ]; then + mkdir -p "$HAWOR_DIR/weights/hawor" + rm -rf "$HAWOR_DIR/weights/hawor/checkpoints" + ln -sfn "$HAWOR_CKPT_DIR" "$HAWOR_DIR/weights/hawor/checkpoints" + echo "linked HaWoR checkpoints -> $HAWOR_CKPT_DIR" + MANO_MODELS="${MANO_DIR:-$CHECKPOINTS_DIR/mano_v1_2}/models" + if [ -f "$MANO_MODELS/MANO_RIGHT.pkl" ]; then + mkdir -p "$HAWOR_DIR/_DATA/data/mano" "$HAWOR_DIR/_DATA/data_left/mano_left" + ln -sfn "$MANO_MODELS/MANO_RIGHT.pkl" "$HAWOR_DIR/_DATA/data/mano/MANO_RIGHT.pkl" + ln -sfn "$MANO_MODELS/MANO_LEFT.pkl" "$HAWOR_DIR/_DATA/data_left/mano_left/MANO_LEFT.pkl" + echo "linked MANO pkls from $MANO_MODELS" + else + echo "[warn] MANO pkls not found at $MANO_MODELS (expected MANO_RIGHT.pkl / MANO_LEFT.pkl)" + fi +fi + +echo "[01] checkpoint links ready" +echo " SAM3 $SAM3_CHECKPOINT" +echo " MoGe $MOGE_CHECKPOINT" +echo " TAPIR $TAPNET_CKPT" +echo " SAM3D $SAM3D_CKPT_DIR" diff --git a/reconstruction/setup/02_create_venv.sh b/reconstruction/setup/02_create_venv.sh new file mode 100644 index 0000000000000000000000000000000000000000..206ec6a25a654d9ad076fd3b632c2042e4cd8bc4 --- /dev/null +++ b/reconstruction/setup/02_create_venv.sh @@ -0,0 +1,131 @@ +#!/bin/bash +# Isolated reconstruction/.venv — no conda, no apt python3-venv. +# Must use CPython 3.10/3.11 so numpy 1.26 and torch install as wheels. +# uv's default 3.13 has no numpy==1.26 wheel (SAM3 pins numpy==1.26). +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +VENV="$ROOT/.venv" +export PATH="${HOME}/.local/bin:${PATH}" + +pick_python() { + # Prefer real distro interpreters. ~/.local/bin/python3.11 is often a uv stub + # that fails with --python-preference only-system. + if [ -x /usr/bin/python3.10 ]; then + echo /usr/bin/python3.10 + return + fi + if [ -x /usr/bin/python3.11 ]; then + echo /usr/bin/python3.11 + return + fi + if [ -x /usr/bin/python3 ]; then + echo /usr/bin/python3 + return + fi + echo "error: no /usr/bin/python3.10" >&2 + exit 1 +} + +PYTHON="$(pick_python)" +PYVER="$("$PYTHON" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')" +case "$PYVER" in + 3.10|3.11) ;; + *) + echo "error: $PYTHON is $PYVER; SAM3's numpy==1.26 has no 3.13 wheel. Use PYTHON=/usr/bin/python3.10" >&2 + exit 1 + ;; +esac + +make_venv() { + rm -rf "$VENV" + if command -v uv >/dev/null 2>&1; then + echo "[venv] uv venv --python $PYTHON ($PYVER) $VENV" + uv venv --python "$PYTHON" "$VENV" + return + fi + echo "[venv] uv not found; pip install --user virtualenv" + "$PYTHON" -m pip install --user virtualenv + "$PYTHON" -m virtualenv "$VENV" +} + +pip_in_venv() { + if command -v uv >/dev/null 2>&1; then + uv pip install --python "$VENV/bin/python" --override "$ROOT/uv.override.txt" "$@" + else + "$VENV/bin/python" -m pip install "$@" + fi +} + +make_venv +# shellcheck disable=SC1091 +source "$VENV/bin/activate" +"$VENV/bin/python" -c 'import sys; assert sys.version_info[:2] in {(3,10),(3,11)}, sys.version' + +pip_in_venv -U pip setuptools wheel +# Binary numpy 1.26.x (SAM3 pin). Never build from source on this cluster. +pip_in_venv --only-binary=:all: "numpy==1.26.4" +pip_in_venv -r "$ROOT/requirements-prep.txt" + +if command -v nvidia-smi >/dev/null 2>&1; then + echo "[venv] installing torch (CUDA wheel)" + pip_in_venv torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128 \ + || pip_in_venv torch torchvision torchaudio +else + echo "[venv] no GPU visible; installing CPU torch" + pip_in_venv torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu +fi + +pip_in_venv \ + opencv-python-headless einops omegaconf hydra-core tqdm mediapy matplotlib \ + decord pycocotools psutil iopath timm ftfy regex huggingface_hub \ + "setuptools<81" + +# SAM-3D mesh stage (must match the repo pin; builds from source on the GPU node). +# --no-build-isolation: pytorch3d's setup imports torch and uv's isolated build env has none. +if command -v uv >/dev/null 2>&1; then + echo "[venv] pytorch3d (no build isolation)" + FORCE_CUDA=1 uv pip install --python "$VENV/bin/python" --no-build-isolation \ + "pytorch3d @ git+https://github.com/facebookresearch/pytorch3d.git@75ebeeaea0908c5527e7b1e305fbc7681382db47" \ + || echo "[warn] pytorch3d skipped" +fi + +if [ -f "$ROOT/modules/sam3/pyproject.toml" ] || [ -f "$ROOT/modules/sam3/setup.py" ]; then + echo "[venv] install modules/sam3 (numpy already installed)" + pip_in_venv -e "$ROOT/modules/sam3" || true +fi +if [ -f "$ROOT/modules/sam-3d-objects/pyproject.toml" ] || [ -f "$ROOT/modules/sam-3d-objects/setup.py" ]; then + echo "[venv] install modules/sam-3d-objects" + pip_in_venv -e "$ROOT/modules/sam-3d-objects" || true + # Do not install the full SAM-3D requirements.txt (pins torch 2.5+cu121 and + # can pull CPU-only `spconv`). CUDA spconv is setup/05_install_spconv.sh. +fi +if [ -d "$ROOT/modules/tapnet/.git" ] || [ -f "$ROOT/modules/tapnet/setup.py" ] || [ -f "$ROOT/modules/tapnet/pyproject.toml" ]; then + echo "[venv] install modules/tapnet" + pip_in_venv -e "$ROOT/modules/tapnet[torch]" || pip_in_venv -e "$ROOT/modules/tapnet" || true +fi +if [ -f "$ROOT/modules/HaWoR/requirements.txt" ]; then + echo "[venv] HaWoR requirements (skip mmcv; chumpy from git)" + grep -vE '^mmcv|^chumpy' "$ROOT/modules/HaWoR/requirements.txt" | pip_in_venv -r /dev/stdin || true + pip_in_venv -e "$ROOT/modules/HaWoR" || true + # PyPI chumpy 0.70 needs pip at build time and fails on numpy 1.26 (np.bool). + pip_in_venv --no-build-isolation "git+https://github.com/mattloper/chumpy.git" || true +fi + +pip_in_venv "geocalib @ git+https://github.com/cvg/GeoCalib.git" || echo "[warn] geocalib skipped" +pip_in_venv "moge @ git+https://github.com/microsoft/MoGe.git" || echo "[warn] moge skipped" +pip_in_venv "utils3d @ git+https://github.com/EasternJournalist/utils3d.git@c5daf6f6c244d251f252102d09e9b7bcef791a38" || echo "[warn] utils3d skipped" + +if [ -f "$ROOT/modules/InterFormer/setup.py" ]; then + echo "[venv] InterFormer (mmseg) — mmcv/mmdet may fail on this torch; install later if needed" + pip_in_venv mmengine "mmcv>=2.0.0,<2.2.0" mmdet || echo "[warn] mmcv/mmdet skipped" + pip_in_venv -e "$ROOT/modules/InterFormer" || true +fi + +FFMPEG_REAL="$("$VENV/bin/python" -c "import imageio_ffmpeg; print(imageio_ffmpeg.get_ffmpeg_exe())")" +ln -sfn "$FFMPEG_REAL" "$VENV/bin/ffmpeg" + +echo +echo "[ok] isolated venv: $VENV" +"$VENV/bin/python" -c "import sys,numpy; print('python', sys.version.split()[0], sys.executable); print('numpy', numpy.__version__)" +"$VENV/bin/ffmpeg" -version | head -n 1 +echo " source $VENV/bin/activate" diff --git a/reconstruction/setup/03_install_pytorch3d.sh b/reconstruction/setup/03_install_pytorch3d.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e19d640afe80a2da369db69d605f9ee28cd82e0 --- /dev/null +++ b/reconstruction/setup/03_install_pytorch3d.sh @@ -0,0 +1,68 @@ +#!/bin/bash +# Build pytorch3d into reconstruction/.venv (needs nvcc, not just pip torch). +# Isolated: no conda. Uses system CUDA module if present, else pip nvidia-cuda-nvcc-cu12. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +VENV="$ROOT/.venv" +export PATH="${HOME}/.local/bin:${PATH}" +# shellcheck disable=SC1091 +source "$VENV/bin/activate" + +uv pip install --python "$VENV/bin/python" ninja + +find_nvcc() { + if command -v nvcc >/dev/null 2>&1; then + command -v nvcc + return + fi + for p in \ + /usr/local/cuda/bin/nvcc \ + /usr/local/cuda-12.8/bin/nvcc \ + /usr/local/cuda-12.4/bin/nvcc \ + /usr/local/cuda-12.1/bin/nvcc \ + /opt/cuda/bin/nvcc; do + [ -x "$p" ] && echo "$p" && return + done + python - <<'PY' +import glob, os, sys +from pathlib import Path +root = Path(sys.prefix) +hits = list(root.glob("lib/python*/site-packages/nvidia/cuda_nvcc/bin/nvcc")) +print(hits[0] if hits else "", end="") +PY +} + +NVCC="$(find_nvcc || true)" +if [ -z "$NVCC" ] || [ ! -x "$NVCC" ]; then + echo "[p3d] nvcc not on PATH; installing nvidia-cuda-nvcc-cu12 into the venv" + uv pip install --python "$VENV/bin/python" nvidia-cuda-nvcc-cu12 nvidia-cuda-cccl-cu12 + NVCC="$(find_nvcc)" +fi +if [ -z "$NVCC" ] || [ ! -x "$NVCC" ]; then + echo "error: still no nvcc. On this cluster try: module avail cuda && module load cuda" >&2 + exit 1 +fi + +export CUDA_HOME="$(cd "$(dirname "$NVCC")/.." && pwd)" +export FORCE_CUDA=1 +export TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST:-8.0;8.6;8.9;9.0}" +export MAX_JOBS="${MAX_JOBS:-8}" + +# CUB: toolkit include, or pip cccl +if [ -d "$CUDA_HOME/include/cub" ]; then + export CUB_HOME="$CUDA_HOME/include" +fi +CCCL="$(python -c "import glob,sys; from pathlib import Path; p=list(Path(sys.prefix).glob('lib/python*/site-packages/nvidia/cuda_cccl/include')); print(p[0] if p else '')")" +if [ -n "$CCCL" ] && [ -d "$CCCL/cub" ]; then + export CUB_HOME="$CCCL" +fi + +echo "[p3d] nvcc=$NVCC" +echo "[p3d] CUDA_HOME=$CUDA_HOME" +echo "[p3d] CUB_HOME=${CUB_HOME:-unset}" +"$NVCC" --version | head -n 4 + +uv pip install --python "$VENV/bin/python" --no-build-isolation \ + "pytorch3d @ git+https://github.com/facebookresearch/pytorch3d.git@75ebeeaea0908c5527e7b1e305fbc7681382db47" + +python -c "import pytorch3d; from pytorch3d.transforms import quaternion_to_matrix; print('pytorch3d ok', pytorch3d.__version__)" diff --git a/reconstruction/setup/04_install_mmcv.sh b/reconstruction/setup/04_install_mmcv.sh new file mode 100644 index 0000000000000000000000000000000000000000..f74c46ada37c6453f2bcd41d8704b2a5193a16d5 --- /dev/null +++ b/reconstruction/setup/04_install_mmcv.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# Build mmcv C++/CUDA ops against reconstruction/.venv torch (no conda). +# Prebuilt OpenMMLab wheels are for torch 2.1; this venv is 2.11+cu128. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "$ROOT/config/paths.sh" +export PATH="${HOME}/.local/bin:${PATH}" +PYTHON="${ROOT}/.venv/bin/python" +if [[ ! -x "$PYTHON" ]]; then + echo "missing $PYTHON" >&2 + exit 1 +fi +if [[ -z "${CUDA_HOME:-}" ]]; then + echo "CUDA_HOME is empty; nvcc is required to compile mmcv ops" >&2 + exit 1 +fi +if ! command -v nvcc >/dev/null; then + echo "nvcc not on PATH. export CUDA_HOME and PATH first." >&2 + exit 1 +fi +echo "python: $PYTHON" +"$PYTHON" -c "import torch; print('torch', torch.__version__, 'cuda', torch.version.cuda)" +echo "nvcc: $(nvcc --version | tail -n 1)" +echo "CUDA_HOME=$CUDA_HOME" + +uv pip uninstall --python "$PYTHON" mmcv || true +export MMCV_WITH_OPS=1 +export FORCE_CUDA=1 +uv pip install --python "$PYTHON" ninja +# 2.2.0 is what pip resolves for torch 2.11 source builds. InterFormer +# originally asserted mmcv<2.2.0; that assert is now a warning. +uv pip install --python "$PYTHON" --no-build-isolation --no-binary mmcv \ + 'mmcv>=2.1.0,<2.3.0' + +"$PYTHON" -c "import mmcv, mmcv.ops; print('mmcv', mmcv.__version__, 'ops ok')" +echo "[ok] mmcv built against this venv's torch" diff --git a/reconstruction/setup/05_install_spconv.sh b/reconstruction/setup/05_install_spconv.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cd607a57ec3f8c7970d7d77c76e020bf0699e52 --- /dev/null +++ b/reconstruction/setup/05_install_spconv.sh @@ -0,0 +1,35 @@ +#!/bin/bash +# SAM-3D sparse convs need a CUDA spconv wheel. Plain `spconv` on PyPI is +# CPU-only and fails with: not implemented for CPU ONLY build. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +export PATH="${HOME}/.local/bin:${PATH}" +PYTHON="${ROOT}/.venv/bin/python" +if [[ ! -x "$PYTHON" ]]; then + echo "missing $PYTHON" >&2 + exit 1 +fi + +uv pip uninstall --python "$PYTHON" spconv || true + +ok=0 +for pkg in spconv-cu126==2.3.8 spconv-cu124==2.3.8 spconv-cu121==2.3.8; do + echo "[spconv] trying $pkg" + if uv pip install --python "$PYTHON" "$pkg"; then + ok=1 + break + fi +done +if [[ "$ok" -ne 1 ]]; then + echo "failed to install a CUDA spconv wheel" >&2 + exit 1 +fi + +"$PYTHON" -c " +from spconv.cppconstants import CPU_ONLY_BUILD +import spconv +assert CPU_ONLY_BUILD is False, 'still CPU-only spconv' +print('spconv', spconv.__file__) +print('CPU_ONLY_BUILD', CPU_ONLY_BUILD) +" +echo "[ok] CUDA spconv" diff --git a/reconstruction/setup/06_install_nvdiffrast.sh b/reconstruction/setup/06_install_nvdiffrast.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a2c64da62c1d14a4dde6a34da40f9064ba44a12 --- /dev/null +++ b/reconstruction/setup/06_install_nvdiffrast.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# NVIDIA nvdiffrast — required by utils3d.torch.rasterization (SAM-3D mesh post). +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "$ROOT/config/paths.sh" +export PATH="${HOME}/.local/bin:${PATH}" +PYTHON="${ROOT}/.venv/bin/python" +if [[ ! -x "$PYTHON" ]]; then + echo "missing $PYTHON" >&2 + exit 1 +fi +if [[ -z "${CUDA_HOME:-}" ]] || ! command -v nvcc >/dev/null; then + echo "nvcc required. export CUDA_HOME (e.g. /app/apps/cuda/12.6.2) and PATH." >&2 + exit 1 +fi +echo "python: $PYTHON" +"$PYTHON" -c "import torch; print('torch', torch.__version__, 'cuda', torch.version.cuda)" +echo "nvcc: $(nvcc --version | tail -n 1)" +echo "CUDA_HOME=$CUDA_HOME" +# Login / compile-without-GPU: torch has no device list, so arch flags are empty. +export TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST:-8.0;9.0}" +export FORCE_CUDA="${FORCE_CUDA:-1}" +echo "TORCH_CUDA_ARCH_LIST=$TORCH_CUDA_ARCH_LIST" + +uv pip install --python "$PYTHON" ninja +# Isolated build env has no torch headers; compile against the venv. +uv pip install --python "$PYTHON" --no-build-isolation \ + "nvdiffrast @ git+https://github.com/NVlabs/nvdiffrast.git" + +"$PYTHON" -c "import nvdiffrast; import nvdiffrast.torch as dr; print('nvdiffrast', nvdiffrast.__file__)" +echo "[ok] nvdiffrast" diff --git a/reconstruction/setup/07_install_gsplat.sh b/reconstruction/setup/07_install_gsplat.sh new file mode 100644 index 0000000000000000000000000000000000000000..8a49e15fb412dcbf0e6736f36996034d94f0789b --- /dev/null +++ b/reconstruction/setup/07_install_gsplat.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# gsplat CUDA rasterizer — SAM-3D texture baking (not INRIA diff_gaussian_rasterization). +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "$ROOT/config/paths.sh" +export PATH="${HOME}/.local/bin:${PATH}" +PYTHON="${ROOT}/.venv/bin/python" +if [[ ! -x "$PYTHON" ]]; then + echo "missing $PYTHON" >&2 + exit 1 +fi +if [[ -z "${CUDA_HOME:-}" ]] || ! command -v nvcc >/dev/null; then + echo "nvcc required. export CUDA_HOME (e.g. /app/apps/cuda/12.6.2) and PATH." >&2 + exit 1 +fi +echo "python: $PYTHON" +"$PYTHON" -c "import torch; print('torch', torch.__version__, 'cuda', torch.version.cuda)" +echo "nvcc: $(nvcc --version | tail -n 1)" +echo "CUDA_HOME=$CUDA_HOME" +export TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST:-8.0;9.0}" +export FORCE_CUDA="${FORCE_CUDA:-1}" +export MAX_JOBS="${MAX_JOBS:-8}" +echo "TORCH_CUDA_ARCH_LIST=$TORCH_CUDA_ARCH_LIST" + +uv pip install --python "$PYTHON" ninja +uv pip install --python "$PYTHON" --no-build-isolation \ + "gsplat @ git+https://github.com/nerfstudio-project/gsplat.git@2323de5905d5e90e035f792fe65bad0fedd413e7" + +"$PYTHON" -c "from gsplat import rasterization; print('gsplat rasterization ok', rasterization)" +echo "[ok] gsplat" diff --git a/reconstruction/uv.override.txt b/reconstruction/uv.override.txt new file mode 100644 index 0000000000000000000000000000000000000000..9ca72aaca8d936f9394483b622465dee3da81e8f --- /dev/null +++ b/reconstruction/uv.override.txt @@ -0,0 +1,3 @@ +# SAM3 declares numpy==1.26 (resolves to 1.26.0, no cp313 wheel). +# 1.26.4 is the same 1.26 series and has manylinux wheels for 3.10/3.11. +numpy==1.26.4 diff --git a/retarget/.gitignore b/retarget/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d4cdf9971edb565080c3821a15c1e425231fd3d9 --- /dev/null +++ b/retarget/.gitignore @@ -0,0 +1,2 @@ +.venv/ +assets/g1_inspire/meshes/ diff --git a/retarget/README.md b/retarget/README.md new file mode 100644 index 0000000000000000000000000000000000000000..378323ccda6169c2aa269f63829ad5c84a61fac1 --- /dev/null +++ b/retarget/README.md @@ -0,0 +1,90 @@ +# G1 five-finger retarget (Wuji default) + +Convert HaWoR **MANO** hands to the **Unitree G1 Wuji** hand (5 fingers, 20 DoF: +`{left,right}_finger<1-5>_joint<1-4>`). That matches the closed-loop play robot +in `simulation/` (`--hands wuji`). + +`--hand inspire` still maps onto Inspire DFQ (`L_`/`R_` joint names) if you need +the older pack. + +NVIDIA `third-party/video_to_data/.../retarget` maps MANO → **Dex3** (3 fingers). +This tree uses the same Pink IK idea but a **separate venv**. Do not install +Pinocchio into `reconstruction/.venv` (it pulls NumPy 2 and breaks SAM3). + +## Setup + +```bash +cd retarget +./setup.sh +source .venv/bin/activate +``` + +`setup.sh` also runs `extract_wuji_hand_urdf.py`, which slices +`left_hand.urdf` / `right_hand.urdf` (and STLs) out of CoordEx's full G1-Wuji +URDF into `assets/g1_wuji/`. + +## Run + +After reconstruction (HaWoR `clip/all_hand_meshes.npz`): + +```bash +cd retarget +./hawor_to_g1.sh \ + --video-dir ../reconstruction/runs/20200709_141754_836212060125 \ + --hands auto +``` + +`--hands auto` uses `config.json` `anchor_hand`. Writes: + +`reconstruction/runs//obj_tracking_out/g1_wuji_retarget.npz` + +Inspire (old default): + +```bash +./hawor_to_g1.sh --video-dir ... --hand inspire +``` + +## Visualize (MP4) + +Pinocchio visual STLs + HaWoR MANO (optional tracked object). Uses pyrender on a +GPU node with EGL; this cluster login node has no `libEGL`, so the script +**CPU-rasterizes** the same meshes. + +```bash +./vis_retarget_video.sh \ + --video-dir ../reconstruction/runs/20200709_141754_836212060125 +``` + +Writes `.../obj_tracking_out/g1_wuji_retarget.mp4` (**gold = G1 Wuji**, **green = MANO**). + +Composite on `clip.mp4`: + +```bash +./vis_retarget_video.sh --video-dir ... --view overlay +``` + +Writes `g1_wuji_retarget_overlay.mp4`. + +- `{side}_q` — Pinocchio `q` per frame (free-flyer 7 + finger joints) +- `{side}_tip_err` — mean fingertip position error (m) +- `{side}_joint_names` +- `hand` — `"wuji"` or `"inspire"` + +Free-flyer `q[:7]` is wrist/palm pose in the HaWoR camera frame (x-right, y-down, z-forward). + +Finger mapping for Wuji (same as the play USD): finger1 = thumb, 2 = index, 3 = +middle, 4 = ring, 5 = pinky. IK targets are the existing `*_finger*_tip_link` +frames plus a `*_palm_ik` frame at the MCP centroid. + +## Isaac Lab + +Pack Z-up poses + a scaled object URDF for `simulation/scripts/replay_v2d.py` +(kinematic teleport): + +```bash +./export_isaaclab.sh --video-dir ../reconstruction/runs/20200709_141754_836212060125 +``` + +Writes `obj_tracking_out/isaaclab_replay.npz` and copies the Wuji hand URDF into +`obj_tracking_out/isaaclab_assets/g1_wuji/`. Then from `simulation/`: +`./replay_v2d.sh --npz --headless`. diff --git a/retarget/__init__.py b/retarget/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6512bbf54c5af1ef41ab9f11f7071304aff8ac04 --- /dev/null +++ b/retarget/__init__.py @@ -0,0 +1 @@ +"""HaWoR MANO → Unitree G1 Inspire DFQ 5-finger retarget.""" diff --git a/retarget/__pycache__/hand_kinematics.cpython-310.pyc b/retarget/__pycache__/hand_kinematics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3bbfce81617f784d19c5b700fbeecf499d5bf7e Binary files /dev/null and b/retarget/__pycache__/hand_kinematics.cpython-310.pyc differ diff --git a/retarget/__pycache__/params.cpython-310.pyc b/retarget/__pycache__/params.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cb8271c8ad6073649fc39b77fee1d9b20f4caa4 Binary files /dev/null and b/retarget/__pycache__/params.cpython-310.pyc differ diff --git a/retarget/assets/g1_inspire/DFQ_left_hand.urdf b/retarget/assets/g1_inspire/DFQ_left_hand.urdf new file mode 100644 index 0000000000000000000000000000000000000000..b9b6b8ee22fad8d5fda2aea91d672c18723a336b --- /dev/null +++ b/retarget/assets/g1_inspire/DFQ_left_hand.urdf @@ -0,0 +1,422 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/retarget/assets/g1_inspire/DFQ_right_hand.urdf b/retarget/assets/g1_inspire/DFQ_right_hand.urdf new file mode 100644 index 0000000000000000000000000000000000000000..511c8537bbf320aff5939f75b587362b0602b6f7 --- /dev/null +++ b/retarget/assets/g1_inspire/DFQ_right_hand.urdf @@ -0,0 +1,422 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/retarget/assets/g1_inspire/meshes/L_hand_base_link.STL b/retarget/assets/g1_inspire/meshes/L_hand_base_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..88d668d9b03e3a74577668bb7c073d3a415f27bd --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/L_hand_base_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33ab4e97801bd5421903a78f5977a44e477ae8653eaf32358d35633e465411e0 +size 1448084 diff --git a/retarget/assets/g1_inspire/meshes/Link11_L.STL b/retarget/assets/g1_inspire/meshes/Link11_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..9933a6ce1083723badfbf22087776755ae318b93 Binary files /dev/null and b/retarget/assets/g1_inspire/meshes/Link11_L.STL differ diff --git a/retarget/assets/g1_inspire/meshes/Link11_R.STL b/retarget/assets/g1_inspire/meshes/Link11_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..30817a810af3469520afab935158d05268a63857 Binary files /dev/null and b/retarget/assets/g1_inspire/meshes/Link11_R.STL differ diff --git a/retarget/assets/g1_inspire/meshes/Link12_L.STL b/retarget/assets/g1_inspire/meshes/Link12_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..894e95880667713843b8e765dad9f87b3c0c786d --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link12_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f35b78a9cab1007ac8b73023a5862ed055d33951b5742f9a783997d38e99551 +size 917284 diff --git a/retarget/assets/g1_inspire/meshes/Link12_R.STL b/retarget/assets/g1_inspire/meshes/Link12_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..930d8478e593f5c53e6b05e13d605bd3e1c4525e --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link12_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:347212bdb22d80fb364dd889de934d6fbb935e38d1f24c682caed84f7b6ea8cb +size 921984 diff --git a/retarget/assets/g1_inspire/meshes/Link13_L.STL b/retarget/assets/g1_inspire/meshes/Link13_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..33694b12879c6d18582cd72179e4d4a94adca851 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link13_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e93b55f2ae73fe0f62cd27e81d8a4620211068cb1c9b25e6414e802a37541ee +size 488584 diff --git a/retarget/assets/g1_inspire/meshes/Link13_R.STL b/retarget/assets/g1_inspire/meshes/Link13_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..3e75d8d23377c4fb165150f534aa4875264149a2 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link13_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c157dfe5b666efb1c3d51342e56f5caad2fc350930ac21ee1e02d956c1034ca3 +size 483284 diff --git a/retarget/assets/g1_inspire/meshes/Link14_L.STL b/retarget/assets/g1_inspire/meshes/Link14_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..29739dcb2b3f3d77f5b490ab1e99c0d29391b8be --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link14_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b677bcdcddcd90ff4b005f83daa9e50eb4003d5e67ea4eeefbf857718716c164 +size 155184 diff --git a/retarget/assets/g1_inspire/meshes/Link14_R.STL b/retarget/assets/g1_inspire/meshes/Link14_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..6a951090c6dc5f14febb0644223eea031f69140d --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link14_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:564aa8c3d2ff0e51b75736a8b01b4c309c7098582a424ea1391ccb75125519d8 +size 155584 diff --git a/retarget/assets/g1_inspire/meshes/Link15_L.STL b/retarget/assets/g1_inspire/meshes/Link15_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..a814265e0cdd56668ea507b4b1d1abb262e1284c --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link15_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c601e7aa8e1c91310a75190dfb6b95a8dc981b707e5f104f9ca9ecbea118b34 +size 407184 diff --git a/retarget/assets/g1_inspire/meshes/Link15_R.STL b/retarget/assets/g1_inspire/meshes/Link15_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..d8528350adb18330616c68e4c9b912b1fb119afe --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link15_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09c120f7fb7761aa97d89240cd8cb8e30c40ee60093cbb8b1c2e13a68a8e3845 +size 411884 diff --git a/retarget/assets/g1_inspire/meshes/Link16_L.STL b/retarget/assets/g1_inspire/meshes/Link16_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..c5e50bc9a8f303c143bd49608f635ddd251522f1 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link16_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d8508c65db44e2349f37e8ab4c057d204a40093d4733897ae5b51075b00f5e9 +size 329384 diff --git a/retarget/assets/g1_inspire/meshes/Link16_R.STL b/retarget/assets/g1_inspire/meshes/Link16_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..9b829bfacd6208764ceedcf3f83027077de1f942 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link16_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6942ada1189cdf442124c6b8935f3e3a3ae310092a3a1414fdeb0bd6d23578bb +size 335484 diff --git a/retarget/assets/g1_inspire/meshes/Link17_L.STL b/retarget/assets/g1_inspire/meshes/Link17_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..95ff58a479e108284ab82f283505171a5f9b24fd --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link17_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca2a68fed635eca290b234fbdc649779036ba5bac753addcb7ce6a086ad95949 +size 407184 diff --git a/retarget/assets/g1_inspire/meshes/Link17_R.STL b/retarget/assets/g1_inspire/meshes/Link17_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..6ccd11de30e6d827ee8df3a5b751162908cbf5cb --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link17_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36fc62c609800ce6d4521ae6f3c4c9b8a732be28654f32f04893696c17e6930c +size 411884 diff --git a/retarget/assets/g1_inspire/meshes/Link18_L.STL b/retarget/assets/g1_inspire/meshes/Link18_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..3a43b7cd7e76bc3f1ebc48292deda9de241e9215 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link18_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9425aea7ebbf6d1dfb2eb0714fb44dfaea6b6a81c71d6e96c8d3950f636dfa62 +size 182684 diff --git a/retarget/assets/g1_inspire/meshes/Link18_R.STL b/retarget/assets/g1_inspire/meshes/Link18_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..3e6ff9f9b7bf00e90f71f5344223ca7a6a3551b9 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link18_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9711fac7df0c09a372e1529f74b9d506d37abf3ebc3241d976ad45e5ee7e2d69 +size 182984 diff --git a/retarget/assets/g1_inspire/meshes/Link19_L.STL b/retarget/assets/g1_inspire/meshes/Link19_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..fe16428f9fc90f760919907916e7c5fa575c972a --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link19_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbb256a70c17e21c995df66807f0755dc136d0312df245112d6d4bfcd29c43a4 +size 407184 diff --git a/retarget/assets/g1_inspire/meshes/Link19_R.STL b/retarget/assets/g1_inspire/meshes/Link19_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..cc8afb42e7ae816abb02e6f05db3b2d11651b8d1 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link19_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46619bd6a887615d7dfe850d39a6f5d8f8c5ecfa9429c567338f3a659a5d4d75 +size 411884 diff --git a/retarget/assets/g1_inspire/meshes/Link20_L.STL b/retarget/assets/g1_inspire/meshes/Link20_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..1299f4bca88772e3b03aa7d28e8b8a1801504969 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link20_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e9145af7a515bce4c1c06d16b5be8900ec3f8375fc8e34d371315ce76f600877 +size 329484 diff --git a/retarget/assets/g1_inspire/meshes/Link20_R.STL b/retarget/assets/g1_inspire/meshes/Link20_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..cfe83e5a5b1a52a54557176e11b4d24be0b8cfa8 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link20_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a517debff6b924c22ae0f87dbb6aac199a1f130c7fef353a7d659e365f30b1f4 +size 334784 diff --git a/retarget/assets/g1_inspire/meshes/Link21_L.STL b/retarget/assets/g1_inspire/meshes/Link21_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..20bc1dd7faf8820072a205416c86218dffc33b1e --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link21_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:180ab4ac01dab60407d0b33819883eb0ec869e4d4f349f786972135c7114fc0d +size 407184 diff --git a/retarget/assets/g1_inspire/meshes/Link21_R.STL b/retarget/assets/g1_inspire/meshes/Link21_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..ae769cde24a23a79bfbbe06e4ac48783e68c5dcb --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link21_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ed0a29d2376e8874f724bc2c20384eeec93d8268e59bb8c45628335f7ab6742e +size 411884 diff --git a/retarget/assets/g1_inspire/meshes/Link22_L.STL b/retarget/assets/g1_inspire/meshes/Link22_L.STL new file mode 100644 index 0000000000000000000000000000000000000000..8ee6e22df6763466586e6c43b989b3f10fbd0f75 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link22_L.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e64ea976ecf08c46e8cb80a5dd56ee3e8c5f36a0573ab3c69160d9337f941e1 +size 413384 diff --git a/retarget/assets/g1_inspire/meshes/Link22_R.STL b/retarget/assets/g1_inspire/meshes/Link22_R.STL new file mode 100644 index 0000000000000000000000000000000000000000..9925767e505bfea1fa09a180b9b1e8d901f1699d --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/Link22_R.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1aa3fb46f689251ee38f5262b71364c680f70d1ad1dd9c6f1cae8c098b0e8422 +size 416484 diff --git a/retarget/assets/g1_inspire/meshes/R_hand_base_link.STL b/retarget/assets/g1_inspire/meshes/R_hand_base_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..042016dbf302500a0cd544d3ff51f323a3a39c20 --- /dev/null +++ b/retarget/assets/g1_inspire/meshes/R_hand_base_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4d84504242a99fa915c4ed5195ce4724c67cb94d9217cd4c254cfb5937ecf5c +size 1472384 diff --git a/retarget/assets/g1_wuji/left_hand.urdf b/retarget/assets/g1_wuji/left_hand.urdf new file mode 100644 index 0000000000000000000000000000000000000000..ea0b6e7e8f89c642bafc0ef3fbd6976c1e1be6f1 --- /dev/null +++ b/retarget/assets/g1_wuji/left_hand.urdf @@ -0,0 +1,715 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger1_link1.STL b/retarget/assets/g1_wuji/meshes/left/left_finger1_link1.STL new file mode 100644 index 0000000000000000000000000000000000000000..68f016dcaf92d557a2fedd8750e9a586b9b2a825 --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/left/left_finger1_link1.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef6226834aafe36a718c3bdedd6a8a53ac076d833f4c989c4259fe111098426e +size 389384 diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger1_link2.STL b/retarget/assets/g1_wuji/meshes/left/left_finger1_link2.STL new file mode 100644 index 0000000000000000000000000000000000000000..673ea14be8f262cf6acff5f232f944f50e4019e1 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger1_link2.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger1_link3.STL b/retarget/assets/g1_wuji/meshes/left/left_finger1_link3.STL new file mode 100644 index 0000000000000000000000000000000000000000..e561e78ff0fb36e5178dedb1725c20b6e7800fbb Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger1_link3.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger1_link4.STL b/retarget/assets/g1_wuji/meshes/left/left_finger1_link4.STL new file mode 100644 index 0000000000000000000000000000000000000000..662a217d5727276f9dca1b17508d9b3a37cddbc4 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger1_link4.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger1_tip_link.STL b/retarget/assets/g1_wuji/meshes/left/left_finger1_tip_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..de0f27e0fb250d08a48ca4a70436747068b107b3 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger1_tip_link.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger2_link1.STL b/retarget/assets/g1_wuji/meshes/left/left_finger2_link1.STL new file mode 100644 index 0000000000000000000000000000000000000000..9a4e08bcb149646a6a146f5cfba7d5b0c0a982ec Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger2_link1.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger2_link2.STL b/retarget/assets/g1_wuji/meshes/left/left_finger2_link2.STL new file mode 100644 index 0000000000000000000000000000000000000000..9cec1ad4cf14a33070f1b5d2d07cc2677f9f66fc Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger2_link2.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger2_link3.STL b/retarget/assets/g1_wuji/meshes/left/left_finger2_link3.STL new file mode 100644 index 0000000000000000000000000000000000000000..7c39fab6a012521f92fed6619addb82d1c172794 --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/left/left_finger2_link3.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:764426f6623a6809565954770980dccfe5694d7c822b3035c75e3fad14712601 +size 133184 diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger2_link4.STL b/retarget/assets/g1_wuji/meshes/left/left_finger2_link4.STL new file mode 100644 index 0000000000000000000000000000000000000000..d491293268e1bc1430d8271f415ae80bfb1d9c5c Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger2_link4.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger2_tip_link.STL b/retarget/assets/g1_wuji/meshes/left/left_finger2_tip_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..97c8a205a0cd0f5cef216c884959ad0e5c79e5ba --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/left/left_finger2_tip_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef47c5b835948311609616142247f6e764adf2fc1e060d620f64fd19efef9458 +size 112784 diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger3_link1.STL b/retarget/assets/g1_wuji/meshes/left/left_finger3_link1.STL new file mode 100644 index 0000000000000000000000000000000000000000..78c41c4ff0e3e5470aae22d2a4ebb71f7201fd6c Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger3_link1.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger3_link2.STL b/retarget/assets/g1_wuji/meshes/left/left_finger3_link2.STL new file mode 100644 index 0000000000000000000000000000000000000000..6265b862d0ea7dda91d3e0a75e1ff13c9ba1f16c Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger3_link2.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger3_link3.STL b/retarget/assets/g1_wuji/meshes/left/left_finger3_link3.STL new file mode 100644 index 0000000000000000000000000000000000000000..a0e8b93cb70d736d5909ac1c0b8d74e764fc33dd --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/left/left_finger3_link3.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:795ecf9b1fe67da36cea333d47bce7e7dc8339c058d9d6dc6dd954c93beb3ba6 +size 133184 diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger3_link4.STL b/retarget/assets/g1_wuji/meshes/left/left_finger3_link4.STL new file mode 100644 index 0000000000000000000000000000000000000000..3692ca2894c91507d8a412dbd8fec548ad5b12a2 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger3_link4.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger3_tip_link.STL b/retarget/assets/g1_wuji/meshes/left/left_finger3_tip_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..3bb469d4c08b454841f106d8914f6437ed0eebf9 --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/left/left_finger3_tip_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36b33404458a39a8e87dcc2e842f3d2679439f2a02dce37d441304060e6a235b +size 112784 diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger4_link1.STL b/retarget/assets/g1_wuji/meshes/left/left_finger4_link1.STL new file mode 100644 index 0000000000000000000000000000000000000000..5fa53c38aa35d88ab7143aeb57fa98d1de004c1f Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger4_link1.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger4_link2.STL b/retarget/assets/g1_wuji/meshes/left/left_finger4_link2.STL new file mode 100644 index 0000000000000000000000000000000000000000..a9f3ed99909fa7efc2bcda16a20ba330ac43e77a Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger4_link2.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger4_link3.STL b/retarget/assets/g1_wuji/meshes/left/left_finger4_link3.STL new file mode 100644 index 0000000000000000000000000000000000000000..ac5043ce599b98f33f3243993f9dfd6a4c7a3704 --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/left/left_finger4_link3.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18d23d11f4b8735bbc0a790a3d4493eeb0389afdbdc44665f77e4c6d604c16fb +size 133184 diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger4_link4.STL b/retarget/assets/g1_wuji/meshes/left/left_finger4_link4.STL new file mode 100644 index 0000000000000000000000000000000000000000..df3c7ad06f05d2af1a2e06e9d9b79d68b198ef1b Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger4_link4.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger4_tip_link.STL b/retarget/assets/g1_wuji/meshes/left/left_finger4_tip_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..d452e798d1cc6800f47a6f30f043f2bd3bcbdcbc --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/left/left_finger4_tip_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:67995957f5082af59a3d8745f435adc44133446b1574b7cfacf07ed02ff7aa09 +size 112784 diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger5_link1.STL b/retarget/assets/g1_wuji/meshes/left/left_finger5_link1.STL new file mode 100644 index 0000000000000000000000000000000000000000..19bdca4aab6047892828c933cdfbc25f689927ef Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger5_link1.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger5_link2.STL b/retarget/assets/g1_wuji/meshes/left/left_finger5_link2.STL new file mode 100644 index 0000000000000000000000000000000000000000..8b1c2e09a450c52c4bcd581780e9a87d6c057f33 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger5_link2.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger5_link3.STL b/retarget/assets/g1_wuji/meshes/left/left_finger5_link3.STL new file mode 100644 index 0000000000000000000000000000000000000000..c55ee38aa06664feed5b1ae2dea7fa46de4a36b2 --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/left/left_finger5_link3.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2550cb770eba8132cab3208c10b6891de17b05c051555dea79dbb9e8dac2b011 +size 133184 diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger5_link4.STL b/retarget/assets/g1_wuji/meshes/left/left_finger5_link4.STL new file mode 100644 index 0000000000000000000000000000000000000000..941d740392365d04f82ea617a60e44be88d2783e Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/left/left_finger5_link4.STL differ diff --git a/retarget/assets/g1_wuji/meshes/left/left_finger5_tip_link.STL b/retarget/assets/g1_wuji/meshes/left/left_finger5_tip_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..f54de214e8a238efeec2bf06a7822d54e4ca398f --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/left/left_finger5_tip_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6955f23515b68a893b6e1c9de7067c4852224e1cc8413211a948ec4c09dbf5aa +size 112784 diff --git a/retarget/assets/g1_wuji/meshes/left/left_palm_link.STL b/retarget/assets/g1_wuji/meshes/left/left_palm_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..3db0592df1dc9a097130d7e2a4c23b90a621a10c --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/left/left_palm_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a16d3510b49444857cc829a18202ce8bf62a129c20684190ccaedb545992298 +size 470084 diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger1_link1.STL b/retarget/assets/g1_wuji/meshes/right/right_finger1_link1.STL new file mode 100644 index 0000000000000000000000000000000000000000..bc2da1cbe88aac240bb5567848121dfead55fec6 --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/right/right_finger1_link1.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e32302a46cd00d6cc1e7fb03cc483988c639271708c2300a9aecc9de537e42b +size 366584 diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger1_link2.STL b/retarget/assets/g1_wuji/meshes/right/right_finger1_link2.STL new file mode 100644 index 0000000000000000000000000000000000000000..648a9c7c275d941ba93bc662e94c06c17eadfd4f Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger1_link2.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger1_link3.STL b/retarget/assets/g1_wuji/meshes/right/right_finger1_link3.STL new file mode 100644 index 0000000000000000000000000000000000000000..f658dd129820604729eb1c18fa2453e75e3b00d2 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger1_link3.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger1_link4.STL b/retarget/assets/g1_wuji/meshes/right/right_finger1_link4.STL new file mode 100644 index 0000000000000000000000000000000000000000..0bb3ab04c494d3d49b39d858483ca563fc077a3e Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger1_link4.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger1_tip_link.STL b/retarget/assets/g1_wuji/meshes/right/right_finger1_tip_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..273f8f16adb7abf52564aa9809923dda32a3fdf3 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger1_tip_link.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger2_link1.STL b/retarget/assets/g1_wuji/meshes/right/right_finger2_link1.STL new file mode 100644 index 0000000000000000000000000000000000000000..d9b8472dc47c7d0fb2a0899352e9ad8fce556438 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger2_link1.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger2_link2.STL b/retarget/assets/g1_wuji/meshes/right/right_finger2_link2.STL new file mode 100644 index 0000000000000000000000000000000000000000..5b0bea8093901c1100e71da3bbfa8d875d815b3c Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger2_link2.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger2_link3.STL b/retarget/assets/g1_wuji/meshes/right/right_finger2_link3.STL new file mode 100644 index 0000000000000000000000000000000000000000..11a0b215807a1f60c8ad2b1605d847603ce24134 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger2_link3.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger2_link4.STL b/retarget/assets/g1_wuji/meshes/right/right_finger2_link4.STL new file mode 100644 index 0000000000000000000000000000000000000000..64cb6c9a22c759ea5726916f4a089a3bddfbc602 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger2_link4.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger2_tip_link.STL b/retarget/assets/g1_wuji/meshes/right/right_finger2_tip_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..59e46226a3363a6b8faf4ae81793fdf809b1ca2d --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/right/right_finger2_tip_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:496039ce3f4f3fbe6bac466a01567797f741af95c6f11dc61626ec2de175900b +size 112784 diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger3_link1.STL b/retarget/assets/g1_wuji/meshes/right/right_finger3_link1.STL new file mode 100644 index 0000000000000000000000000000000000000000..6b1e76cac9c6dde7fdb9b6239b741467a9473e52 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger3_link1.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger3_link2.STL b/retarget/assets/g1_wuji/meshes/right/right_finger3_link2.STL new file mode 100644 index 0000000000000000000000000000000000000000..84082390f1c509587a31d459359de6068c4058b2 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger3_link2.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger3_link3.STL b/retarget/assets/g1_wuji/meshes/right/right_finger3_link3.STL new file mode 100644 index 0000000000000000000000000000000000000000..a69ba513df59ce22240116c3aa8e25f36301a379 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger3_link3.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger3_link4.STL b/retarget/assets/g1_wuji/meshes/right/right_finger3_link4.STL new file mode 100644 index 0000000000000000000000000000000000000000..67ca1f32cdc100da3ef322f3addf2763dfc95a45 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger3_link4.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger3_tip_link.STL b/retarget/assets/g1_wuji/meshes/right/right_finger3_tip_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..3fef1c5f6f0e12a24cfcc250ad5fe6f77d392834 --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/right/right_finger3_tip_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a99f65a6a473899913d4273e61319e3724fbf81ac8532969ed5c2ff1c1bde54 +size 112784 diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger4_link1.STL b/retarget/assets/g1_wuji/meshes/right/right_finger4_link1.STL new file mode 100644 index 0000000000000000000000000000000000000000..68db5f87ad1c5e9babfe2ad4e903c47a5ce86dff Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger4_link1.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger4_link2.STL b/retarget/assets/g1_wuji/meshes/right/right_finger4_link2.STL new file mode 100644 index 0000000000000000000000000000000000000000..d61a8317d033bce08426a0357975d28672717b76 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger4_link2.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger4_link3.STL b/retarget/assets/g1_wuji/meshes/right/right_finger4_link3.STL new file mode 100644 index 0000000000000000000000000000000000000000..1c42dbef621061a7f7524d75bd229611ef1aa95f Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger4_link3.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger4_link4.STL b/retarget/assets/g1_wuji/meshes/right/right_finger4_link4.STL new file mode 100644 index 0000000000000000000000000000000000000000..1079ae0586aa663858e1b2b4865381e207593f06 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger4_link4.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger4_tip_link.STL b/retarget/assets/g1_wuji/meshes/right/right_finger4_tip_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..623387db6c305d55525c24d99d3a946a7373dd8d --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/right/right_finger4_tip_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8b1fbee8e019afe490e820b1cba5e02c5124bb4a09aa73896bd46db6586dfde +size 113484 diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger5_link1.STL b/retarget/assets/g1_wuji/meshes/right/right_finger5_link1.STL new file mode 100644 index 0000000000000000000000000000000000000000..09c47cd7677673ee940e3d3dbb600034299e4380 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger5_link1.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger5_link2.STL b/retarget/assets/g1_wuji/meshes/right/right_finger5_link2.STL new file mode 100644 index 0000000000000000000000000000000000000000..1ac92055bc8bf48c374f61cffff32c59df0a53df Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger5_link2.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger5_link3.STL b/retarget/assets/g1_wuji/meshes/right/right_finger5_link3.STL new file mode 100644 index 0000000000000000000000000000000000000000..0f40c6bc2dce5d07e203bce8aa7b19859cd687f2 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger5_link3.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger5_link4.STL b/retarget/assets/g1_wuji/meshes/right/right_finger5_link4.STL new file mode 100644 index 0000000000000000000000000000000000000000..d40d954635d110d213215c1f8a2734b4c74c0022 Binary files /dev/null and b/retarget/assets/g1_wuji/meshes/right/right_finger5_link4.STL differ diff --git a/retarget/assets/g1_wuji/meshes/right/right_finger5_tip_link.STL b/retarget/assets/g1_wuji/meshes/right/right_finger5_tip_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..ccd435d946a9fdd98801f91da956064c36e5ad6b --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/right/right_finger5_tip_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ebbf48ca7ba3bca5f329f95277ae392d0c1a09615eda23f1bf646c5112a38cee +size 112784 diff --git a/retarget/assets/g1_wuji/meshes/right/right_palm_link.STL b/retarget/assets/g1_wuji/meshes/right/right_palm_link.STL new file mode 100644 index 0000000000000000000000000000000000000000..7a28ced65f14afb861080fbaee89cf8676861bb0 --- /dev/null +++ b/retarget/assets/g1_wuji/meshes/right/right_palm_link.STL @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ba4495e3b7adc707d50150a8625a0ed3731fa42ab6d40e62ae7437da103ce5e +size 456184 diff --git a/retarget/assets/g1_wuji/right_hand.urdf b/retarget/assets/g1_wuji/right_hand.urdf new file mode 100644 index 0000000000000000000000000000000000000000..0f64e1abd92a2d1ae3edd1ee3b73159c43894b2f --- /dev/null +++ b/retarget/assets/g1_wuji/right_hand.urdf @@ -0,0 +1,715 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/retarget/export_isaaclab.py b/retarget/export_isaaclab.py new file mode 100644 index 0000000000000000000000000000000000000000..5c60c39c087aec2c7d57c88a5d14549debf0fe09 --- /dev/null +++ b/retarget/export_isaaclab.py @@ -0,0 +1,330 @@ +#!/usr/bin/env python3 +"""Pack HaWoR MANO + G1 five-finger IK + tracked object for Isaac Lab replay. + +Writes Z-up world tensors (Isaac Lab / NVIDIA motion_v1 convention) next to +the reconstruction run: + + /obj_tracking_out/isaaclab_replay.npz + /obj_tracking_out/isaaclab_assets/object.urdf + +Quaternions in the npz are **wxyz**. Isaac Lab 3 root pose is xyz + **xyzw**; +the replay script converts. + + ./export_isaaclab.sh --video-dir ../reconstruction/runs/ +""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import sys +from pathlib import Path + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from params import DEFAULT_HAND, retarget_npz_name + +import numpy as np +from scipy.spatial.transform import Rotation as R + +# OpenCV camera (x-right, y-down, z-forward) -> Isaac / NVIDIA Z-up. +_R_CAM_TO_ZUP = np.array( + [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0]], + dtype=np.float64, +) + + +def _require_retarget_venv() -> None: + if "/reconstruction/.venv" in os.path.realpath(sys.prefix): + sys.exit("[error] use retarget/.venv: ./export_isaaclab.sh ...") + + +def _cam_to_zup_pts(p: np.ndarray) -> np.ndarray: + return np.asarray(p, dtype=np.float64) @ _R_CAM_TO_ZUP.T + + +def _cam_to_zup_rot(Rm: np.ndarray) -> np.ndarray: + return _R_CAM_TO_ZUP @ np.asarray(Rm, dtype=np.float64) + + +def _cam_to_zup_wxyz(wxyz: np.ndarray) -> np.ndarray: + Rm = _cam_to_zup_rot(R.from_quat(wxyz, scalar_first=True).as_matrix()) + return R.from_matrix(Rm).as_quat(scalar_first=True) + + +def _object_id(video_dir: Path) -> str: + cfg = video_dir / "config.json" + if cfg.is_file(): + names = json.loads(cfg.read_text()).get("object_names") or [] + if names: + return str(names[0]).replace(" ", "_") + return "object" + + +def _load_object_traj(video_dir: Path, object_id: str, n: int): + layout = ( + video_dir + / "obj_tracking_out" + / object_id + / "combined_visualization" + / "layout_camera_frame_optimized.json" + ) + if not layout.is_file(): + layout = layout.with_name("layout_camera_frame.json") + mesh_path = ( + video_dir + / "video_segmentation" + / "masks" + / "frame_000000_masks" + / object_id + / f"{object_id}.obj" + ) + pos = np.full((n, 3), np.nan) + wxyz = np.zeros((n, 4)) + wxyz[:, 0] = 1.0 + scale = 1.0 + if not layout.is_file(): + return pos, wxyz, scale, mesh_path if mesh_path.is_file() else None + data = json.loads(layout.read_text()) + tso = data.get("translation_scale_optimization") or {} + if "mesh_scale" in tso: + scale = float(tso["mesh_scale"]) + by_idx = {int(o["frame_idx"]): o for o in data.get("objects", []) if "frame_idx" in o} + last = None + for t in range(n): + obj = by_idx.get(t, last) + if obj is None: + continue + last = obj + lts = obj["local_to_scene"] + if "mesh_scale" not in tso and "scale" in lts: + scale = float(lts["scale"][0]) + if data.get("frame") == "camera_frame": + qwxyz = np.asarray(lts["quat_wxyz_camera_frame"], dtype=np.float64) + t_cam = np.asarray(lts["translation_camera_frame"], dtype=np.float64) + else: + qwxyz = np.asarray(lts["new_quat"], dtype=np.float64) + tx, ty, tz = lts["translation"] + t_cam = np.array([tz, tx, ty], dtype=np.float64) + pos[t] = _cam_to_zup_pts(t_cam) + wxyz[t] = _cam_to_zup_wxyz(qwxyz) + return pos, wxyz, scale, mesh_path if mesh_path.is_file() else None + + +def _copy_hand_urdf(src_urdf: Path, dest_dir: Path) -> Path: + dest_dir.mkdir(parents=True, exist_ok=True) + dst = dest_dir / src_urdf.name + shutil.copy2(src_urdf, dst) + src_meshes = src_urdf.parent / "meshes" + dst_meshes = dest_dir / "meshes" + if src_meshes.is_dir(): + if dst_meshes.exists(): + shutil.rmtree(dst_meshes) + shutil.copytree(src_meshes, dst_meshes) + return dst + + +def _obj_material_files(mesh_src: Path) -> list[Path]: + """Sidecar MTL + map_Kd (etc.) next to a Wavefront OBJ.""" + files: list[Path] = [] + seen: set[Path] = set() + src_dir = mesh_src.parent + obj_text = mesh_src.read_text(errors="replace") + mtl_names: list[str] = [] + for line in obj_text.splitlines(): + parts = line.strip().split() + if len(parts) >= 2 and parts[0] == "mtllib": + mtl_names.extend(parts[1:]) + if not mtl_names: + default = src_dir / "material.mtl" + if default.is_file(): + mtl_names.append(default.name) + for name in mtl_names: + mtl = (src_dir / name).resolve() + if not mtl.is_file() or mtl in seen: + continue + files.append(mtl) + seen.add(mtl) + for line in mtl.read_text(errors="replace").splitlines(): + parts = line.strip().split() + if len(parts) < 2: + continue + if parts[0] in {"map_Kd", "map_Ka", "map_Ks", "map_d", "map_Bump", "bump", "disp", "norm"}: + tex = (mtl.parent / parts[-1]).resolve() + if tex.is_file() and tex not in seen: + files.append(tex) + seen.add(tex) + for extra in src_dir.glob("material_*.png"): + p = extra.resolve() + if p not in seen: + files.append(p) + seen.add(p) + return files + + +def _write_object_urdf(mesh_src: Path, dest_dir: Path, scale: float) -> Path: + dest_dir.mkdir(parents=True, exist_ok=True) + mesh_dst = dest_dir / mesh_src.name + shutil.copy2(mesh_src, mesh_dst) + for src in _obj_material_files(mesh_src): + shutil.copy2(src, dest_dir / src.name) + urdf = dest_dir / "object.urdf" + s = float(scale) + # No URDF color: the OBJ's mtllib / map_Kd is the appearance. + urdf.write_text( + f""" + + + + + + + + + + + + + + + + +""" + ) + return urdf + + +def parse_args(): + p = argparse.ArgumentParser(description="Export G1 + object + MANO for Isaac Lab") + p.add_argument("--video-dir", required=True, type=Path) + p.add_argument("--retarget-npz", default=None) + p.add_argument( + "--hand", + default=DEFAULT_HAND, + choices=["wuji", "inspire"], + ) + p.add_argument("--hand-meshes", default=None) + p.add_argument("--fps", type=float, default=30.0) + p.add_argument("--output", default=None) + return p.parse_args() + + +def main(): + _require_retarget_venv() + args = parse_args() + video_dir = args.video_dir.resolve() + retarget_npz = Path(args.retarget_npz) if args.retarget_npz else ( + video_dir / "obj_tracking_out" / retarget_npz_name(args.hand) + ) + if not retarget_npz.is_file() and args.retarget_npz is None: + alt = video_dir / "obj_tracking_out" / retarget_npz_name( + "inspire" if args.hand == "wuji" else "wuji" + ) + if alt.is_file(): + retarget_npz = alt + if not retarget_npz.is_file(): + sys.exit(f"[error] missing {retarget_npz} (run hawor_to_g1 first)") + hawor = Path(args.hand_meshes) if args.hand_meshes else video_dir / "clip" / "all_hand_meshes.npz" + if not hawor.is_file(): + sys.exit(f"[error] missing {hawor}") + out = Path(args.output) if args.output else ( + video_dir / "obj_tracking_out" / "isaaclab_replay.npz" + ) + assets = out.parent / "isaaclab_assets" + + rt = np.load(retarget_npz, allow_pickle=True) + hand_kind = str(rt["hand"]) if "hand" in rt.files else args.hand + hm = np.load(hawor) + hands = [str(x) for x in np.atleast_1d(rt["hands"]).tolist()] + side = hands[0] + q = np.asarray(rt[f"{side}_q"], dtype=np.float64) + n = q.shape[0] + names = np.asarray(rt[f"{side}_joint_names"]) + + root_pos = np.full((n, 3), np.nan) + root_wxyz = np.zeros((n, 4)) + root_wxyz[:, 0] = 1.0 + finger_q = np.full((n, q.shape[1] - 7), np.nan) + last = None + for t in range(n): + if not np.isfinite(q[t]).all(): + if last is None: + continue + root_pos[t] = root_pos[last] + root_wxyz[t] = root_wxyz[last] + finger_q[t] = finger_q[last] + continue + xyzw = q[t, 3:7] + wxyz = np.array([xyzw[3], xyzw[0], xyzw[1], xyzw[2]]) + root_pos[t] = _cam_to_zup_pts(q[t, :3]) + root_wxyz[t] = _cam_to_zup_wxyz(wxyz) + finger_q[t] = q[t, 7:] + last = t + + obj_id = _object_id(video_dir) + obj_pos, obj_wxyz, obj_scale, mesh_path = _load_object_traj(video_dir, obj_id, n) + obj_urdf = "" + if mesh_path is not None: + obj_urdf = str(_write_object_urdf(mesh_path, assets, obj_scale)) + + mano_joints = _cam_to_zup_pts(np.asarray(hm[f"{side}_joints"], dtype=np.float64)) + mano_verts = _cam_to_zup_pts(np.asarray(hm[f"{side}_vertices"], dtype=np.float64)) + mano_faces = np.asarray(hm[f"{side}_faces"]) + + pts = [root_pos[np.isfinite(root_pos).all(axis=1)]] + if np.isfinite(obj_pos).any(): + pts.append(obj_pos[np.isfinite(obj_pos).all(axis=1)]) + zmin = float(np.concatenate(pts, axis=0)[:, 2].min()) if pts and len(pts[0]) else 0.0 + lift = 0.05 - zmin + root_pos[:, 2] += lift + obj_pos[:, 2] += lift + mano_joints[:, :, 2] += lift + mano_verts[:, :, 2] += lift + + if hand_kind == "wuji": + src_hand = ( + Path(__file__).resolve().parent / "assets" / "g1_wuji" / f"{side}_hand.urdf" + ) + dest_sub = "g1_wuji" + else: + src_hand = ( + Path(__file__).resolve().parent / "assets" / "g1_inspire" / f"DFQ_{side}_hand.urdf" + ) + dest_sub = "g1_inspire" + if not src_hand.is_file(): + sys.exit(f"[error] missing {src_hand}") + hand_urdf = str(_copy_hand_urdf(src_hand, assets / dest_sub)) + np.savez_compressed( + out, + fps=np.float64(args.fps), + side=np.array(side), + coord_frame=np.array("zup"), + lift=np.float64(lift), + object_id=np.array(obj_id), + object_scale=np.float64(obj_scale), + object_urdf=np.array(obj_urdf), + object_pos=obj_pos, + object_wxyz=obj_wxyz, + hand_urdf=np.array(hand_urdf), + root_pos=root_pos, + root_wxyz=root_wxyz, + finger_joint_names=names, + finger_q=finger_q, + mano_joints=mano_joints, + mano_vertices=mano_verts, + mano_faces=mano_faces, + source_retarget=np.array(str(retarget_npz)), + source_hawor=np.array(str(hawor)), + robot_hand=np.array(hand_kind), + ) + print(f"wrote {out}", flush=True) + print(f" T={n} side={side} lift={lift:.3f} m object={obj_id}", flush=True) + if obj_urdf: + print(f" object urdf {obj_urdf}", flush=True) + print(f" hand urdf {hand_urdf}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/retarget/export_isaaclab.sh b/retarget/export_isaaclab.sh new file mode 100644 index 0000000000000000000000000000000000000000..207fe5163faeb5368afc0826dec23a47cc4d72cb --- /dev/null +++ b/retarget/export_isaaclab.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PY="$ROOT/.venv/bin/python" +if [[ ! -x "$PY" ]]; then + echo "retarget venv missing. Run: $ROOT/setup.sh" >&2 + exit 1 +fi +exec "$PY" "$ROOT/export_isaaclab.py" "$@" diff --git a/retarget/extract_wuji_hand_urdf.py b/retarget/extract_wuji_hand_urdf.py new file mode 100644 index 0000000000000000000000000000000000000000..13ec605dc58e63bce4742794f6fb21a38fcd9da2 --- /dev/null +++ b/retarget/extract_wuji_hand_urdf.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Slice left/right Wuji hands out of CoordEx's full G1 URDF for Pink IK. + +Pinocchio retarget needs a free-flyer hand, not the 29-DoF body. The source is +``third-party/coordex/.../g1_wuji.urdf``; we keep every descendant of +``{left,right}_palm_link`` and copy the matching STLs. +""" + +from __future__ import annotations + +import copy +import shutil +import xml.etree.ElementTree as ET +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +SRC_URDF = ( + ROOT.parents[0] + / "third-party" + / "coordex" + / "source" + / "coordex" + / "coordex" + / "assets" + / "g1_wuji" + / "g1_wuji.urdf" +) +SRC_MESH = SRC_URDF.parent / "meshes" +DST = ROOT / "assets" / "g1_wuji" + + +def _name(el: ET.Element) -> str: + n = el.get("name") + if n: + return n + child = el.find("name") + return (child.text or "").strip() if child is not None else "" + + +def _attr_or_child(el: ET.Element, tag: str) -> str: + v = el.get(tag) + if v: + return v + child = el.find(tag) + if child is None: + return "" + if child.get("link"): + return child.get("link") + return (child.text or "").strip() + + +def _mesh_files(el: ET.Element) -> list[str]: + out = [] + for mesh in el.iter("mesh"): + fn = mesh.get("filename") + if fn: + out.append(fn) + return out + + +def extract_side(tree: ET.Element, side: str) -> tuple[ET.Element, set[str]]: + root_link = f"{side}_palm_link" + joints = list(tree.findall("joint")) + links = {el.get("name"): el for el in tree.findall("link") if el.get("name")} + + children: dict[str, list[ET.Element]] = {} + for j in joints: + parent = _attr_or_child(j, "parent") + children.setdefault(parent, []).append(j) + + keep_links = {root_link} + keep_joints: list[ET.Element] = [] + stack = [root_link] + while stack: + cur = stack.pop() + for j in children.get(cur, []): + child = _attr_or_child(j, "child") + keep_joints.append(j) + if child and child not in keep_links: + keep_links.add(child) + stack.append(child) + + robot = ET.Element("robot", {"name": f"g1_wuji_{side}_hand"}) + meshes: set[str] = set() + for name in sorted(keep_links): + el = copy.deepcopy(links[name]) + robot.append(el) + meshes.update(_mesh_files(el)) + for j in keep_joints: + el = copy.deepcopy(j) + robot.append(el) + meshes.update(_mesh_files(el)) + return robot, meshes + + +def main() -> None: + if not SRC_URDF.is_file(): + raise SystemExit(f"missing {SRC_URDF}") + tree = ET.parse(SRC_URDF).getroot() + DST.mkdir(parents=True, exist_ok=True) + for side in ("left", "right"): + robot, meshes = extract_side(tree, side) + ET.indent(robot, space=" ") + out = DST / f"{side}_hand.urdf" + ET.ElementTree(robot).write(out, encoding="unicode", xml_declaration=True) + for rel in meshes: + src = SRC_URDF.parent / rel + dst = DST / rel + dst.parent.mkdir(parents=True, exist_ok=True) + if src.is_file(): + shutil.copy2(src, dst) + else: + print(f" warn missing mesh {src}") + print(f"wrote {out} meshes={len(meshes)}") + + +if __name__ == "__main__": + main() diff --git a/retarget/fetch_inspire_meshes.sh b/retarget/fetch_inspire_meshes.sh new file mode 100644 index 0000000000000000000000000000000000000000..b988c635e31d9ccd5e0aaad1ff326523d47f5b64 --- /dev/null +++ b/retarget/fetch_inspire_meshes.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# Download Inspire DFQ STLs into assets/g1_inspire/meshes/ (unitree_ros). +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +MESH_DIR="$ROOT/assets/g1_inspire/meshes" +BASE="https://raw.githubusercontent.com/unitreerobotics/unitree_ros/master/robots/g1_description/meshes" +mkdir -p "$MESH_DIR" +while IFS= read -r name; do + [[ -z "$name" ]] && continue + dest="$MESH_DIR/$name" + if [[ -f "$dest" ]]; then + continue + fi + echo "fetch $name" + curl -fsSL -o "$dest" "$BASE/$name" +done <<'EOF' +L_hand_base_link.STL +R_hand_base_link.STL +Link11_L.STL +Link11_R.STL +Link12_L.STL +Link12_R.STL +Link13_L.STL +Link13_R.STL +Link14_L.STL +Link14_R.STL +Link15_L.STL +Link15_R.STL +Link16_L.STL +Link16_R.STL +Link17_L.STL +Link17_R.STL +Link18_L.STL +Link18_R.STL +Link19_L.STL +Link19_R.STL +Link20_L.STL +Link20_R.STL +Link21_L.STL +Link21_R.STL +Link22_L.STL +Link22_R.STL +EOF +echo "[ok] meshes in $MESH_DIR" diff --git a/retarget/hand_kinematics.py b/retarget/hand_kinematics.py new file mode 100644 index 0000000000000000000000000000000000000000..6c932f29e15b03d241a518713abf8acc26016009 --- /dev/null +++ b/retarget/hand_kinematics.py @@ -0,0 +1,421 @@ +"""Pink IK from MANO 21 joints onto a Unitree G1 five-finger URDF. + +Pattern follows NVIDIA `robotic_grounding.retarget.hand_kinematics.Dex3HandKinematics` +(third-party/video_to_data). Default embodiment is **Wuji** (the play robot); +Inspire DFQ remains available as ``hand="inspire"``. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Literal, Optional + +import numpy as np +import pinocchio as pin +from scipy.spatial.transform import Rotation as R + +from params import ( + G1_INSPIRE_TO_MANO_MAPPING, + G1_WUJI_TO_MANO_MAPPING, + MANO_JOINTS_ORDER, + MANO_MCP_JOINTS, +) + +RETARGET_ROOT = Path(__file__).resolve().parent +INSPIRE_ASSETS = RETARGET_ROOT / "assets" / "g1_inspire" +WUJI_ASSETS = RETARGET_ROOT / "assets" / "g1_wuji" + +HandKind = Literal["inspire", "wuji"] + + +@dataclass(frozen=True) +class _HandSpec: + kind: str + assets: Path + urdf_name: str + palm_link: str + mapping: dict[str, tuple[str, float, float]] + mcp_links: tuple[str, ...] + index_mcp: str + pinky_mcp: str + attach_tips: bool + inspire_last_links: dict[str, str] | None = None + + +def _inspire_spec(side: Literal["right", "left"]) -> _HandSpec: + p = "R" if side == "right" else "L" + return _HandSpec( + kind="inspire", + assets=INSPIRE_ASSETS, + urdf_name=f"DFQ_{side}_hand.urdf", + palm_link=f"{p}_hand_base_link", + mapping={k.replace(".*", p): v for k, v in G1_INSPIRE_TO_MANO_MAPPING.items()}, + mcp_links=tuple(f"{p}_{f}_proximal" for f in ("index", "middle", "ring", "pinky")), + index_mcp=f"{p}_index_proximal", + pinky_mcp=f"{p}_pinky_proximal", + attach_tips=True, + inspire_last_links={ + "thumb": f"{p}_thumb_distal", + "index": f"{p}_index_intermediate", + "middle": f"{p}_middle_intermediate", + "ring": f"{p}_ring_intermediate", + "pinky": f"{p}_pinky_intermediate", + }, + ) + + +def _wuji_spec(side: Literal["right", "left"]) -> _HandSpec: + return _HandSpec( + kind="wuji", + assets=WUJI_ASSETS, + urdf_name=f"{side}_hand.urdf", + palm_link=f"{side}_palm_link", + mapping={k.replace("{side}", side): v for k, v in G1_WUJI_TO_MANO_MAPPING.items()}, + mcp_links=tuple(f"{side}_finger{i}_link1" for i in range(2, 6)), + index_mcp=f"{side}_finger2_link1", + pinky_mcp=f"{side}_finger5_link1", + attach_tips=False, + ) + + +def hand_spec(hand: HandKind, side: Literal["right", "left"]) -> _HandSpec: + if hand == "wuji": + return _wuji_spec(side) + if hand == "inspire": + return _inspire_spec(side) + raise ValueError(f"unknown hand {hand!r}") + + +class _Robot: + def __init__(self, model: pin.Model): + self.model = model + self.data = model.createData() + self.q0 = pin.neutral(model) + self.visual_model = None + self.visual_data = None + self.collision_model = None + + +class G1HandKinematics: + def __init__( + self, + side: Literal["right", "left"], + hand: HandKind = "wuji", + robot_asset_path: Optional[str] = None, + solver: str = "daqp", + max_iter: int = 120, + frequency: float = 100.0, + frame_tasks_converged_threshold: float = 1e-5, + ) -> None: + import pink + from loop_rate_limiters import RateLimiter + from pink.limits import ConfigurationLimit, VelocityLimit + from pink.tasks import FrameTask + from pink import solve_ik + + self._pink = pink + self._solve_ik = solve_ik + self._FrameTask = FrameTask + + self.side = side + self.hand = hand + self.spec = hand_spec(hand, side) + self.prefix = "R" if side == "right" else "L" + default = self.spec.assets / self.spec.urdf_name + self.robot_asset_path = str(robot_asset_path or default) + if not Path(self.robot_asset_path).is_file(): + extra = "" + if hand == "wuji": + extra = "; run retarget/extract_wuji_hand_urdf.py first" + raise FileNotFoundError(f"{self.robot_asset_path} not found{extra}") + self.solver = solver + self.max_iter = max_iter + self.frame_tasks_converged_threshold = frame_tasks_converged_threshold + + self.robot = self._load_model() + self._palm_axes_in_base = self._measure_palm_axes() + self.configuration_limits = [ + ConfigurationLimit(self.robot.model), + VelocityLimit(self.robot.model), + ] + self.configuration = pink.Configuration( + self.robot.model, self.robot.data, self.robot.q0 + ) + self.dt = RateLimiter(frequency=frequency, warn=False).period + self.source_joint_order = MANO_JOINTS_ORDER + self.target_to_source = dict(self.spec.mapping) + missing = [n for n in self.target_to_source if not self.robot.model.existFrame(n)] + if missing: + raise RuntimeError( + f"URDF missing frames {missing}. Available sample: " + f"{[f.name for f in self.robot.model.frames[:30]]}" + ) + self.frame_tasks = {} + for name, (_, pos_c, ori_c) in self.target_to_source.items(): + task = FrameTask( + name, position_cost=pos_c, orientation_cost=ori_c, lm_damping=1.0 + ) + task.set_target_from_configuration(self.configuration) + self.frame_tasks[name] = task + + self.robot_finger_joint_names = [] + for i, name in enumerate(self.robot.model.names): + if i == 0: + continue + if "universe" in name or "root" in name.lower() or "fly" in name.lower(): + continue + self.robot_finger_joint_names.append(name) + + def _load_model(self) -> _Robot: + model = pin.buildModelFromUrdf( + self.robot_asset_path, pin.JointModelFreeFlyer() + ) + robot = _Robot(model) + mesh_dir = self.spec.assets / "meshes" + if mesh_dir.is_dir() and any(mesh_dir.rglob("*.STL")): + robot.visual_model = pin.buildGeomFromUrdf( + model, + self.robot_asset_path, + pin.GeometryType.VISUAL, + package_dirs=[str(self.spec.assets)], + ) + robot.visual_data = pin.GeometryData(robot.visual_model) + self._add_ik_frames(robot) + robot.data = robot.model.createData() + if robot.visual_model is not None: + robot.visual_data = pin.GeometryData(robot.visual_model) + return robot + + def _add_ik_frames(self, robot: _Robot) -> None: + """Palm at MCP centroid; Inspire also adds tip frames on last-link meshes.""" + spec = self.spec + model = robot.model + data = robot.data + pin.forwardKinematics(model, data, robot.q0) + pin.updateFramePlacements(model, data) + + oMb = data.oMf[model.getFrameId(spec.palm_link)] + mcp = [] + for name in spec.mcp_links: + fid = model.getFrameId(name) + mcp.append(np.asarray(oMb.actInv(data.oMf[fid].translation))) + palm_off = np.mean(np.stack(mcp, axis=0), axis=0) + self._attach_op_frame(model, data, spec.palm_link, f"{self.side}_palm_ik" if spec.kind == "wuji" else f"{self.prefix}_palm_ik", palm_off) + + if not spec.attach_tips or not spec.inspire_last_links: + return + p = self.prefix + for finger, link in spec.inspire_last_links.items(): + offset = np.array([0.0, 0.035, 0.0]) + if robot.visual_model is not None: + offset = self._mesh_far_vertex(robot, link) + self._attach_op_frame(model, data, link, f"{p}_{finger}_tip", offset) + + def _attach_op_frame( + self, + model: pin.Model, + data: pin.Data, + parent_link: str, + name: str, + offset_in_link: np.ndarray, + ) -> None: + # Pinocchio Frame.placement is relative to parentJoint, which for the + # Inspire palm is the free-flyer (fixed wrist→palm joint is merged). + parent_id = model.getFrameId(parent_link) + parent = model.frames[parent_id] + local = pin.SE3(np.eye(3), np.asarray(offset_in_link, dtype=np.float64)) + placement = data.oMi[parent.parentJoint].inverse() * data.oMf[parent_id] * local + model.addFrame( + pin.Frame(name, parent.parentJoint, parent_id, placement, pin.FrameType.OP_FRAME) + ) + + def _mesh_far_vertex(self, robot: _Robot, link_name: str) -> np.ndarray: + import trimesh + + link_id = robot.model.getFrameId(link_name) + parent_j = robot.model.frames[link_id].parentJoint + oMl = robot.data.oMf[link_id] + best = np.array([0.0, 0.035, 0.0]) + best_dot = -1e9 + for geom in robot.visual_model.geometryObjects: + if geom.parentJoint != parent_j: + continue + path = geom.meshPath + if not path: + continue + tm = trimesh.load(path, force="mesh") + if isinstance(tm, trimesh.Scene): + tm = tm.dump(concatenate=True) + if not isinstance(tm, trimesh.Trimesh) or len(tm.vertices) == 0: + continue + verts = np.asarray(tm.vertices, dtype=np.float64) * np.asarray(geom.meshScale).reshape(3) + M = geom.placement + oMj = robot.data.oMi[geom.parentJoint] + verts_link = [] + for v in verts: + verts_link.append(np.asarray(oMl.actInv(oMj.act(M.act(v))))) + verts_link = np.stack(verts_link, axis=0) + mean = verts_link.mean(axis=0) + axis = mean / max(float(np.linalg.norm(mean)), 1e-9) + dots = verts_link @ axis + i = int(np.argmax(dots)) + if float(dots[i]) > best_dot: + best_dot = float(dots[i]) + best = verts_link[i] + return best + + def _measure_palm_axes(self) -> np.ndarray: + """Columns: anatomy (forward, to_pinky, normal) in palm coordinates.""" + spec = self.spec + model, data, q0 = self.robot.model, self.robot.data, self.robot.q0 + pin.forwardKinematics(model, data, q0) + pin.updateFramePlacements(model, data) + oMb = data.oMf[model.getFrameId(spec.palm_link)] + + def in_base(name: str) -> np.ndarray: + return np.asarray(oMb.actInv(data.oMf[model.getFrameId(name)].translation)) + + idx = in_base(spec.index_mcp) + pky = in_base(spec.pinky_mcp) + mcp = np.mean(np.stack([in_base(n) for n in spec.mcp_links], axis=0), axis=0) + forward = mcp / max(np.linalg.norm(mcp), 1e-9) + to_pinky = pky - idx + to_pinky = to_pinky - forward * float(np.dot(to_pinky, forward)) + to_pinky = to_pinky / max(np.linalg.norm(to_pinky), 1e-9) + normal = np.cross(forward, to_pinky) + normal = normal / max(np.linalg.norm(normal), 1e-9) + to_pinky = np.cross(normal, forward) + return np.column_stack([forward, to_pinky, normal]) + + @staticmethod + def _anatomy_axes(joints: np.ndarray) -> np.ndarray: + wrist = np.asarray(joints[0], dtype=np.float64) + mcp_idx = [MANO_JOINTS_ORDER.index(n) for n in MANO_MCP_JOINTS] + mcp = np.mean(np.asarray(joints)[mcp_idx], axis=0) + forward = mcp - wrist + forward = forward / max(np.linalg.norm(forward), 1e-9) + index1 = np.asarray(joints[MANO_JOINTS_ORDER.index("index1")]) + pinky1 = np.asarray(joints[MANO_JOINTS_ORDER.index("pinky1")]) + to_pinky = pinky1 - index1 + to_pinky = to_pinky - forward * float(np.dot(to_pinky, forward)) + to_pinky = to_pinky / max(np.linalg.norm(to_pinky), 1e-9) + normal = np.cross(forward, to_pinky) + normal = normal / max(np.linalg.norm(normal), 1e-9) + to_pinky = np.cross(normal, forward) + return np.column_stack([forward, to_pinky, normal]) + + def palm_world_rotation(self, source_joints: np.ndarray) -> np.ndarray: + """hand_base rotation in world so robot anatomy matches MANO anatomy.""" + R_world_anatomy = self._anatomy_axes(source_joints) + R_base_anatomy = self._palm_axes_in_base + return R_world_anatomy @ R_base_anatomy.T + + def seed_q(self, source_joints: np.ndarray) -> np.ndarray: + """Place the free-flyer so palm_ik sits on the MANO MCP centroid.""" + q = self.robot.q0.copy() + R_wb = self.palm_world_rotation(source_joints) + pin.forwardKinematics(self.robot.model, self.robot.data, q) + pin.updateFramePlacements(self.robot.model, self.robot.data) + oMroot = self.robot.data.oMi[1] + palm_id = self.robot.model.getFrameId( + f"{self.side}_palm_ik" if self.spec.kind == "wuji" else f"{self.prefix}_palm_ik" + ) + p_palm = np.asarray(self.robot.data.oMf[palm_id].translation) + p_root = np.asarray(oMroot.translation) + R_root = np.asarray(oMroot.rotation) + palm_in_root = R_root.T @ (p_palm - p_root) + # current root rot is identity at q0; desired root rot from hand_base. + base_id = self.robot.model.getFrameId(self.spec.palm_link) + R_root_base = np.asarray(self.robot.data.oMf[base_id].rotation) + R_world_root = R_wb @ R_root_base.T + mcp_idx = [MANO_JOINTS_ORDER.index(n) for n in MANO_MCP_JOINTS] + target = np.mean(np.asarray(source_joints)[mcp_idx], axis=0) + q[:3] = target - R_world_root @ palm_in_root + q[3:7] = R.from_matrix(R_world_root).as_quat() + return q + + def set_frame_tasks_target( + self, + source_joints: np.ndarray, + source_joints_wxyz: np.ndarray, + source_to_robot_scale: float = 1.0, + ) -> None: + source_joints = np.asarray(source_joints, dtype=np.float64) + base_pos = source_joints[self.source_joint_order.index("wrist")] + mcp_idx = [self.source_joint_order.index(n) for n in MANO_MCP_JOINTS] + mcp_pos = np.mean(source_joints[mcp_idx], axis=0) + palm_rot = self.palm_world_rotation(source_joints) + for frame_name, (src_name, _, _) in self.target_to_source.items(): + if src_name == "mcp_centroid": + target_pos = base_pos + (mcp_pos - base_pos) * source_to_robot_scale + target_rot = palm_rot + else: + idx = self.source_joint_order.index(src_name) + target_pos = source_joints[idx] + target_pos = base_pos + (target_pos - base_pos) * source_to_robot_scale + wxyz = np.asarray(source_joints_wxyz[idx], dtype=np.float64) + target_rot = R.from_quat(wxyz, scalar_first=True).as_matrix() + self.frame_tasks[frame_name].transform_target_to_world.translation = ( + target_pos.copy() + ) + self.frame_tasks[frame_name].transform_target_to_world.rotation = ( + target_rot.copy() + ) + + def compute( + self, + source_joints: np.ndarray, + source_joints_wxyz: np.ndarray, + source_to_robot_scale: float = 1.0, + qpos: Optional[np.ndarray] = None, + ) -> dict[str, Any]: + self.set_frame_tasks_target( + source_joints, source_joints_wxyz, source_to_robot_scale + ) + tasks = list(self.frame_tasks.values()) + self.configuration.q = ( + self.robot.q0.copy() if qpos is None else np.asarray(qpos, dtype=np.float64).copy() + ) + last_err = {k: np.inf for k in self.frame_tasks} + n_iter = 0 + for _ in range(self.max_iter): + vel = self._solve_ik( + configuration=self.configuration, + tasks=tasks, + dt=self.dt, + solver=self.solver, + safety_break=False, + limits=self.configuration_limits, + ) + self.configuration.integrate_inplace(vel, self.dt) + n_iter += 1 + done = True + for name, task in self.frame_tasks.items(): + err = float(np.linalg.norm(np.asarray(task.compute_error(self.configuration))[:3])) + if abs(err - last_err[name]) >= self.frame_tasks_converged_threshold: + done = False + last_err[name] = err + if done: + break + return { + "q": self.configuration.q.copy(), + "frame_task_errors": [last_err[k] for k in self.frame_tasks], + "num_optimization_iterations": n_iter, + } + + +class G1InspireHandKinematics(G1HandKinematics): + """Back-compat alias: MANO → Inspire DFQ.""" + + def __init__(self, side: Literal["right", "left"], **kwargs: Any) -> None: + kwargs.setdefault("hand", "inspire") + super().__init__(side, **kwargs) + + +def make_hand_kinematics( + side: Literal["right", "left"], + hand: HandKind = "wuji", + **kwargs: Any, +) -> G1HandKinematics: + return G1HandKinematics(side, hand=hand, **kwargs) diff --git a/retarget/hawor_to_g1.py b/retarget/hawor_to_g1.py new file mode 100644 index 0000000000000000000000000000000000000000..0d0db42c500db93344ded8732e8036d631db26e9 --- /dev/null +++ b/retarget/hawor_to_g1.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Retarget HaWoR MANO hands to a Unitree G1 five-finger URDF (Wuji by default). + +Reads reconstruction `clip/all_hand_meshes.npz` (joints + MANO global rot) +and runs Pink IK like NVIDIA Dex3 (`arctic_to_dex3.py`), with ring+pinky +targets. Use `--hand inspire` for the older Inspire DFQ mapping. + + python hawor_to_g1.py --video-dir ../reconstruction/runs/ --hands right +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import numpy as np +from scipy.spatial.transform import Rotation as R + +from hand_kinematics import make_hand_kinematics +from params import DEFAULT_HAND, retarget_npz_name + + +def _require_retarget_venv() -> None: + prefix = os.path.realpath(sys.prefix) + if "/reconstruction/.venv" in prefix: + print( + "[error] this script must use retarget/.venv, not reconstruction/.venv " + "(Pinocchio would upgrade numpy and break SAM3).\n" + " cd retarget && ./setup.sh && ./hawor_to_g1.sh --video-dir ...", + file=sys.stderr, + ) + sys.exit(1) + + +def _find_npz(video_dir: Path, explicit: str | None) -> Path: + if explicit: + p = Path(explicit) + if not p.is_file(): + sys.exit(f"[error] --hand-meshes not found: {p}") + return p + clip = video_dir / "clip" / "all_hand_meshes.npz" + if clip.is_file(): + return clip + for child in video_dir.iterdir(): + cand = child / "all_hand_meshes.npz" + if cand.is_file(): + return cand + sys.exit(f"[error] no all_hand_meshes.npz under {video_dir}") + + +def _anchor_hand(video_dir: Path) -> str: + cfg = video_dir / "config.json" + if cfg.is_file(): + h = json.loads(cfg.read_text()).get("anchor_hand") + if h in ("left", "right"): + return h + return "right" + + +def _aa_to_wxyz(aa: np.ndarray) -> np.ndarray: + aa = np.asarray(aa, dtype=np.float64).reshape(3) + return R.from_rotvec(aa).as_quat(scalar_first=True) + + +def _mano_wxyz(n: int, wrist_wxyz: np.ndarray) -> np.ndarray: + out = np.zeros((n, 4), dtype=np.float64) + out[:, 0] = 1.0 + out[0] = wrist_wxyz + return out + + +def _depth_ok(verts: np.ndarray, min_median_z: float = 0.15) -> bool: + z = np.asarray(verts)[:, 2] + return bool(np.isfinite(z).all() and float(np.median(z)) >= min_median_z) + + +def parse_args() -> argparse.Namespace: + p = argparse.ArgumentParser( + description="HaWoR MANO → Unitree G1 five-finger IK (Wuji default)", + ) + p.add_argument("--video-dir", required=True, type=Path) + p.add_argument("--hand-meshes", default=None) + p.add_argument( + "--hand", + default=DEFAULT_HAND, + choices=["wuji", "inspire"], + help="Robot hand URDF to IK onto. Simulation play uses wuji.", + ) + p.add_argument( + "--hands", + default="auto", + choices=["auto", "right", "left", "both"], + ) + p.add_argument("--mano-to-robot-scale", type=float, default=1.0) + p.add_argument("--max-iter", type=int, default=120) + p.add_argument( + "--output", + default=None, + help="Output npz (default: /obj_tracking_out/g1__retarget.npz)", + ) + return p.parse_args() + + +def main() -> None: + _require_retarget_venv() + args = parse_args() + video_dir = args.video_dir.resolve() + npz_path = _find_npz(video_dir, args.hand_meshes) + data = np.load(npz_path) + hands = [_anchor_hand(video_dir)] if args.hands == "auto" else ( + ["left", "right"] if args.hands == "both" else [args.hands] + ) + out_path = Path(args.output) if args.output else ( + video_dir / "obj_tracking_out" / retarget_npz_name(args.hand) + ) + out_path.parent.mkdir(parents=True, exist_ok=True) + + print(f"input: {npz_path}", flush=True) + print(f"hand: {args.hand}", flush=True) + print(f"hands: {hands}", flush=True) + print(f"output: {out_path}", flush=True) + + payload: dict = { + "source_npz": str(npz_path), + "mano_to_robot_scale": np.float64(args.mano_to_robot_scale), + "hands": np.array(hands), + "hand": np.array(args.hand), + } + + for side in hands: + kin = make_hand_kinematics(side=side, hand=args.hand, max_iter=args.max_iter) + joints = np.asarray(data[f"{side}_joints"], dtype=np.float64) + rots = np.asarray(data[f"{side}_rot"], dtype=np.float64) + verts = np.asarray(data[f"{side}_vertices"], dtype=np.float64) + n = joints.shape[0] + qs = [] + errs = [] + q_prev = None + nq = kin.robot.q0.shape[0] + for t in range(n): + if not _depth_ok(verts[t]): + qs.append(np.full(nq, np.nan)) + errs.append(np.nan) + q_prev = None + continue + wxyz = _mano_wxyz(21, _aa_to_wxyz(rots[t])) + if q_prev is None: + q = kin.seed_q(joints[t]) + else: + q = q_prev + res = kin.compute( + joints[t], + wxyz, + source_to_robot_scale=args.mano_to_robot_scale, + qpos=q, + ) + q_prev = res["q"] + qs.append(res["q"]) + errs.append(float(np.mean(res["frame_task_errors"]))) + if t % 10 == 0: + named = ", ".join( + f"{k.split('_',1)[-1]}={e*100:.1f}cm" + for k, e in zip(kin.frame_tasks, res["frame_task_errors"]) + ) + print( + f" {side} frame {t}/{n} mean={errs[-1]*100:.1f}cm {named} iters={res['num_optimization_iterations']}", + flush=True, + ) + payload[f"{side}_q"] = np.stack(qs, axis=0) + payload[f"{side}_tip_err"] = np.asarray(errs) + payload[f"{side}_joint_names"] = np.array(kin.robot_finger_joint_names) + + np.savez_compressed(out_path, **payload) + print(f"wrote {out_path}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/retarget/hawor_to_g1.sh b/retarget/hawor_to_g1.sh new file mode 100644 index 0000000000000000000000000000000000000000..d76ce531a0c0c9d1ea2d6661cdfefddd38ed2cdd --- /dev/null +++ b/retarget/hawor_to_g1.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# Run HaWoR → G1 five-finger IK with retarget/.venv only. +# Default embodiment is Wuji (--hand wuji). Pass --hand inspire for DFQ. +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PY="$ROOT/.venv/bin/python" +if [[ ! -x "$PY" ]]; then + echo "retarget venv missing. Run: $ROOT/setup.sh" >&2 + exit 1 +fi +exec "$PY" "$ROOT/hawor_to_g1.py" "$@" diff --git a/retarget/params.py b/retarget/params.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e2edab2cf5d985fe778493281450c44ac56963 --- /dev/null +++ b/retarget/params.py @@ -0,0 +1,72 @@ +"""MANO and Unitree G1 five-finger IK maps (Inspire DFQ and Wuji). + +Dex3 in NVIDIA robotic_grounding only has thumb/index/middle. Both Inspire and +Wuji add ring + pinky; the fingertip frames differ by USD. +""" + +MANO_JOINTS_ORDER = [ + "wrist", + "thumb1", + "thumb2", + "thumb3", + "thumb4", + "index1", + "index2", + "index3", + "index4", + "middle1", + "middle2", + "middle3", + "middle4", + "ring1", + "ring2", + "ring3", + "ring4", + "pinky1", + "pinky2", + "pinky3", + "pinky4", +] + +MANO_JOINTS_PARENTS = [ + -1, + 0, 1, 2, 3, + 0, 5, 6, 7, + 0, 9, 10, 11, + 0, 13, 14, 15, + 0, 17, 18, 19, +] + +# Operational frames added in hand_kinematics (not raw CAD origins). +# Dex3 maps palm_link origin ≈ MANO wrist. Inspire `*_hand_base_link` origin is +# a CAD point ~14cm from the finger MCPs, so we IK `*_palm_ik` (MCP centroid) +# and `*_…_tip` (mesh far vertex), not the link origins. +# `.*` is replaced with L or R. +G1_INSPIRE_TO_MANO_MAPPING = { + ".*_palm_ik": ("mcp_centroid", 1.0, 0.25), + ".*_thumb_tip": ("thumb4", 1.0, 0.0), + ".*_index_tip": ("index4", 1.0, 0.0), + ".*_middle_tip": ("middle4", 1.0, 0.0), + ".*_ring_tip": ("ring4", 1.0, 0.0), + ".*_pinky_tip": ("pinky4", 1.0, 0.0), +} + +# Wuji: finger1 is the thumb (CoordEx `RIGHT_HAND_TIP_NAMES[0]`), then index→pinky. +# `{side}` is replaced with left or right. Tip links already exist in the URDF. +G1_WUJI_TO_MANO_MAPPING = { + "{side}_palm_ik": ("mcp_centroid", 1.0, 0.25), + "{side}_finger1_tip_link": ("thumb4", 1.0, 0.0), + "{side}_finger2_tip_link": ("index4", 1.0, 0.0), + "{side}_finger3_tip_link": ("middle4", 1.0, 0.0), + "{side}_finger4_tip_link": ("ring4", 1.0, 0.0), + "{side}_finger5_tip_link": ("pinky4", 1.0, 0.0), +} + +# MANO MCP joints used as the palm IK target (index/middle/ring/pinky). +MANO_MCP_JOINTS = ("index1", "middle1", "ring1", "pinky1") + +DEFAULT_HAND = "wuji" + + +def retarget_npz_name(hand: str = DEFAULT_HAND) -> str: + return f"g1_{hand}_retarget.npz" diff --git a/retarget/requirements.txt b/retarget/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..7d64f734990892f8b87d8fd7f542caac4fae5a5d --- /dev/null +++ b/retarget/requirements.txt @@ -0,0 +1,13 @@ +numpy +scipy +tqdm +pin +pin-pink +daqp +loop-rate-limiters +opencv-python-headless +trimesh +pyrender +imageio +imageio-ffmpeg +PyOpenGL diff --git a/retarget/setup.sh b/retarget/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..24019bfc519a28415b1d2897be901edb71e2acaf --- /dev/null +++ b/retarget/setup.sh @@ -0,0 +1,46 @@ +#!/bin/bash +# Isolated retarget/.venv — Pinocchio/Pink. Never install into reconstruction/.venv +# (SAM3 pins numpy==1.26; pin pulls numpy 2). +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +VENV="$ROOT/.venv" +export PATH="${HOME}/.local/bin:${PATH}" + +if [[ "${1:-}" == "--into-reconstruction" ]]; then + echo "error: retarget must not share reconstruction/.venv" >&2 + exit 1 +fi + +pick_python() { + if [ -x /usr/bin/python3.10 ]; then + echo /usr/bin/python3.10 + return + fi + if [ -x /usr/bin/python3.11 ]; then + echo /usr/bin/python3.11 + return + fi + if [ -x /usr/bin/python3 ]; then + echo /usr/bin/python3 + return + fi + echo "error: no /usr/bin/python3.10" >&2 + exit 1 +} + +PYTHON="$(pick_python)" +echo "[retarget] python $PYTHON -> $VENV" +if command -v uv >/dev/null 2>&1; then + uv venv --python "$PYTHON" "$VENV" + uv pip install --python "$VENV/bin/python" -r "$ROOT/requirements.txt" +else + "$PYTHON" -m pip install --user virtualenv + "$PYTHON" -m virtualenv "$VENV" + "$VENV/bin/python" -m pip install -r "$ROOT/requirements.txt" +fi + +"$VENV/bin/python" -c "import numpy, pinocchio, pink; print('ok numpy', numpy.__version__, 'pinocchio', pinocchio.__version__)" +"$VENV/bin/python" "$ROOT/extract_wuji_hand_urdf.py" +echo +echo "[ok] source $VENV/bin/activate" +echo " python $ROOT/hawor_to_g1.py --video-dir # MANO → Wuji (default)" diff --git a/retarget/vis_retarget_video.py b/retarget/vis_retarget_video.py new file mode 100644 index 0000000000000000000000000000000000000000..03e0d1921fc5b65f115065cc92d95139cdfdaeca --- /dev/null +++ b/retarget/vis_retarget_video.py @@ -0,0 +1,448 @@ +#!/usr/bin/env python3 +"""MP4 of G1 five-finger retarget (robot visual meshes + HaWoR MANO). + +Matches NVIDIA robotic_grounding ``_offline_video.py`` content: Pinocchio +visual STLs, MANO mesh, optional tracked object. Uses pyrender+EGL when +available (GPU node); otherwise a CPU painter's rasterizer (login node). + + ./vis_retarget_video.sh --video-dir ../reconstruction/runs/ +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import cv2 +import numpy as np +import pinocchio as pin +import trimesh +from scipy.spatial.transform import Rotation as R + +from hand_kinematics import make_hand_kinematics +from params import DEFAULT_HAND, retarget_npz_name + +# OpenCV camera (x-right, y-down, z-forward) -> Z-up world. +_R_CAM_TO_ZUP = np.array( + [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0]], + dtype=np.float64, +) + + +def _require_retarget_venv() -> None: + if "/reconstruction/.venv" in os.path.realpath(sys.prefix): + print("[error] use retarget/.venv: ./vis_retarget_video.sh ...", file=sys.stderr) + sys.exit(1) + + +def _cam_to_zup_pts(p: np.ndarray) -> np.ndarray: + return np.asarray(p, dtype=np.float64) @ _R_CAM_TO_ZUP.T + + +def _cam_to_zup_q(q: np.ndarray) -> np.ndarray: + q = np.asarray(q, dtype=np.float64).copy() + q[:3] = _R_CAM_TO_ZUP @ q[:3] + Rm = _R_CAM_TO_ZUP @ R.from_quat(q[3:7]).as_matrix() + q[3:7] = R.from_matrix(Rm).as_quat() + return q + + +def _compose(rot: np.ndarray, trans: np.ndarray) -> np.ndarray: + T = np.eye(4) + T[:3, :3] = rot + T[:3, 3] = trans + return T + + +def _intrinsics(video_dir: Path, width: int, height: int): + npy = video_dir / "all_frames" / "000000_intrinsics.npy" + txt = video_dir / "0000_intrinsics.txt" + if npy.is_file(): + k = np.load(npy) + return float(k[0, 0]), float(k[1, 1]), float(k[0, 2]), float(k[1, 2]) + if txt.is_file(): + vals = [float(x) for x in txt.read_text().split()] + if len(vals) >= 4: + return vals[0], vals[1], vals[2], vals[3] + return 0.9 * width, 1.2 * height, width / 2.0, height / 2.0 + + +def _object_id(video_dir: Path) -> str | None: + cfg = video_dir / "config.json" + if cfg.is_file(): + names = json.loads(cfg.read_text()).get("object_names") or [] + if names: + return str(names[0]).replace(" ", "_") + return None + + +def _load_object(video_dir: Path, object_id: str | None): + if not object_id: + return None, None + layout = ( + video_dir + / "obj_tracking_out" + / object_id + / "combined_visualization" + / "layout_camera_frame_optimized.json" + ) + if not layout.is_file(): + layout = layout.with_name("layout_camera_frame.json") + mesh_path = ( + video_dir + / "video_segmentation" + / "masks" + / "frame_000000_masks" + / object_id + / f"{object_id}.obj" + ) + if not layout.is_file() or not mesh_path.is_file(): + return None, None + data = json.loads(layout.read_text()) + objects = [o for o in data.get("objects", []) if "frame_idx" in o] + objects.sort(key=lambda o: o["frame_idx"]) + tso = data.get("translation_scale_optimization") or {} + override_scale = float(tso["mesh_scale"]) if "mesh_scale" in tso else None + tm = trimesh.load(str(mesh_path), force="mesh") + if isinstance(tm, trimesh.Scene): + tm = tm.dump(concatenate=True) + poses = {} + for obj in objects: + lts = obj["local_to_scene"] + scale = override_scale if override_scale is not None else lts["scale"][0] + if data.get("frame") == "camera_frame": + qwxyz = lts["quat_wxyz_camera_frame"] + t = np.asarray(lts["translation_camera_frame"], dtype=np.float64) + else: + qwxyz = lts["new_quat"] + tx, ty, tz = lts["translation"] + t = np.array([tz, tx, ty], dtype=np.float64) + Rm = R.from_quat([qwxyz[1], qwxyz[2], qwxyz[3], qwxyz[0]]).as_matrix() + T = _compose(Rm * float(scale), t) + poses[int(obj["frame_idx"])] = T + verts = np.asarray(tm.vertices, dtype=np.float64) + faces = np.asarray(tm.faces, dtype=np.int32) + return (verts, faces), poses + + +def _decimate_faces(faces: np.ndarray, max_faces: int) -> np.ndarray: + if len(faces) <= max_faces: + return faces + rng = np.random.default_rng(0) + return faces[rng.choice(len(faces), max_faces, replace=False)] + + +def _load_visual_meshes(kin) -> list[dict]: + out = [] + vm = kin.robot.visual_model + if vm is None: + raise RuntimeError( + "URDF visual meshes missing. For Wuji run extract_wuji_hand_urdf.py; " + "for Inspire run fetch_inspire_meshes.sh" + ) + for geom in vm.geometryObjects: + path = geom.meshPath + if "hand_base_link" in geom.name: + # Inspire CAD palm origin is ~14cm behind the MCPs. + continue + if "palm_link" in geom.name and kin.hand == "inspire": + continue + if not path or not os.path.isfile(path): + continue + tm = trimesh.load(path, force="mesh") + if isinstance(tm, trimesh.Scene): + tm = tm.dump(concatenate=True) + if not isinstance(tm, trimesh.Trimesh) or len(tm.vertices) == 0: + continue + scale = np.asarray(geom.meshScale).reshape(3) + verts = np.asarray(tm.vertices, dtype=np.float64) * scale + faces = _decimate_faces(np.asarray(tm.faces, dtype=np.int32), 900) + out.append({"name": geom.name, "verts": verts, "faces": faces}) + return out + + +def _look_at_cv(eye, target): + eye = np.asarray(eye, dtype=np.float64) + target = np.asarray(target, dtype=np.float64) + z = target - eye + z = z / max(np.linalg.norm(z), 1e-9) + world_up = np.array([0.0, 0.0, 1.0]) + x = np.cross(z, world_up) + n = np.linalg.norm(x) + if n < 1e-6: + x = np.array([1.0, 0.0, 0.0]) + else: + x = x / n + y = np.cross(z, x) + R_wc = np.column_stack([x, y, z]) + return R_wc, eye + + +def _fit_camera(points: np.ndarray, yfov=np.pi / 3.0, elevation_deg=30.0, azimuth_deg=45.0, padding=1.6): + points = np.asarray(points, dtype=np.float64).reshape(-1, 3) + lo, hi = points.min(axis=0), points.max(axis=0) + target = 0.5 * (lo + hi) + diag = max(float(np.linalg.norm(hi - lo)), 0.3) + distance = padding * 0.5 * diag / max(np.tan(yfov / 2.0), 1e-6) + el, az = np.deg2rad(elevation_deg), np.deg2rad(azimuth_deg) + direction = np.array( + [np.cos(el) * np.cos(az), np.cos(el) * np.sin(az), np.sin(el)], + dtype=np.float64, + ) + return target + distance * direction, target + + +def _to_cam(xyz: np.ndarray, R_wc: np.ndarray | None, eye: np.ndarray | None) -> np.ndarray: + if R_wc is None: + return xyz + return (xyz - eye) @ R_wc + + +def _paint(img: np.ndarray, xyz_cam: np.ndarray, faces: np.ndarray, color, fx, fy, cx, cy): + near = 1e-3 + z = xyz_cam[:, 2] + vis = np.isfinite(xyz_cam).all(axis=1) & (z > near) + u = fx * xyz_cam[:, 0] / np.clip(z, near, None) + cx + v = fy * xyz_cam[:, 1] / np.clip(z, near, None) + cy + pts = np.stack([u, v], axis=1) + depths = [] + for i, f in enumerate(faces): + if not vis[f].all(): + continue + depths.append((float(z[f].mean()), i)) + depths.sort(reverse=True) + col = (int(color[0]), int(color[1]), int(color[2])) + h, w = img.shape[:2] + for _, i in depths: + tri = np.round(pts[faces[i]]).astype(np.int32) + if ( + (tri[:, 0] < 0).all() + or (tri[:, 0] >= w).all() + or (tri[:, 1] < 0).all() + or (tri[:, 1] >= h).all() + ): + continue + cv2.fillConvexPoly(img, tri, col, lineType=cv2.LINE_AA) + + +def _ffmpeg_bin() -> str | None: + import shutil + + exe = shutil.which("ffmpeg") + if exe: + return exe + try: + import imageio_ffmpeg + + return imageio_ffmpeg.get_ffmpeg_exe() + except Exception: + return None + + +def _ffmpeg(src: str, dst: Path) -> None: + dst.parent.mkdir(parents=True, exist_ok=True) + ff = _ffmpeg_bin() + if ff is None: + os.replace(src, str(dst)) + print("[warn] ffmpeg not found; wrote mp4v (may not play in all browsers)", flush=True) + return + subprocess.run( + [ff, "-y", "-i", src, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(dst)], + check=True, + ) + os.remove(src) + + +def parse_args(): + p = argparse.ArgumentParser(description="G1 five-finger retarget MP4") + p.add_argument("--video-dir", required=True, type=Path) + p.add_argument("--retarget-npz", default=None) + p.add_argument( + "--hand", + default=DEFAULT_HAND, + choices=["wuji", "inspire"], + ) + p.add_argument("--hand-meshes", default=None) + p.add_argument("--output", default=None) + p.add_argument("--fps", type=float, default=30.0) + p.add_argument( + "--view", + choices=["third_person", "overlay"], + default="third_person", + help="third_person = 3D look-at (robotic_grounding). overlay = on clip.mp4", + ) + p.add_argument("--no-object", action="store_true") + p.add_argument("--no-mano", action="store_true") + return p.parse_args() + + +def main(): + _require_retarget_venv() + args = parse_args() + video_dir = args.video_dir.resolve() + retarget_npz = Path(args.retarget_npz) if args.retarget_npz else ( + video_dir / "obj_tracking_out" / retarget_npz_name(args.hand) + ) + if not retarget_npz.is_file() and args.retarget_npz is None: + alt = video_dir / "obj_tracking_out" / retarget_npz_name( + "inspire" if args.hand == "wuji" else "wuji" + ) + if alt.is_file(): + retarget_npz = alt + if not retarget_npz.is_file(): + sys.exit(f"[error] run hawor_to_g1 first: missing {retarget_npz}") + hawor = Path(args.hand_meshes) if args.hand_meshes else video_dir / "clip" / "all_hand_meshes.npz" + if not hawor.is_file(): + sys.exit(f"[error] HaWoR npz not found: {hawor}") + + rt = np.load(retarget_npz, allow_pickle=True) + hm = np.load(hawor) + hand_kind = str(rt["hand"]) if "hand" in rt.files else args.hand + suffix = "_overlay" if args.view == "overlay" else "" + out = Path(args.output) if args.output else ( + video_dir / "obj_tracking_out" / f"g1_{hand_kind}_retarget{suffix}.mp4" + ) + hands = [str(x) for x in np.atleast_1d(rt["hands"]).tolist()] + qmap = {side: np.asarray(rt[f"{side}_q"]) for side in hands} + n_frames = max(q.shape[0] for q in qmap.values()) + overlay = args.view == "overlay" + + kins = {} + link_meshes = {} + for side in hands: + kin = make_hand_kinematics(side=side, hand=hand_kind) + kins[side] = kin + link_meshes[side] = _load_visual_meshes(kin) + print(f" {side} visual geoms={len(link_meshes[side])}", flush=True) + + obj_geom, obj_poses = (None, None) + if not args.no_object: + obj_geom, obj_poses = _load_object(video_dir, _object_id(video_dir)) + if obj_geom is not None: + print(f"object mesh frames={len(obj_poses)}", flush=True) + + if overlay: + clip = video_dir / "clip.mp4" + if not clip.is_file(): + sys.exit(f"[error] missing {clip}") + cap = cv2.VideoCapture(str(clip)) + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + fx, fy, cx, cy = _intrinsics(video_dir, width, height) + print(f"overlay CPU raster fx={fx:.1f} fy={fy:.1f}", flush=True) + R_wc, eye = None, None + else: + cap = None + width, height = 1280, 720 + yfov = np.pi / 3.0 + fy = height / (2.0 * np.tan(yfov / 2.0)) + fx = fy + cx, cy = width / 2.0, height / 2.0 + pts = [] + for side in hands: + q = qmap[side] + finite = np.isfinite(q).all(axis=1) + if finite.any(): + pts.append(_cam_to_zup_pts(q[finite, :3])) + if f"{side}_vertices" in hm: + v = np.asarray(hm[f"{side}_vertices"]) + z = v[:, :, 2] + ok = np.isfinite(z).all(axis=1) & (np.median(z, axis=1) >= 0.15) + if ok.any(): + pts.append(_cam_to_zup_pts(v[ok].reshape(-1, 3))) + if not pts: + sys.exit("[error] no finite poses to frame the camera") + all_pts = np.concatenate(pts, axis=0) + med = np.median(all_pts, axis=0) + inliers = all_pts[np.linalg.norm(all_pts - med, axis=1) < 5.0] + cam_eye, cam_target = _fit_camera(inliers if len(inliers) else all_pts) + R_wc, eye = _look_at_cv(cam_eye, cam_target) + print("third-person CPU rasterizer (no EGL on this node)", flush=True) + + tmp = str(out) + ".tmp.avi" + writer = cv2.VideoWriter(tmp, cv2.VideoWriter_fourcc(*"mp4v"), args.fps, (width, height)) + robot_color = {"right": (220, 160, 40), "left": (40, 90, 210)} + mano_color = (40, 200, 80) + obj_color = (70, 190, 120) + + for t in range(n_frames): + if overlay: + ok, bgr = cap.read() + if not ok: + break + canvas = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) + draw = np.zeros_like(canvas) + else: + canvas = np.full((height, width, 3), 235, dtype=np.uint8) + draw = canvas + for side in hands: + q = qmap[side][t] + if not np.isfinite(q).all(): + continue + q_use = q if overlay else _cam_to_zup_q(q) + kin = kins[side] + pin.forwardKinematics(kin.robot.model, kin.robot.data, q_use) + pin.updateGeometryPlacements( + kin.robot.model, kin.robot.data, kin.robot.visual_model, kin.robot.visual_data + ) + if not args.no_mano and f"{side}_vertices" in hm: + verts = np.asarray(hm[f"{side}_vertices"][t], dtype=np.float64) + if np.isfinite(verts).all() and float(np.median(verts[:, 2])) >= 0.15: + if not overlay: + verts = _cam_to_zup_pts(verts) + faces = _decimate_faces(np.asarray(hm[f"{side}_faces"], dtype=np.int32), 1500) + _paint(draw, _to_cam(verts, R_wc, eye), faces, mano_color, fx, fy, cx, cy) + for item in link_meshes[side]: + gid = kin.robot.visual_model.getGeometryId(item["name"]) + M = kin.robot.visual_data.oMg[gid] + xyz = item["verts"] @ np.asarray(M.rotation).T + np.asarray(M.translation) + _paint(draw, _to_cam(xyz, R_wc, eye), item["faces"], robot_color[side], fx, fy, cx, cy) + if obj_geom is not None and obj_poses is not None: + T = obj_poses.get(t) + if T is not None: + if not overlay: + T = T.copy() + T[:3, :3] = _R_CAM_TO_ZUP @ T[:3, :3] + T[:3, 3] = _R_CAM_TO_ZUP @ T[:3, 3] + verts, faces = obj_geom + xyz = verts @ T[:3, :3].T + T[:3, 3] + _paint(draw, _to_cam(xyz, R_wc, eye), _decimate_faces(faces, 2000), obj_color, fx, fy, cx, cy) + + if overlay: + vis = canvas.copy() + mask = draw.any(axis=2) + vis[mask] = ( + 0.62 * draw[mask].astype(np.float32) + 0.38 * canvas[mask].astype(np.float32) + ).clip(0, 255).astype(np.uint8) + else: + vis = draw + cv2.putText( + vis, + f"frame {t} green=MANO gold=G1 {hand_kind}", + (16, 36), + cv2.FONT_HERSHEY_SIMPLEX, + 0.8, + (40, 40, 40) if not overlay else (255, 255, 255), + 2, + cv2.LINE_AA, + ) + writer.write(cv2.cvtColor(vis, cv2.COLOR_RGB2BGR)) + if t % 10 == 0: + print(f" frame {t}/{n_frames}", flush=True) + + if cap is not None: + cap.release() + writer.release() + _ffmpeg(tmp, out) + print(f"wrote {out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/retarget/vis_retarget_video.sh b/retarget/vis_retarget_video.sh new file mode 100644 index 0000000000000000000000000000000000000000..7492daf7f4e859f73b808df0ed0628fae0a1e7e4 --- /dev/null +++ b/retarget/vis_retarget_video.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PY="$ROOT/.venv/bin/python" +if [[ ! -x "$PY" ]]; then + echo "retarget venv missing. Run: $ROOT/setup.sh" >&2 + exit 1 +fi +exec "$PY" "$ROOT/vis_retarget_video.py" "$@" diff --git a/rl/README.md b/rl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..47aac923f82f08de95db3df1a18e747e728ca274 --- /dev/null +++ b/rl/README.md @@ -0,0 +1,47 @@ +# RL + +Abstract trainer for **Unitree G1 + table + object** in Isaac Lab (real physics: +gravity, collisions, PD actuation). The Gym env lives in +`simulation/source/v2d_sim` and does **not** import `robotic_grounding`. + +NVIDIA `v2d_whole_body` is the layout reference (ManagerBasedRLEnv + RSL-RL PPO). +A frozen **SONIC v1.1** whole-body controller is wired separately (ONNX, G1 29-DoF) +via `simulation/replay_sonic.sh` — that is not this PPO stub. + +## Layout + +``` +rl/ +├── train.sh / play.sh +├── scripts/train.py +├── scripts/play.py +└── v2d_rl/algorithms/ # Algorithm ABC + RSL-RL PPO stub +``` + +Env: `simulation/source/v2d_sim/tasks/g1_table_object/` + +| Gym id | What | +|---|---| +| `V2D-G1-TableObject-v0` | 64 envs, G1 minimal (gravity on, floating base), kinematic table, dynamic box | +| `V2D-G1-TableObject-Play-v0` | same, 4 envs | + +## Run (GPU node, simulation/.venv) + +```bash +cd rl +./play.sh --headless --steps 300 +``` + +Writes `simulation/runs/rl/play/g1_table_object.mp4`. **Play does not use DexYCB +or reconstruction npz** — only the procedural Isaac scene (G1 minimal USD + cuboid +table and box) with zero (or `--random`) joint actions. + +Action space is joint-position PD (stub). Rewards are alive / upright / object-on-table +placeholders. + +Whole-body SONIC play (reconstruction clip, G1 29-DoF, not this Gym env): + +```bash +cd ../simulation +./replay_sonic.sh --headless +``` diff --git a/rl/play.sh b/rl/play.sh new file mode 100644 index 0000000000000000000000000000000000000000..7d3a7ba3b1fb62b036a15071f2c7b5806b81cba3 --- /dev/null +++ b/rl/play.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# Zero-action smoke test of the physical G1 scene; writes an MP4 under $RUNS_DIR/rl/play/. +set -euo pipefail +RL_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(cd "$RL_ROOT/.." && pwd)" +SIM_ROOT="$PROJECT_ROOT/simulation" +# shellcheck disable=SC1091 +source "$SIM_ROOT/config/paths.sh" +export PYTHONPATH="$SIM_ROOT/source:$RL_ROOT:$PYTHONPATH" +exec "$SIM_ROOT/run_isaaclab.sh" --python "$RL_ROOT/scripts/play.py" "$@" diff --git a/rl/scripts/play.py b/rl/scripts/play.py new file mode 100644 index 0000000000000000000000000000000000000000..2a77af901d10d9d5293f733591536c3d53bc860c --- /dev/null +++ b/rl/scripts/play.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Play the physical G1 + table + object env and write an MP4. + +This does **not** load DexYCB, HaWoR, or ``isaaclab_replay.npz``. The scene is +procedural Isaac Lab: Nucleus G1 (minimal USD), a cuboid table, a cuboid object. +Actions are zeros (or ``--random``) unless you pass a later checkpoint. + + ./play.sh --headless --steps 300 + # MP4: simulation/runs/rl/play/g1_table_object.mp4 +""" + +from __future__ import annotations + +import argparse +import os +import sys +from pathlib import Path + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Play V2D-G1-TableObject and record MP4.") +parser.add_argument("--task", type=str, default="V2D-G1-TableObject-Play-v0") +parser.add_argument("--num_envs", type=int, default=1) +parser.add_argument("--steps", type=int, default=300) +parser.add_argument("--random", action="store_true") +parser.add_argument( + "--output", + type=Path, + default=None, + help="MP4 path (default: $RUNS_DIR/rl/play/g1_table_object.mp4)", +) +parser.add_argument("--fps", type=float, default=30.0) +AppLauncher.add_app_launcher_args(parser) +args_cli = parser.parse_args() +args_cli.enable_cameras = True + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +import gymnasium as gym # noqa: E402 +import numpy as np # noqa: E402 +import torch # noqa: E402 +from isaaclab_tasks.utils import parse_env_cfg # noqa: E402 + +import v2d_sim # noqa: E402, F401 + + +def _as_uint8_rgb(img) -> np.ndarray | None: + if img is None: + return None + if hasattr(img, "cpu"): + img = img.detach().cpu().numpy() + img = np.asarray(img) + if img.ndim == 4: + img = img[0] + img = img[..., :3] + if img.dtype != np.uint8: + scale = 255.0 if float(np.nanmax(img)) <= 1.5 else 1.0 + img = np.clip(img * scale, 0, 255).astype(np.uint8) + h, w = img.shape[:2] + return img[: h - (h % 2), : w - (w % 2)] + + +def _write_mp4(path: Path, frames: list[np.ndarray], fps: float) -> None: + if not frames: + raise RuntimeError("no frames captured") + path.parent.mkdir(parents=True, exist_ok=True) + try: + import imageio.v2 as imageio + + imageio.mimsave(str(path), frames, fps=float(fps), codec="libx264", pixelformat="yuv420p") + return + except Exception as exc: + print(f"[v2d-rl] imageio h264 failed ({exc}); trying OpenCV", flush=True) + import cv2 + + h, w = frames[0].shape[:2] + writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), float(fps), (w, h)) + if not writer.isOpened(): + raise RuntimeError(f"could not open VideoWriter for {path}") + for fr in frames: + writer.write(cv2.cvtColor(fr, cv2.COLOR_RGB2BGR)) + writer.release() + + +def main() -> None: + runs = Path(os.environ.get("RUNS_DIR", Path.cwd() / "runs")) + out_mp4 = (args_cli.output or (runs / "rl" / "play" / "g1_table_object.mp4")).resolve() + env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=args_cli.num_envs) + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array") + env.reset() + print("[v2d-rl] play uses procedural Isaac assets (not DexYCB / isaaclab_replay.npz)", flush=True) + print(" robot: Unitree G1 (G1_MINIMAL_CFG), gravity on, floating base", flush=True) + print(" table: kinematic cuboid object: dynamic cuboid", flush=True) + print(f" actions: {'random' if args_cli.random else 'zeros'} steps={args_cli.steps}", flush=True) + print(f" mp4 {out_mp4}", flush=True) + + frames: list[np.ndarray] = [] + for i in range(args_cli.steps): + if not simulation_app.is_running(): + break + if args_cli.random: + action = torch.as_tensor(env.action_space.sample(), device=env.unwrapped.device) + else: + action = torch.zeros(env.unwrapped.action_space.shape, device=env.unwrapped.device) + _obs, rew, _term, _trunc, _info = env.step(action) + rgb = _as_uint8_rgb(env.unwrapped.render()) + if rgb is not None: + frames.append(rgb) + if i % 50 == 0: + r = rew.mean().item() if hasattr(rew, "mean") else float(rew) + print(f" step {i} reward_mean={r:.3f} frames={len(frames)}", flush=True) + + _write_mp4(out_mp4, frames, args_cli.fps) + print(f"[v2d-rl] wrote {out_mp4} ({len(frames)} frames)", flush=True) + env.close() + + +if __name__ == "__main__": + try: + main() + finally: + simulation_app.close() + sys.exit(0) diff --git a/rl/scripts/train.py b/rl/scripts/train.py new file mode 100644 index 0000000000000000000000000000000000000000..09e9c0c1328d0086614d14638baf4f49f48b87f1 --- /dev/null +++ b/rl/scripts/train.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Train V2D-G1-TableObject-v0 with the abstract PPO trainer. + +Must be launched through Isaac Lab (AppLauncher) so Sim starts first: + + cd simulation && source .venv/bin/activate + ../rl/train.sh --headless --num_envs 64 +""" + +from __future__ import annotations + +import argparse +import os +import sys +from datetime import datetime +from pathlib import Path + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Train G1 table-object RL (algorithm stub).") +parser.add_argument("--task", type=str, default="V2D-G1-TableObject-v0") +parser.add_argument("--num_envs", type=int, default=None) +parser.add_argument("--max_iterations", type=int, default=None) +parser.add_argument("--seed", type=int, default=42) +AppLauncher.add_app_launcher_args(parser) +args_cli = parser.parse_args() + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +import gymnasium as gym # noqa: E402 +from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper # noqa: E402 +from isaaclab_tasks.utils import parse_env_cfg # noqa: E402 + +import v2d_sim # noqa: E402, F401 +from v2d_rl.algorithms.ppo import RslRlPpoTrainer # noqa: E402 + + +def main() -> None: + env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=args_cli.num_envs) + env = gym.make(args_cli.task, cfg=env_cfg) + spec = gym.spec(args_cli.task) + agent_cfg_entry = spec.kwargs["rsl_rl_cfg_entry_point"] + mod_name, cls_name = agent_cfg_entry.rsplit(":", 1) + import importlib + + agent_cfg = getattr(importlib.import_module(mod_name), cls_name)() + if args_cli.max_iterations is not None: + agent_cfg.max_iterations = args_cli.max_iterations + agent_cfg.seed = args_cli.seed + + env = RslRlVecEnvWrapper(env) + log_root = Path(os.environ.get("RUNS_DIR", "runs")) / "rl" / args_cli.task + log_dir = str(log_root / datetime.now().strftime("%Y-%m-%d_%H-%M-%S")) + Path(log_dir).mkdir(parents=True, exist_ok=True) + print(f"[v2d-rl] task={args_cli.task} log={log_dir}", flush=True) + trainer = RslRlPpoTrainer(agent_cfg) + trainer.train(env, log_dir=log_dir) + env.close() + + +if __name__ == "__main__": + try: + main() + finally: + simulation_app.close() + sys.exit(0) diff --git a/rl/train.sh b/rl/train.sh new file mode 100644 index 0000000000000000000000000000000000000000..f813e683f60ca63b8adce0d273450014139b2f6f --- /dev/null +++ b/rl/train.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# Train G1 + table + object RL using simulation/.venv (Isaac Lab). +set -euo pipefail +RL_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(cd "$RL_ROOT/.." && pwd)" +SIM_ROOT="$PROJECT_ROOT/simulation" +# shellcheck disable=SC1091 +source "$SIM_ROOT/config/paths.sh" +export PYTHONPATH="$SIM_ROOT/source:$RL_ROOT:$PYTHONPATH" +export RUNS_DIR="${RUNS_DIR:-$SIM_ROOT/runs}" +exec "$SIM_ROOT/run_isaaclab.sh" --python "$RL_ROOT/scripts/train.py" "$@" diff --git a/rl/v2d_rl/__init__.py b/rl/v2d_rl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f083a3a72251778d8e51fbd1afc9754fa9774c31 --- /dev/null +++ b/rl/v2d_rl/__init__.py @@ -0,0 +1,5 @@ +"""Abstract RL algorithms for v2d G1 table-object training. + +Env lives in ``simulation/source/v2d_sim``. This package does not pick +PPO vs residual vs SONIC yet — only the trainer interface. +""" diff --git a/rl/v2d_rl/algorithms/__init__.py b/rl/v2d_rl/algorithms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a90e3512408755022383739cc2d49f5e3ddce104 --- /dev/null +++ b/rl/v2d_rl/algorithms/__init__.py @@ -0,0 +1,3 @@ +from .base import Algorithm # noqa: F401 +from .ppo import RslRlPpoTrainer # noqa: F401 +from .sonic import SonicAgent # noqa: F401 diff --git a/rl/v2d_rl/algorithms/base.py b/rl/v2d_rl/algorithms/base.py new file mode 100644 index 0000000000000000000000000000000000000000..2544d7e6da8fa45d57da336c71277e4ea1badd85 --- /dev/null +++ b/rl/v2d_rl/algorithms/base.py @@ -0,0 +1,22 @@ +"""Algorithm interface. Concrete PPO / residual / hierarchical details later.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import Any + + +class Algorithm(ABC): + """Train or roll out a policy against an Isaac Lab vec env.""" + + @abstractmethod + def train(self, env: Any, log_dir: str) -> None: + """Run learning. ``env`` is already wrapped for the library.""" + + @abstractmethod + def load(self, checkpoint: str) -> None: + """Load weights.""" + + @abstractmethod + def act(self, obs: Any) -> Any: + """Return actions for a batch of observations.""" diff --git a/rl/v2d_rl/algorithms/ppo.py b/rl/v2d_rl/algorithms/ppo.py new file mode 100644 index 0000000000000000000000000000000000000000..0aca9562f4b0db55622c8fed0b2bba229786906c --- /dev/null +++ b/rl/v2d_rl/algorithms/ppo.py @@ -0,0 +1,39 @@ +"""RSL-RL PPO trainer stub (Isaac Lab ``OnPolicyRunner``). + +Hyperparameters come from the Gym task's ``rsl_rl_cfg_entry_point``. +Swap this class when we lock the algorithm (plain PPO vs joint residual, etc.). +""" + +from __future__ import annotations + +from typing import Any + +from .base import Algorithm + + +class RslRlPpoTrainer(Algorithm): + def __init__(self, agent_cfg: Any): + self.agent_cfg = agent_cfg + self._runner = None + + def train(self, env: Any, log_dir: str) -> None: + from isaaclab.utils import class_to_dict + from rsl_rl.runners import OnPolicyRunner + + self._runner = OnPolicyRunner( + env, class_to_dict(self.agent_cfg), log_dir=log_dir, device=str(env.unwrapped.device) + ) + self._runner.learn( + num_learning_iterations=self.agent_cfg.max_iterations, + init_at_random_ep_len=True, + ) + + def load(self, checkpoint: str) -> None: + if self._runner is None: + raise RuntimeError("call train() or construct a runner before load()") + self._runner.load(checkpoint) + + def act(self, obs: Any) -> Any: + if self._runner is None: + raise RuntimeError("no runner") + return self._runner.alg.act(obs) diff --git a/rl/v2d_rl/algorithms/sonic.py b/rl/v2d_rl/algorithms/sonic.py new file mode 100644 index 0000000000000000000000000000000000000000..5297970361dab416c6d92bc8d10360fb7be0c4a9 --- /dev/null +++ b/rl/v2d_rl/algorithms/sonic.py @@ -0,0 +1,32 @@ +"""SONIC ONNX rollout helper (weights live under checkpoints/sonic).""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from v2d_sim.sonic import SonicOnnxAgent +from v2d_sim.sonic.obs import History, pack_decoder, pack_encoder + +from .base import Algorithm + + +class SonicAgent(Algorithm): + """Inference-only SONIC v1.1. Training is not implemented here.""" + + def __init__(self, checkpoint_dir: str | Path) -> None: + self.policy = SonicOnnxAgent(checkpoint_dir) + self.hist = History() + + def train(self, env: Any, log_dir: str) -> None: + raise NotImplementedError("SONIC here is a frozen ONNX controller; use GR00T gear_sonic to train.") + + def load(self, checkpoint: str) -> None: + self.policy = SonicOnnxAgent(checkpoint) + self.hist = History() + + def act(self, obs: Any) -> Any: + raise NotImplementedError("Use simulation/scripts/play_sonic.py for the packed encoder/decoder loop.") + + +__all__ = ["SonicAgent", "History", "pack_decoder", "pack_encoder"] diff --git a/simulation/.gitignore b/simulation/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1cd0bba293959e4676032e95c8af82b4ee67c5da --- /dev/null +++ b/simulation/.gitignore @@ -0,0 +1,5 @@ +.venv/ +runs/ +modules/IsaacLab/ +# ~39 MB Inspire hand USD mirror; recreate with scripts/fetch_inspire_hand.py +assets/ diff --git a/simulation/.venv-planner/bin/Activate.ps1 b/simulation/.venv-planner/bin/Activate.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..b49d77ba44b24fe6d69f6bbe75139b3b5dc23075 --- /dev/null +++ b/simulation/.venv-planner/bin/Activate.ps1 @@ -0,0 +1,247 @@ +<# +.Synopsis +Activate a Python virtual environment for the current PowerShell session. + +.Description +Pushes the python executable for a virtual environment to the front of the +$Env:PATH environment variable and sets the prompt to signify that you are +in a Python virtual environment. Makes use of the command line switches as +well as the `pyvenv.cfg` file values present in the virtual environment. + +.Parameter VenvDir +Path to the directory that contains the virtual environment to activate. The +default value for this is the parent of the directory that the Activate.ps1 +script is located within. + +.Parameter Prompt +The prompt prefix to display when this virtual environment is activated. By +default, this prompt is the name of the virtual environment folder (VenvDir) +surrounded by parentheses and followed by a single space (ie. '(.venv) '). + +.Example +Activate.ps1 +Activates the Python virtual environment that contains the Activate.ps1 script. + +.Example +Activate.ps1 -Verbose +Activates the Python virtual environment that contains the Activate.ps1 script, +and shows extra information about the activation as it executes. + +.Example +Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv +Activates the Python virtual environment located in the specified location. + +.Example +Activate.ps1 -Prompt "MyPython" +Activates the Python virtual environment that contains the Activate.ps1 script, +and prefixes the current prompt with the specified string (surrounded in +parentheses) while the virtual environment is active. + +.Notes +On Windows, it may be required to enable this Activate.ps1 script by setting the +execution policy for the user. You can do this by issuing the following PowerShell +command: + +PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser + +For more information on Execution Policies: +https://go.microsoft.com/fwlink/?LinkID=135170 + +#> +Param( + [Parameter(Mandatory = $false)] + [String] + $VenvDir, + [Parameter(Mandatory = $false)] + [String] + $Prompt +) + +<# Function declarations --------------------------------------------------- #> + +<# +.Synopsis +Remove all shell session elements added by the Activate script, including the +addition of the virtual environment's Python executable from the beginning of +the PATH variable. + +.Parameter NonDestructive +If present, do not remove this function from the global namespace for the +session. + +#> +function global:deactivate ([switch]$NonDestructive) { + # Revert to original values + + # The prior prompt: + if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) { + Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt + Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT + } + + # The prior PYTHONHOME: + if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) { + Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME + Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME + } + + # The prior PATH: + if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) { + Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH + Remove-Item -Path Env:_OLD_VIRTUAL_PATH + } + + # Just remove the VIRTUAL_ENV altogether: + if (Test-Path -Path Env:VIRTUAL_ENV) { + Remove-Item -Path env:VIRTUAL_ENV + } + + # Just remove VIRTUAL_ENV_PROMPT altogether. + if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) { + Remove-Item -Path env:VIRTUAL_ENV_PROMPT + } + + # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether: + if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) { + Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force + } + + # Leave deactivate function in the global namespace if requested: + if (-not $NonDestructive) { + Remove-Item -Path function:deactivate + } +} + +<# +.Description +Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the +given folder, and returns them in a map. + +For each line in the pyvenv.cfg file, if that line can be parsed into exactly +two strings separated by `=` (with any amount of whitespace surrounding the =) +then it is considered a `key = value` line. The left hand string is the key, +the right hand is the value. + +If the value starts with a `'` or a `"` then the first and last character is +stripped from the value before being captured. + +.Parameter ConfigDir +Path to the directory that contains the `pyvenv.cfg` file. +#> +function Get-PyVenvConfig( + [String] + $ConfigDir +) { + Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg" + + # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue). + $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue + + # An empty map will be returned if no config file is found. + $pyvenvConfig = @{ } + + if ($pyvenvConfigPath) { + + Write-Verbose "File exists, parse `key = value` lines" + $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath + + $pyvenvConfigContent | ForEach-Object { + $keyval = $PSItem -split "\s*=\s*", 2 + if ($keyval[0] -and $keyval[1]) { + $val = $keyval[1] + + # Remove extraneous quotations around a string value. + if ("'""".Contains($val.Substring(0, 1))) { + $val = $val.Substring(1, $val.Length - 2) + } + + $pyvenvConfig[$keyval[0]] = $val + Write-Verbose "Adding Key: '$($keyval[0])'='$val'" + } + } + } + return $pyvenvConfig +} + + +<# Begin Activate script --------------------------------------------------- #> + +# Determine the containing directory of this script +$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition +$VenvExecDir = Get-Item -Path $VenvExecPath + +Write-Verbose "Activation script is located in path: '$VenvExecPath'" +Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)" +Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)" + +# Set values required in priority: CmdLine, ConfigFile, Default +# First, get the location of the virtual environment, it might not be +# VenvExecDir if specified on the command line. +if ($VenvDir) { + Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values" +} +else { + Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir." + $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/") + Write-Verbose "VenvDir=$VenvDir" +} + +# Next, read the `pyvenv.cfg` file to determine any required value such +# as `prompt`. +$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir + +# Next, set the prompt from the command line, or the config file, or +# just use the name of the virtual environment folder. +if ($Prompt) { + Write-Verbose "Prompt specified as argument, using '$Prompt'" +} +else { + Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value" + if ($pyvenvCfg -and $pyvenvCfg['prompt']) { + Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'" + $Prompt = $pyvenvCfg['prompt']; + } + else { + Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)" + Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'" + $Prompt = Split-Path -Path $venvDir -Leaf + } +} + +Write-Verbose "Prompt = '$Prompt'" +Write-Verbose "VenvDir='$VenvDir'" + +# Deactivate any currently active virtual environment, but leave the +# deactivate function in place. +deactivate -nondestructive + +# Now set the environment variable VIRTUAL_ENV, used by many tools to determine +# that there is an activated venv. +$env:VIRTUAL_ENV = $VenvDir + +if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) { + + Write-Verbose "Setting prompt to '$Prompt'" + + # Set the prompt to include the env name + # Make sure _OLD_VIRTUAL_PROMPT is global + function global:_OLD_VIRTUAL_PROMPT { "" } + Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT + New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt + + function global:prompt { + Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) " + _OLD_VIRTUAL_PROMPT + } + $env:VIRTUAL_ENV_PROMPT = $Prompt +} + +# Clear PYTHONHOME +if (Test-Path -Path Env:PYTHONHOME) { + Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME + Remove-Item -Path Env:PYTHONHOME +} + +# Add the venv to the PATH +Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH +$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH" diff --git a/simulation/.venv-planner/bin/activate b/simulation/.venv-planner/bin/activate new file mode 100644 index 0000000000000000000000000000000000000000..15ce741196688abd4aaac37db7f9ffcb433fc1d6 --- /dev/null +++ b/simulation/.venv-planner/bin/activate @@ -0,0 +1,76 @@ +# This file must be used with "source bin/activate" *from bash* +# You cannot run it directly + +deactivate () { + # reset old environment variables + if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then + PATH="${_OLD_VIRTUAL_PATH:-}" + export PATH + unset _OLD_VIRTUAL_PATH + fi + if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then + PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}" + export PYTHONHOME + unset _OLD_VIRTUAL_PYTHONHOME + fi + + # Call hash to forget past locations. Without forgetting + # past locations the $PATH changes we made may not be respected. + # See "man bash" for more details. hash is usually a builtin of your shell + hash -r 2> /dev/null + + if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then + PS1="${_OLD_VIRTUAL_PS1:-}" + export PS1 + unset _OLD_VIRTUAL_PS1 + fi + + unset VIRTUAL_ENV + unset VIRTUAL_ENV_PROMPT + if [ ! "${1:-}" = "nondestructive" ] ; then + # Self destruct! + unset -f deactivate + fi +} + +# unset irrelevant variables +deactivate nondestructive + +# on Windows, a path can contain colons and backslashes and has to be converted: +case "$(uname)" in + CYGWIN*|MSYS*|MINGW*) + # transform D:\path\to\venv to /d/path/to/venv on MSYS and MINGW + # and to /cygdrive/d/path/to/venv on Cygwin + VIRTUAL_ENV=$(cygpath /scratch/users/create/smrvmdo/projects/v2d/simulation/.venv-planner) + export VIRTUAL_ENV + ;; + *) + # use the path as-is + export VIRTUAL_ENV=/scratch/users/create/smrvmdo/projects/v2d/simulation/.venv-planner + ;; +esac + +_OLD_VIRTUAL_PATH="$PATH" +PATH="$VIRTUAL_ENV/"bin":$PATH" +export PATH + +VIRTUAL_ENV_PROMPT='(.venv-planner) ' +export VIRTUAL_ENV_PROMPT + +# unset PYTHONHOME if set +# this will fail if PYTHONHOME is set to the empty string (which is bad anyway) +# could use `if (set -u; : $PYTHONHOME) ;` in bash +if [ -n "${PYTHONHOME:-}" ] ; then + _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}" + unset PYTHONHOME +fi + +if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then + _OLD_VIRTUAL_PS1="${PS1:-}" + PS1="("'(.venv-planner) '") ${PS1:-}" + export PS1 +fi + +# Call hash to forget past commands. Without forgetting +# past commands the $PATH changes we made may not be respected +hash -r 2> /dev/null diff --git a/simulation/.venv-planner/bin/activate.csh b/simulation/.venv-planner/bin/activate.csh new file mode 100644 index 0000000000000000000000000000000000000000..e4449b519bbc536a736f9c0c1a6e9733269d45ef --- /dev/null +++ b/simulation/.venv-planner/bin/activate.csh @@ -0,0 +1,27 @@ +# This file must be used with "source bin/activate.csh" *from csh*. +# You cannot run it directly. + +# Created by Davide Di Blasi . +# Ported to Python 3.3 venv by Andrew Svetlov + +alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate' + +# Unset irrelevant variables. +deactivate nondestructive + +setenv VIRTUAL_ENV /scratch/users/create/smrvmdo/projects/v2d/simulation/.venv-planner + +set _OLD_VIRTUAL_PATH="$PATH" +setenv PATH "$VIRTUAL_ENV/"bin":$PATH" + + +set _OLD_VIRTUAL_PROMPT="$prompt" + +if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then + set prompt = '(.venv-planner) '"$prompt" + setenv VIRTUAL_ENV_PROMPT '(.venv-planner) ' +endif + +alias pydoc python -m pydoc + +rehash diff --git a/simulation/.venv-planner/bin/activate.fish b/simulation/.venv-planner/bin/activate.fish new file mode 100644 index 0000000000000000000000000000000000000000..3bad8d4fc67632dfede2d5e6d4da41253ac3a875 --- /dev/null +++ b/simulation/.venv-planner/bin/activate.fish @@ -0,0 +1,69 @@ +# This file must be used with "source /bin/activate.fish" *from fish* +# (https://fishshell.com/). You cannot run it directly. + +function deactivate -d "Exit virtual environment and return to normal shell environment" + # reset old environment variables + if test -n "$_OLD_VIRTUAL_PATH" + set -gx PATH $_OLD_VIRTUAL_PATH + set -e _OLD_VIRTUAL_PATH + end + if test -n "$_OLD_VIRTUAL_PYTHONHOME" + set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME + set -e _OLD_VIRTUAL_PYTHONHOME + end + + if test -n "$_OLD_FISH_PROMPT_OVERRIDE" + set -e _OLD_FISH_PROMPT_OVERRIDE + # prevents error when using nested fish instances (Issue #93858) + if functions -q _old_fish_prompt + functions -e fish_prompt + functions -c _old_fish_prompt fish_prompt + functions -e _old_fish_prompt + end + end + + set -e VIRTUAL_ENV + set -e VIRTUAL_ENV_PROMPT + if test "$argv[1]" != "nondestructive" + # Self-destruct! + functions -e deactivate + end +end + +# Unset irrelevant variables. +deactivate nondestructive + +set -gx VIRTUAL_ENV /scratch/users/create/smrvmdo/projects/v2d/simulation/.venv-planner + +set -gx _OLD_VIRTUAL_PATH $PATH +set -gx PATH "$VIRTUAL_ENV/"bin $PATH + +# Unset PYTHONHOME if set. +if set -q PYTHONHOME + set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME + set -e PYTHONHOME +end + +if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" + # fish uses a function instead of an env var to generate the prompt. + + # Save the current fish_prompt function as the function _old_fish_prompt. + functions -c fish_prompt _old_fish_prompt + + # With the original prompt function renamed, we can override with our own. + function fish_prompt + # Save the return status of the last command. + set -l old_status $status + + # Output the venv prompt; color taken from the blue of the Python logo. + printf "%s%s%s" (set_color 4B8BBE) '(.venv-planner) ' (set_color normal) + + # Restore the return status of the previous command. + echo "exit $old_status" | . + # Output the original/"old" prompt. + _old_fish_prompt + end + + set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV" + set -gx VIRTUAL_ENV_PROMPT '(.venv-planner) ' +end diff --git a/simulation/.venv-planner/bin/pip b/simulation/.venv-planner/bin/pip new file mode 100644 index 0000000000000000000000000000000000000000..3b3dc6878ca93a9d87517787985528f93c621b5b --- /dev/null +++ b/simulation/.venv-planner/bin/pip @@ -0,0 +1,8 @@ +#!/scratch/users/create/smrvmdo/projects/v2d/simulation/.venv-planner/bin/python3.12 +# -*- coding: utf-8 -*- +import re +import sys +from pip._internal.cli.main import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/simulation/.venv-planner/bin/pip3 b/simulation/.venv-planner/bin/pip3 new file mode 100644 index 0000000000000000000000000000000000000000..3b3dc6878ca93a9d87517787985528f93c621b5b --- /dev/null +++ b/simulation/.venv-planner/bin/pip3 @@ -0,0 +1,8 @@ +#!/scratch/users/create/smrvmdo/projects/v2d/simulation/.venv-planner/bin/python3.12 +# -*- coding: utf-8 -*- +import re +import sys +from pip._internal.cli.main import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/simulation/.venv-planner/bin/pip3.12 b/simulation/.venv-planner/bin/pip3.12 new file mode 100644 index 0000000000000000000000000000000000000000..3b3dc6878ca93a9d87517787985528f93c621b5b --- /dev/null +++ b/simulation/.venv-planner/bin/pip3.12 @@ -0,0 +1,8 @@ +#!/scratch/users/create/smrvmdo/projects/v2d/simulation/.venv-planner/bin/python3.12 +# -*- coding: utf-8 -*- +import re +import sys +from pip._internal.cli.main import main +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(main()) diff --git a/simulation/.venv-planner/bin/python b/simulation/.venv-planner/bin/python new file mode 100644 index 0000000000000000000000000000000000000000..a35293803763fe3db4a7a0294d08b62d0a906ca2 --- /dev/null +++ b/simulation/.venv-planner/bin/python @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9544d2a29138833e6177d45dbc57468d37710b5080c901fbb579d53f251cdd6f +size 30929576 diff --git a/simulation/.venv-planner/bin/python3 b/simulation/.venv-planner/bin/python3 new file mode 100644 index 0000000000000000000000000000000000000000..a35293803763fe3db4a7a0294d08b62d0a906ca2 --- /dev/null +++ b/simulation/.venv-planner/bin/python3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9544d2a29138833e6177d45dbc57468d37710b5080c901fbb579d53f251cdd6f +size 30929576 diff --git a/simulation/.venv-planner/bin/python3.12 b/simulation/.venv-planner/bin/python3.12 new file mode 100644 index 0000000000000000000000000000000000000000..a35293803763fe3db4a7a0294d08b62d0a906ca2 --- /dev/null +++ b/simulation/.venv-planner/bin/python3.12 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9544d2a29138833e6177d45dbc57468d37710b5080c901fbb579d53f251cdd6f +size 30929576 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/_simvenv.pth b/simulation/.venv-planner/lib/python3.12/site-packages/_simvenv.pth new file mode 100644 index 0000000000000000000000000000000000000000..1cfd2d9e211d9e0121e6d3dc838dbeb5168f90df --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/_simvenv.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:301076676cff0b26ff2439f531e78ffe7380502f45916233d12f7ce64660a5a8 +size 89 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/INSTALLER b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/METADATA b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b4aa797cbefebe54b6be2e7d8b3425f72497c6c4 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/METADATA @@ -0,0 +1,202 @@ +Metadata-Version: 2.4 +Name: adam-atan2-pytorch +Version: 0.4.0 +Summary: Adam-atan2 for Pytorch +Project-URL: Homepage, https://pypi.org/project/adam_atan2_pytorch/ +Project-URL: Repository, https://github.com/lucidrains/adam_atan2_pytorch +Author-email: Phil Wang +License: MIT License + + Copyright (c) 2024 Phil Wang + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +License-File: LICENSE +Keywords: adam,artificial intelligence,deep learning,optimizers +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3.9 +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Requires-Python: >=3.9 +Requires-Dist: einops>=0.8.0 +Requires-Dist: torch>=2.0 +Provides-Extra: examples +Provides-Extra: test +Requires-Dist: pytest; extra == 'test' +Description-Content-Type: text/markdown + + + +## Adam-atan2 - Pytorch + +Implementation of the proposed Adam-atan2 optimizer in Pytorch + +A multi-million dollar paper out of google deepmind proposes a small change to Adam update rule (using `atan2`) to remove the epsilon altogether for numerical stability and scale invariance + +It also contains some features for improving plasticity (continual learning field) + +## Install + +```bash +$ pip install adam-atan2-pytorch +``` + +## Usage + +```python +import torch +from torch import nn + +# toy model + +model = nn.Linear(10, 1) + +# import AdamAtan2 and instantiate with parameters + +from adam_atan2_pytorch import AdamAtan2 + +opt = AdamAtan2(model.parameters(), lr = 1e-4) + +# forward and backwards + +for _ in range(100): + loss = model(torch.randn(10)) + loss.backward() + + # optimizer step + + opt.step() + opt.zero_grad() +``` + +## Citations + +```bibtex +@inproceedings{Everett2024ScalingEA, + title = {Scaling Exponents Across Parameterizations and Optimizers}, + author = {Katie Everett and Lechao Xiao and Mitchell Wortsman and Alex Alemi and Roman Novak and Peter J. Liu and Izzeddin Gur and Jascha Narain Sohl-Dickstein and Leslie Pack Kaelbling and Jaehoon Lee and Jeffrey Pennington}, + year = {2024}, + url = {https://api.semanticscholar.org/CorpusID:271051056} +} +``` + +```bibtex +@inproceedings{Kumar2023MaintainingPI, + title = {Maintaining Plasticity in Continual Learning via Regenerative Regularization}, + author = {Saurabh Kumar and Henrik Marklund and Benjamin Van Roy}, + year = {2023}, + url = {https://api.semanticscholar.org/CorpusID:261076021} +} +``` + +```bibtex +@article{Lewandowski2024LearningCB, + title = {Learning Continually by Spectral Regularization}, + author = {Alex Lewandowski and Saurabh Kumar and Dale Schuurmans and Andr'as Gyorgy and Marlos C. Machado}, + journal = {ArXiv}, + year = {2024}, + volume = {abs/2406.06811}, + url = {https://api.semanticscholar.org/CorpusID:270380086} +} +``` + +```bibtex +@inproceedings{Taniguchi2024ADOPTMA, + title = {ADOPT: Modified Adam Can Converge with Any \$\beta\_2\$ with the Optimal Rate}, + author = {Shohei Taniguchi and Keno Harada and Gouki Minegishi and Yuta Oshima and Seong Cheol Jeong and Go Nagahara and Tomoshi Iiyama and Masahiro Suzuki and Yusuke Iwasawa and Yutaka Matsuo}, + year = {2024}, + url = {https://api.semanticscholar.org/CorpusID:273822148} +} +``` + +```bibtex +@inproceedings{Liang2024CautiousOI, + title = {Cautious Optimizers: Improving Training with One Line of Code}, + author = {Kaizhao Liang and Lizhang Chen and Bo Liu and Qiang Liu}, + year = {2024}, + url = {https://api.semanticscholar.org/CorpusID:274234738} +} +``` + +```bibtex +@misc{jordan2024muon, + author = {Keller Jordan and Yuchen Jin and Vlado Boza and Jiacheng You and Franz Cesista and Laker Newhouse and Jeremy Bernstein}, + title = {Muon: An optimizer for hidden layers in neural networks}, + year = {2024}, + url = {https://kellerjordan.github.io/posts/muon/} +} +``` + +```bibtex +@misc{kimiteam2025kimik2openagentic, + title = {Kimi K2: Open Agentic Intelligence}, + author = {Kimi Team and Yifan Bai and Yiping Bao and Guanduo Chen and Jiahao Chen and Ningxin Chen and Ruijue Chen and Yanru Chen and Yuankun Chen and Yutian Chen and Zhuofu Chen and Jialei Cui and Hao Ding and Mengnan Dong and Angang Du and Chenzhuang Du and Dikang Du and Yulun Du and Yu Fan and Yichen Feng and Kelin Fu and Bofei Gao and Hongcheng Gao and Peizhong Gao and Tong Gao and Xinran Gu and Longyu Guan and Haiqing Guo and Jianhang Guo and Hao Hu and Xiaoru Hao and Tianhong He and Weiran He and Wenyang He and Chao Hong and Yangyang Hu and Zhenxing Hu and Weixiao Huang and Zhiqi Huang and Zihao Huang and Tao Jiang and Zhejun Jiang and Xinyi Jin and Yongsheng Kang and Guokun Lai and Cheng Li and Fang Li and Haoyang Li and Ming Li and Wentao Li and Yanhao Li and Yiwei Li and Zhaowei Li and Zheming Li and Hongzhan Lin and Xiaohan Lin and Zongyu Lin and Chengyin Liu and Chenyu Liu and Hongzhang Liu and Jingyuan Liu and Junqi Liu and Liang Liu and Shaowei Liu and T. Y. Liu and Tianwei Liu and Weizhou Liu and Yangyang Liu and Yibo Liu and Yiping Liu and Yue Liu and Zhengying Liu and Enzhe Lu and Lijun Lu and Shengling Ma and Xinyu Ma and Yingwei Ma and Shaoguang Mao and Jie Mei and Xin Men and Yibo Miao and Siyuan Pan and Yebo Peng and Ruoyu Qin and Bowen Qu and Zeyu Shang and Lidong Shi and Shengyuan Shi and Feifan Song and Jianlin Su and Zhengyuan Su and Xinjie Sun and Flood Sung and Heyi Tang and Jiawen Tao and Qifeng Teng and Chensi Wang and Dinglu Wang and Feng Wang and Haiming Wang and Jianzhou Wang and Jiaxing Wang and Jinhong Wang and Shengjie Wang and Shuyi Wang and Yao Wang and Yejie Wang and Yiqin Wang and Yuxin Wang and Yuzhi Wang and Zhaoji Wang and Zhengtao Wang and Zhexu Wang and Chu Wei and Qianqian Wei and Wenhao Wu and Xingzhe Wu and Yuxin Wu and Chenjun Xiao and Xiaotong Xie and Weimin Xiong and Boyu Xu and Jing Xu and Jinjing Xu and L. H. Xu and Lin Xu and Suting Xu and Weixin Xu and Xinran Xu and Yangchuan Xu and Ziyao Xu and Junjie Yan and Yuzi Yan and Xiaofei Yang and Ying Yang and Zhen Yang and Zhilin Yang and Zonghan Yang and Haotian Yao and Xingcheng Yao and Wenjie Ye and Zhuorui Ye and Bohong Yin and Longhui Yu and Enming Yuan and Hongbang Yuan and Mengjie Yuan and Haobing Zhan and Dehao Zhang and Hao Zhang and Wanlu Zhang and Xiaobin Zhang and Yangkun Zhang and Yizhi Zhang and Yongting Zhang and Yu Zhang and Yutao Zhang and Yutong Zhang and Zheng Zhang and Haotian Zhao and Yikai Zhao and Huabin Zheng and Shaojie Zheng and Jianren Zhou and Xinyu Zhou and Zaida Zhou and Zhen Zhu and Weiyu Zhuang and Xinxing Zu}, + year = {2025}, + eprint = {2507.20534}, + archivePrefix = {arXiv}, + primaryClass = {cs.LG}, + url = {https://arxiv.org/abs/2507.20534}, +} +``` + +```bibtex +@misc{chen2026cautiousweightdecay, + title = {Cautious Weight Decay}, + author = {Lizhang Chen and Jonathan Li and Kaizhao Liang and Baiyu Su and Cong Xie and Nuo Wang Pierse and Chen Liang and Ni Lao and Qiang Liu}, + year = {2026}, + eprint = {2510.12402}, + archivePrefix = {arXiv}, + primaryClass = {cs.LG}, + url = {https://arxiv.org/abs/2510.12402}, +} +``` + +```bibtex +@misc{amsel2025polarexpressoptimalmatrix, + title = {The Polar Express: Optimal Matrix Sign Methods and Their Application to the Muon Algorithm}, + author = {Noah Amsel and David Persson and Christopher Musco and Robert M. Gower}, + year = {2025}, + eprint = {2505.16932}, + archivePrefix = {arXiv}, + primaryClass = {cs.LG}, + url = {https://arxiv.org/abs/2505.16932}, +} +``` + +```bibtex +@misc{han2025learningstreamingvideoorthogonal, + title = {Learning from Streaming Video with Orthogonal Gradients}, + author = {Tengda Han and Dilara Gokay and Joseph Heyward and Chuhan Zhang and Daniel Zoran and Viorica Pătrăucean and João Carreira and Dima Damen and Andrew Zisserman}, + year = {2025}, + eprint = {2504.01961}, + archivePrefix = {arXiv}, + primaryClass = {cs.CV}, + url = {https://arxiv.org/abs/2504.01961}, +} +``` + +```bibtex +@article{volchkov2026cliptogrok, + title = {Clip to Grok: Weight Norm Clipping for Accelerated Generalization}, + author = {Volchkov, Vladimir and Rivlin, Aviad}, + year = {2026}, + journal = {arXiv preprint}, + note = {Implementation available at \url{https://github.com/NiftyliuS/cliptogrok}} +} +``` diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/RECORD b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..eacc7e4a82639554d5318558e99cf7c9848497bb --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/RECORD @@ -0,0 +1,26 @@ +adam_atan2_pytorch-0.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +adam_atan2_pytorch-0.4.0.dist-info/METADATA,sha256=4IAwjfs1HMgNUdhbK4ODbKxZ9tniREthrGcSZva-s7E,9671 +adam_atan2_pytorch-0.4.0.dist-info/RECORD,, +adam_atan2_pytorch-0.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +adam_atan2_pytorch-0.4.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87 +adam_atan2_pytorch-0.4.0.dist-info/licenses/LICENSE,sha256=E7RGS7kpJIStk5za_-4DVhWEAamf65EU0CNML25mq4c,1066 +adam_atan2_pytorch/__init__.py,sha256=l4eeNYacsax0kzoJyhOmeqAjQtbxK1qkuoPAghw_L90,338 +adam_atan2_pytorch/__pycache__/__init__.cpython-312.pyc,, +adam_atan2_pytorch/__pycache__/adam_atan2.cpython-312.pyc,, +adam_atan2_pytorch/__pycache__/adam_atan2_clip_grok.cpython-312.pyc,, +adam_atan2_pytorch/__pycache__/adam_atan2_with_orthog_grad.cpython-312.pyc,, +adam_atan2_pytorch/__pycache__/adam_atan2_with_wasserstein_reg.cpython-312.pyc,, +adam_atan2_pytorch/__pycache__/adopt.cpython-312.pyc,, +adam_atan2_pytorch/__pycache__/adopt_atan2.cpython-312.pyc,, +adam_atan2_pytorch/__pycache__/foreach.cpython-312.pyc,, +adam_atan2_pytorch/__pycache__/muon_adam_atan2.cpython-312.pyc,, +adam_atan2_pytorch/__pycache__/polar_adam_atan2.cpython-312.pyc,, +adam_atan2_pytorch/adam_atan2.py,sha256=bCQkxM7RJggEFbwU8UoxjghFkns59Kv7Ly0duK1kcck,4421 +adam_atan2_pytorch/adam_atan2_clip_grok.py,sha256=rqK6bMpt3JjjmpHvkS23MwylerXxDZMDNgUlC2C6Cls,5334 +adam_atan2_pytorch/adam_atan2_with_orthog_grad.py,sha256=vSSZt059Me0TSb6WXUO1u3LRNbZyoFeIlFBdYTuextg,7080 +adam_atan2_pytorch/adam_atan2_with_wasserstein_reg.py,sha256=Wrmw93DJCHdrRdDQFWcJXL-KJl-uOuO0UL_ZpYKr7b8,4141 +adam_atan2_pytorch/adopt.py,sha256=Ja4_bXg8TBa978tPo9cNe2Af1rMt5Tcf2BCwFkLKtIE,2859 +adam_atan2_pytorch/adopt_atan2.py,sha256=eNQD02nh806T5l43ssIHjCnir-01br7eKz09y4hR8eI,3858 +adam_atan2_pytorch/foreach.py,sha256=IPwzq-tdjSBdnBmAdgSkhWwpLJw1Hl7U0rjEYoAGdFA,4769 +adam_atan2_pytorch/muon_adam_atan2.py,sha256=Q4XJ3_qgYRaC4ODRNT--GwrM1ZbLTWr29FXeDAXCBaQ,7431 +adam_atan2_pytorch/polar_adam_atan2.py,sha256=o7mSCf97f4Lly1YLrrdTFSubO1T2nEIP4pJpCvb4f0c,8752 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/REQUESTED b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/WHEEL b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7401812e19af977cc5088f3b8fb1ef6bc0441c0a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.31.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/licenses/LICENSE b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ec5abf0f1fafaf17e95eb05a67f5c54df5f4cae1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch-0.4.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Phil Wang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..227fdb8cbce2aea0bd3796a801476b7edba62f8f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__init__.py @@ -0,0 +1,9 @@ +from adam_atan2_pytorch.adam_atan2 import AdamAtan2 +from adam_atan2_pytorch.adam_atan2_clip_grok import AdamAtan2ClipGrok +from adam_atan2_pytorch.adopt_atan2 import AdoptAtan2 + +from adam_atan2_pytorch.muon_adam_atan2 import MuonAdamAtan2 +from adam_atan2_pytorch.polar_adam_atan2 import PolarAdamAtan2 + +Adam = AdamAtan2 +Adopt = AdoptAtan2 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f42a283937a35b8cc5bff3cf5e286af146f6d73e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aec48aac4892e5e7056a4fca275cc51b6e7ceada Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2_clip_grok.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2_clip_grok.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9857ca7a45dd65591ac94a7b47c640aaf651ad31 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2_clip_grok.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2_with_orthog_grad.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2_with_orthog_grad.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dab1fc83d0ce5655f27bfc4ace466d12398d8adf Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2_with_orthog_grad.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2_with_wasserstein_reg.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2_with_wasserstein_reg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..301b17021e3bb53ec3147c9fff8156d3080b3e76 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adam_atan2_with_wasserstein_reg.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adopt.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adopt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e30e9ddb351306cf8e42ad09269a8116d77d33dd Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adopt.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adopt_atan2.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adopt_atan2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb37c93fb8f11fb451611c3d72540e6c6b499699 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/adopt_atan2.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/foreach.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/foreach.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5ae8ad142e38fd4d1eb02f98bd0950ae0002933 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/foreach.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/muon_adam_atan2.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/muon_adam_atan2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28cb0bc456fb5308f7372bb312a40f94ccc3fcef Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/muon_adam_atan2.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/polar_adam_atan2.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/polar_adam_atan2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..632e9dcfda717346554c66cbde9afcbad5c1df90 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/__pycache__/polar_adam_atan2.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2.py b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2.py new file mode 100644 index 0000000000000000000000000000000000000000..62eee24b7390620c15e543ba353c90e04837633e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2.py @@ -0,0 +1,139 @@ +from __future__ import annotations +from typing import Callable + +import torch +from torch import atan2, sqrt +from torch.optim.optimizer import Optimizer + +# functions + +def exists(val): + return val is not None + +# class + +class AdamAtan2(Optimizer): + def __init__( + self, + params, + lr = 1e-4, + betas: tuple[float, float] = (0.9, 0.99), + weight_decay = 0., + regen_reg_rate = 0., + decoupled_wd = False, + cautious_wd = False, + cautious_factor = 1., # set to 0. for zeroing out any updates not in same direction as gradient as in https://arxiv.org/abs/2411.16085 + a = 1.27, + b = 1. + ): + assert lr > 0. + assert all([0. <= beta <= 1. for beta in betas]) + assert weight_decay >= 0. + assert regen_reg_rate >= 0. + assert not (weight_decay > 0. and regen_reg_rate > 0.) + assert 0. <= cautious_factor <= 1. + + self._init_lr = lr + self.decoupled_wd = decoupled_wd + + defaults = dict( + lr = lr, + betas = betas, + a = a, + b = b, + weight_decay = weight_decay, + cautious_wd = cautious_wd, + regen_reg_rate = regen_reg_rate, + cautious_factor = cautious_factor + ) + + super().__init__(params, defaults) + + # independent of lr + + if decoupled_wd: + for group in self.param_groups: + group['weight_decay'] /= lr + group['regen_reg_rate'] /= lr + + @torch.no_grad() + def step( + self, + closure: Callable | None = None + ): + + loss = None + if exists(closure): + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + for p in filter(lambda p: exists(p.grad), group['params']): + + grad, lr, wd, regen_rate, cautious_wd, cautious_factor, beta1, beta2, a, b, state, init_lr = p.grad, group['lr'], group['weight_decay'], group['regen_reg_rate'], group['cautious_wd'], group['cautious_factor'], *group['betas'], group['a'], group['b'], self.state[p], self._init_lr + + # regenerative regularization from Kumar et al. https://arxiv.org/abs/2308.11958 + + if regen_rate > 0. and 'param_init' in state: + param_init = state['param_init'] + p.lerp_(param_init, lr * regen_rate) + + # init state if needed + + if len(state) == 0: + state['steps'] = 0 + state['exp_avg'] = torch.zeros_like(grad) + state['exp_avg_sq'] = torch.zeros_like(grad) + + if regen_rate > 0.: + state['param_init'] = p.clone() + + # get some of the states + + exp_avg, exp_avg_sq, steps = state['exp_avg'], state['exp_avg_sq'], state['steps'] + + steps += 1 + + # bias corrections + + bias_correct1 = 1. - beta1 ** steps + bias_correct2 = 1. - beta2 ** steps + + # decay running averages + + exp_avg.lerp_(grad, 1. - beta1) + exp_avg_sq.lerp_(grad * grad, 1. - beta2) + + # the following line is the proposed change to the update rule + # using atan2 instead of a division with epsilon in denominator + # a * atan2(exp_avg / bias_correct1, b * sqrt(exp_avg_sq / bias_correct2)) + + den = exp_avg_sq.mul(b * b / bias_correct2).sqrt_() + update = exp_avg.mul(1. / bias_correct1).atan2_(den) + + # maybe cautious update - algorithm 2 in https://arxiv.org/abs/2411.16085 + + if cautious_factor < 1.: + align_mask = (update * grad) > 0 + scale = torch.where(align_mask, torch.ones_like(grad), cautious_factor) + update *= (scale / scale.mean().clamp(min = 1e-5)) + + # maybe weight decay + + if wd > 0.: + # maybe cautious + # https://arxiv.org/abs/2510.12402 + + wd_mask = (update * p > 0).float() if cautious_wd else 1. + + p.mul_(1. - lr * wd * wd_mask) + + # update parameters + + p.add_(update, alpha = -lr * a) + + # increment steps + + state['steps'] = steps + + return loss diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2_clip_grok.py b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2_clip_grok.py new file mode 100644 index 0000000000000000000000000000000000000000..3919c47a5726120b8ab91346076695f86f394668 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2_clip_grok.py @@ -0,0 +1,162 @@ +from __future__ import annotations +from typing import Callable + +import torch +from torch import atan2, sqrt +from torch.optim.optimizer import Optimizer + +# functions + +def exists(val): + return val is not None + +# clip to grok - Volchkov et al. + +def softclamp(t, value): + return (t / value).tanh() * value + +def soft_clip_max_norm(weights, max_norm, dim, eps = 1e-5): + assert max_norm > 1. + shift, scale = (max_norm + 1.) * 0.5, (max_norm - 1.) * 0.5 + + norm = weights.norm(dim = dim, p = 2, keepdim = True) + softclamped_norm = softclamp(norm - shift, scale) + shift + + return weights / softclamped_norm.clamp_min(eps) + +# class + +class AdamAtan2ClipGrok(Optimizer): + def __init__( + self, + params, + lr = 1e-4, + betas: tuple[float, float] = (0.9, 0.99), + weight_decay = 0., + regen_reg_rate = 0., + decoupled_wd = False, + cautious_wd = False, + cautious_factor = 1., # set to 0. for zeroing out any updates not in same direction as gradient as in https://arxiv.org/abs/2411.16085 + clip_to_grok = True, + clip_to_grok_max_norm = 2.0, + a = 1.27, + b = 1. + ): + assert lr > 0. + assert all([0. <= beta <= 1. for beta in betas]) + assert weight_decay >= 0. + assert regen_reg_rate >= 0. + assert not (weight_decay > 0. and regen_reg_rate > 0.) + assert 0. <= cautious_factor <= 1. + + self._init_lr = lr + self.decoupled_wd = decoupled_wd + + defaults = dict( + lr = lr, + betas = betas, + a = a, + b = b, + weight_decay = weight_decay, + cautious_wd = cautious_wd, + regen_reg_rate = regen_reg_rate, + cautious_factor = cautious_factor, + clip_to_grok = clip_to_grok, + clip_to_grok_max_norm = clip_to_grok_max_norm + ) + + super().__init__(params, defaults) + + # independent of lr + + if decoupled_wd: + for group in self.param_groups: + group['weight_decay'] /= lr + group['regen_reg_rate'] /= lr + + @torch.no_grad() + def step( + self, + closure: Callable | None = None + ): + + loss = None + if exists(closure): + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + for p in filter(lambda p: exists(p.grad), group['params']): + + grad, lr, wd, regen_rate, cautious_wd, cautious_factor, clip_to_grok, clip_to_grok_max_norm, beta1, beta2, a, b, state, init_lr = p.grad, group['lr'], group['weight_decay'], group['regen_reg_rate'], group['cautious_wd'], group['cautious_factor'], group['clip_to_grok'], group['clip_to_grok_max_norm'], *group['betas'], group['a'], group['b'], self.state[p], self._init_lr + + # regenerative regularization from Kumar et al. https://arxiv.org/abs/2308.11958 + + if regen_rate > 0. and 'param_init' in state: + param_init = state['param_init'] + p.lerp_(param_init, lr * regen_rate) + + # init state if needed + + if len(state) == 0: + state['steps'] = 0 + state['exp_avg'] = torch.zeros_like(grad) + state['exp_avg_sq'] = torch.zeros_like(grad) + + if regen_rate > 0.: + state['param_init'] = p.clone() + + # get some of the states + + exp_avg, exp_avg_sq, steps = state['exp_avg'], state['exp_avg_sq'], state['steps'] + + steps += 1 + + # bias corrections + + bias_correct1 = 1. - beta1 ** steps + bias_correct2 = 1. - beta2 ** steps + + # decay running averages + + exp_avg.lerp_(grad, 1. - beta1) + exp_avg_sq.lerp_(grad * grad, 1. - beta2) + + # the following line is the proposed change to the update rule + # using atan2 instead of a division with epsilon in denominator + # a * atan2(exp_avg / bias_correct1, b * sqrt(exp_avg_sq / bias_correct2)) + + den = exp_avg_sq.mul(b * b / bias_correct2).sqrt_() + update = exp_avg.mul(1. / bias_correct1).atan2_(den) + + # maybe cautious update - algorithm 2 in https://arxiv.org/abs/2411.16085 + + if cautious_factor < 1.: + align_mask = (update * grad) > 0 + scale = torch.where(align_mask, torch.ones_like(grad), cautious_factor) + update *= (scale / scale.mean().clamp(min = 1e-5)) + + # maybe weight decay + + if wd > 0.: + # maybe cautious + # https://arxiv.org/abs/2510.12402 + + wd_mask = (update * p > 0).float() if cautious_wd else 1. + + p.mul_(1. - lr * wd * wd_mask) + + # update parameters + + p.add_(update, alpha = -lr * a) + + # clip to grok - Volchkov et al. from Clip to Grok + + if clip_to_grok and p.dim() >= 2: + p.data.copy_(soft_clip_max_norm(p.data, max_norm = clip_to_grok_max_norm, dim = -1)) + + # increment steps + + state['steps'] = steps + + return loss diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2_with_orthog_grad.py b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2_with_orthog_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..94604a1167a9456e59705020b7fb8ba048402230 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2_with_orthog_grad.py @@ -0,0 +1,212 @@ +from __future__ import annotations +from typing import Callable + +import torch +from torch import atan2, sqrt +import torch.nn.functional as F +from torch.optim.optimizer import Optimizer + +# functions + +def exists(val): + return val is not None + +# tensor helpers + +def orthog_proj(x, y, double_precision = False): + assert x.shape == y.shape + shape = x.shape + + x, y = x.flatten(), y.flatten() + + if double_precision: + dtype = x.dtype + x, y = x.double(), y.double() + + unit = F.normalize(y, dim = -1) + + parallel = (x * unit).sum(dim = -1, keepdim = True) * unit + orthogonal = x - parallel + + out = orthogonal.reshape(*shape) + + if double_precision: + out = out.to(dtype) + + return out + +# class + +class AdamAtan2(Optimizer): + def __init__( + self, + params, + lr = 1e-4, + betas: tuple[float, float] = (0.9, 0.99), + weight_decay = 0., + regen_reg_rate = 0., + orig_grad_ema_beta = 0.9, + orthog_grad = True, + orthog_proj_double_precision = True, + decoupled_wd = False, + cautious_wd = False, + cautious_factor = 1., # set to 0. for zeroing out any updates not in same direction as gradient as in https://arxiv.org/abs/2411.16085 + a = 1.27, + b = 1. + ): + assert lr > 0. + assert all([0. <= beta <= 1. for beta in betas]) + assert weight_decay >= 0. + assert regen_reg_rate >= 0. + assert not (weight_decay > 0. and regen_reg_rate > 0.) + assert 0. <= cautious_factor <= 1. + + self._init_lr = lr + self.decoupled_wd = decoupled_wd + + defaults = dict( + lr = lr, + betas = betas, + a = a, + b = b, + weight_decay = weight_decay, + regen_reg_rate = regen_reg_rate, + orthog_grad = orthog_grad, + orig_grad_ema_beta = orig_grad_ema_beta, + orthog_proj_double_precision = orthog_proj_double_precision, + cautious_wd = cautious_wd, + cautious_factor = cautious_factor + ) + + super().__init__(params, defaults) + + # independent of lr + + if decoupled_wd: + for group in self.param_groups: + group['weight_decay'] /= lr + group['regen_reg_rate'] /= lr + + # resetting the ema of the original grad, say at the boundary of a new video or trajectory, or could even be determined by the uncertainty of some predictive module + + @torch.no_grad() + def reset_( + self, + key = None + ): + for group in self.param_groups: + for p in group['params']: + state = self.state[p] + + if 'grad_emas' not in state: + continue + + if not exists(key): + state['grad_emas'].clear() + elif key in state['grad_emas']: + state['grad_emas'][key].zero_() + + @torch.no_grad() + def step( + self, + closure: Callable | None = None, + store_grad_key: str | None = 'orig_grad', + orthog_against_key: str | None = 'orig_grad' + ): + + loss = None + if exists(closure): + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + for p in filter(lambda p: exists(p.grad), group['params']): + + grad, lr, wd, regen_rate, orthog_grad, orig_grad_ema_beta, orthog_proj_double_precision, cautious_wd, cautious_factor, beta1, beta2, a, b, state, init_lr = p.grad, group['lr'], group['weight_decay'], group['regen_reg_rate'], group['orthog_grad'], group['orig_grad_ema_beta'], group['orthog_proj_double_precision'], group['cautious_wd'], group['cautious_factor'], *group['betas'], group['a'], group['b'], self.state[p], self._init_lr + + # regenerative regularization from Kumar et al. https://arxiv.org/abs/2308.11958 + + if regen_rate > 0. and 'param_init' in state: + param_init = state['param_init'] + p.lerp_(param_init, lr * regen_rate) + + # init state if needed + + if len(state) == 0: + state['steps'] = 0 + + state['exp_avg'] = torch.zeros_like(grad) + state['exp_avg_sq'] = torch.zeros_like(grad) + state['grad_emas'] = dict() + + if regen_rate > 0.: + state['param_init'] = p.clone() + + # get some of the states + + exp_avg, exp_avg_sq, steps = state['exp_avg'], state['exp_avg_sq'], state['steps'] + + steps += 1 + + # orthogonal gradients for decorrelating successive gradient updates + # e.g. for learning on temporal streams (https://arxiv.org/abs/2504.01961) + # or auxiliary RL losses to prevent clashing between representation learning and policy gradients + + if orthog_grad: + new_grad = grad + grad_emas = state['grad_emas'] + + if exists(orthog_against_key) and orthog_against_key in grad_emas: + new_grad = orthog_proj(grad, grad_emas[orthog_against_key], double_precision = orthog_proj_double_precision) + + if exists(store_grad_key): + if store_grad_key not in grad_emas: + grad_emas[store_grad_key] = torch.zeros_like(grad) + + grad_emas[store_grad_key].lerp_(grad, 1. - orig_grad_ema_beta) + + grad = new_grad + + # bias corrections + + bias_correct1 = 1. - beta1 ** steps + bias_correct2 = 1. - beta2 ** steps + + # decay running averages + + exp_avg.lerp_(grad, 1. - beta1) + exp_avg_sq.lerp_(grad * grad, 1. - beta2) + + # the following line is the proposed change to the update rule + # using atan2 instead of a division with epsilon in denominator + # a * atan2(exp_avg / bias_correct1, b * sqrt(exp_avg_sq / bias_correct2)) + + den = exp_avg_sq.mul(b * b / bias_correct2).sqrt_() + update = exp_avg.mul(1. / bias_correct1).atan2_(den) + + # maybe cautious update - algorithm 2 in https://arxiv.org/abs/2411.16085 + + if cautious_factor < 1.: + align_mask = (update * grad) > 0 + scale = torch.where(align_mask, torch.ones_like(grad), cautious_factor) + update *= (scale / scale.mean().clamp(min = 1e-5)) + + # maybe weight decay + + if wd > 0.: + # maybe cautious + # https://arxiv.org/abs/2510.12402 + + wd_mask = (update * p > 0).float() if cautious_wd else 1. + + p.mul_(1. - lr * wd * wd_mask) + + # update parameters + + p.add_(update, alpha = -lr * a) + + # increment steps + + state['steps'] = steps + + return loss diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2_with_wasserstein_reg.py b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2_with_wasserstein_reg.py new file mode 100644 index 0000000000000000000000000000000000000000..1a922da99550ee92c094b8eed57f3a20552bcdaa --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adam_atan2_with_wasserstein_reg.py @@ -0,0 +1,141 @@ +from __future__ import annotations +from typing import Callable + +import torch +from torch import atan2, sqrt +from torch.optim.optimizer import Optimizer + +# functions + +def exists(val): + return val is not None + +# class + +class AdamAtan2(Optimizer): + def __init__( + self, + params, + lr = 1e-4, + betas: tuple[float, float] = (0.9, 0.99), + weight_decay = 0., + regen_reg_rate = 0., + decoupled_wd = False, + a = 1.27, + b = 1. + ): + assert lr > 0. + assert all([0. <= beta <= 1. for beta in betas]) + assert weight_decay >= 0. + assert regen_reg_rate >= 0. + assert not (weight_decay > 0. and regen_reg_rate > 0.) + + self._init_lr = lr + self.decoupled_wd = decoupled_wd + + defaults = dict( + lr = lr, + betas = betas, + a = a, + b = b, + weight_decay = weight_decay, + regen_reg_rate = regen_reg_rate, + ) + + super().__init__(params, defaults) + + @torch.no_grad() + def step( + self, + closure: Callable | None = None + ): + + loss = None + if exists(closure): + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + for p in filter(lambda p: exists(p.grad), group['params']): + + grad, lr, wd, regen_rate, beta1, beta2, a, b, state, init_lr = p.grad, group['lr'], group['weight_decay'], group['regen_reg_rate'], *group['betas'], group['a'], group['b'], self.state[p], self._init_lr + + # maybe decoupled weight decay + + if self.decoupled_wd: + wd /= init_lr + + # weight decay + + if wd > 0.: + p.mul_(1. - lr * wd) + + # regenerative regularization from Kumar et al. https://arxiv.org/abs/2308.11958 + + if regen_rate > 0. and 'param_init' in state: + param_init = state['param_init'] + + shape = param_init.shape + + # wasserstein compares using ordered statistics, iiuc + + indices = p.flatten().sort(dim = -1).indices + indices = indices.argsort(dim = -1) + + target = param_init.flatten()[indices] + target = target.reshape(shape) + + p.lerp_(target, lr / init_lr * regen_rate) + + # init state if needed + + if len(state) == 0: + state['steps'] = 0 + state['exp_avg'] = torch.zeros_like(grad) + state['exp_avg_sq'] = torch.zeros_like(grad) + + if regen_rate > 0.: + + # wasserstein reg - https://arxiv.org/abs/2406.06811v1 + # initial parameters sorted for efficiency + + shape = p.shape + sorted_p = p.flatten().sort(dim = -1).values + sorted_p = sorted_p.reshape(shape) + + state['param_init'] = sorted_p.clone() + + # get some of the states + + exp_avg, exp_avg_sq, steps = state['exp_avg'], state['exp_avg_sq'], state['steps'] + + steps += 1 + + # bias corrections + + bias_correct1 = 1. - beta1 ** steps + bias_correct2 = 1. - beta2 ** steps + + # decay running averages + + exp_avg.lerp_(grad, 1. - beta1) + exp_avg_sq.lerp_(grad * grad, 1. - beta2) + + # the following line is the proposed change to the update rule + # using atan2 instead of a division with epsilon in denominator + # a * atan2(exp_avg / bias_correct1, b * sqrt(exp_avg_sq / bias_correct2)) + + den = exp_avg_sq.mul(b * b / bias_correct2).sqrt_() + update = exp_avg.mul(1. / bias_correct1).atan2_(den) + + # update parameters + + p.add_(update, alpha = -lr * a) + + # increment steps + + state['steps'] = steps + + return loss + +Adam = AdamAtan2 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adopt.py b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adopt.py new file mode 100644 index 0000000000000000000000000000000000000000..86f6be5f4731a7aff99033c4682bba7e4e902383 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adopt.py @@ -0,0 +1,117 @@ +from __future__ import annotations +from typing import Callable + +import torch +from torch import atan2, sqrt +from torch.optim.optimizer import Optimizer + +# functions + +def exists(val): + return val is not None + +# class + +class Adopt(Optimizer): + """ + the proposed Adam substitute from University of Tokyo + + Algorithm 3 in https://arxiv.org/abs/2411.02853 + """ + + def __init__( + self, + params, + lr = 1e-4, + betas: tuple[float, float] = (0.9, 0.99), + eps = 1e-6, + weight_decay = 0., + decoupled_wd = True + ): + assert lr > 0. + assert all([0. <= beta <= 1. for beta in betas]) + assert weight_decay >= 0. + + self._init_lr = lr + self.decoupled_wd = decoupled_wd + + defaults = dict( + lr = lr, + betas = betas, + eps = eps, + weight_decay = weight_decay, + ) + + super().__init__(params, defaults) + + @torch.no_grad() + def step( + self, + closure: Callable | None = None + ): + + loss = None + if exists(closure): + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + for p in filter(lambda p: exists(p.grad), group['params']): + + grad, lr, wd, beta1, beta2, eps, state, init_lr = p.grad, group['lr'], group['weight_decay'], *group['betas'], group['eps'], self.state[p], self._init_lr + + # maybe decoupled weight decay + + if self.decoupled_wd: + wd /= init_lr + + # weight decay + + if wd > 0.: + p.mul_(1. - lr * wd) + + # init state if needed + + if len(state) == 0: + state['steps'] = 0 + state['m'] = torch.zeros_like(grad) + state['v'] = grad * grad + + # get some of the states + + m, v, steps = state['m'], state['v'], state['steps'] + + # for the first step do nothing + + if steps == 0: + state['steps'] += 1 + continue + + # calculate m + + grad_sq = grad * grad + + update = grad.div(v.sqrt().clamp(min = eps)) # they claim that a max(value, eps) performs better than adding the epsilon + + # clip with t ^ 0.25 as in Algorithm 3 + + clip_value = steps ** 0.25 + update.clamp_(min = -clip_value, max = clip_value) + + # update m + + m.lerp_(update, 1. - beta1) + + # then update parameters + + p.add_(m, alpha = -lr) + + # update exp grad sq (v) + + v.lerp_(grad_sq, 1. - beta2) + + # increment steps + + state['steps'] += 1 + + return loss diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adopt_atan2.py b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adopt_atan2.py new file mode 100644 index 0000000000000000000000000000000000000000..2947ded25de3d8a5d47990babaf822952d6dfb84 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/adopt_atan2.py @@ -0,0 +1,136 @@ +from __future__ import annotations +from typing import Callable + +import torch +from torch import atan2, sqrt +from torch.optim.optimizer import Optimizer + +# functions + +def exists(val): + return val is not None + +# class + +class AdoptAtan2(Optimizer): + """ + the proposed Adam substitute from University of Tokyo + combined with the proposed atan2 method for ridding of the eps from Google + + Algorithm 3 in https://arxiv.org/abs/2411.02853 + """ + + def __init__( + self, + params, + lr = 1e-4, + betas: tuple[float, float] = (0.9, 0.99), + weight_decay = 0., + regen_reg_rate = 0., + decoupled_wd = True, + cautious_factor = 1., # set to 0. for zeroing out any updates not in same direction as gradient as in https://arxiv.org/abs/2411.16085 + a = 1.27, + b = 1. + ): + assert lr > 0. + assert all([0. <= beta <= 1. for beta in betas]) + assert weight_decay >= 0. + assert not (weight_decay > 0. and regen_reg_rate > 0.) + + self._init_lr = lr + self.decoupled_wd = decoupled_wd + + defaults = dict( + lr = lr, + betas = betas, + a = a, + b = b, + weight_decay = weight_decay, + regen_reg_rate = regen_reg_rate, + cautious_factor = cautious_factor + ) + + super().__init__(params, defaults) + + @torch.no_grad() + def step( + self, + closure: Callable | None = None + ): + + loss = None + if exists(closure): + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + for p in filter(lambda p: exists(p.grad), group['params']): + + grad, lr, wd, regen_rate, cautious_factor, beta1, beta2, a, b, state, init_lr = p.grad, group['lr'], group['weight_decay'], group['regen_reg_rate'], group['cautious_factor'], *group['betas'], group['a'], group['b'], self.state[p], self._init_lr + + # maybe decoupled weight decay + + if self.decoupled_wd: + wd /= init_lr + + # regenerative regularization from Kumar et al. https://arxiv.org/abs/2308.11958 + + if regen_rate > 0. and 'param_init' in state: + param_init = state['param_init'] + p.lerp_(param_init, lr / init_lr * regen_rate) + + # weight decay + + if wd > 0.: + p.mul_(1. - lr * wd) + + # init state if needed + + if len(state) == 0: + state['steps'] = 0 + state['m'] = torch.zeros_like(grad) + state['v'] = grad * grad + + if regen_rate > 0.: + state['param_init'] = p.clone() + + # get some of the states + + m, v, steps = state['m'], state['v'], state['steps'] + + # for the first step do nothing + + if steps == 0: + state['steps'] += 1 + continue + + # maybe cautious update - algorithm 2 in https://arxiv.org/abs/2411.16085 + + scale = 1. + + if cautious_factor < 1.: + align_mask = (m * grad) > 0 + scale = torch.where(align_mask, torch.ones_like(grad), cautious_factor) + scale /= scale.mean().clamp(min = 1e-5) + + # calculate m + + grad_sq = grad * grad + + update = grad.atan2(b * v.sqrt()) + + m.lerp_(update, 1. - beta1) + + # then update parameters + + p.add_(m * scale, alpha = -lr * a) + + # update exp grad sq (v) + + v.lerp_(grad_sq, 1. - beta2) + + # increment steps + + state['steps'] += 1 + + return loss diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/foreach.py b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/foreach.py new file mode 100644 index 0000000000000000000000000000000000000000..426f99461afb5a1d542b509c9d349886a8dd2e7b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/foreach.py @@ -0,0 +1,172 @@ +from __future__ import annotations +from typing import Callable + +import torch +from torch import atan2, sqrt, Tensor +from torch.optim.optimizer import Optimizer + +# functions + +def exists(val): + return val is not None + +def default(*args): + for arg in args: + if exists(arg): + return arg + return None + +# slow foreach atan2 + +def slow_foreach_atan2_(nums: list[Tensor], dens: list[Tensor]): + for num, den, in zip(nums, dens): + num.atan2_(den) + +# class + +class AdamAtan2(Optimizer): + def __init__( + self, + params, + lr = 1e-4, + betas: tuple[float, float] = (0.9, 0.99), + weight_decay = 0., + regen_reg_rate = 0., + decoupled_wd = False, + a = 1.27, + b = 1., + foreach_atan2_fn: Callable | None = None + ): + assert lr > 0. + assert all([0. <= beta <= 1. for beta in betas]) + assert weight_decay >= 0. + assert regen_reg_rate >= 0. + assert not (weight_decay > 0. and regen_reg_rate > 0.) + assert all([hasattr(torch, f'_foreach_{attr}_') for attr in ('mul', 'add', 'lerp', 'sqrt')]), 'this version of torch does not have the prerequisite foreach functions' + + self._init_lr = lr + self.decoupled_wd = decoupled_wd + + self._foreach_atan2_ = default( + foreach_atan2_fn, + getattr(torch, '_foreach_atan2_', None), + slow_foreach_atan2_ + ) + + defaults = dict( + lr = lr, + betas = betas, + a = a, + b = b, + weight_decay = weight_decay, + regen_reg_rate = regen_reg_rate + ) + + super().__init__(params, defaults) + + @torch.no_grad() + def step( + self, + closure: Callable | None = None + ): + init_lr = self._init_lr + + loss = None + if exists(closure): + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + + wd, regen_rate, lr, beta1, beta2, a, b = group['weight_decay'], group['regen_reg_rate'], group['lr'], *group['betas'], group['a'], group['b'] + + has_weight_decay = wd > 0 + + if self.decoupled_wd and has_weight_decay: + wd /= init_lr + + has_regenerative_reg = regen_rate > 0 + + # accumulate List[Tensor] for foreach inplace updates + + params = [] + params_init = [] + grads = [] + grad_squared = [] + exp_avgs = [] + exp_avg_sqs = [] + bias_correct1 = [] + bias_correct2 = [] + + for p in filter(lambda p: exists(p.grad), group['params']): + + grad, state = p.grad, self.state[p] + + # init state if needed + + if len(state) == 0: + state['steps'] = 0 + state['exp_avg'] = torch.zeros_like(grad) + state['exp_avg_sq'] = torch.zeros_like(grad) + state['param_init'] = p.clone() + + # get some of the states + + exp_avg, exp_avg_sq, param_init, steps = state['exp_avg'], state['exp_avg_sq'], state['param_init'], state['steps'] + + steps += 1 + + # bias corrections + + bias_correct1.append(1. / (1. - beta1 ** steps)) + bias_correct2.append(b * b / (1. - beta2 ** steps)) + + # append to list + + params.append(p) + params_init.append(param_init) + grads.append(grad) + grad_squared.append(grad * grad) + exp_avgs.append(exp_avg) + exp_avg_sqs.append(exp_avg_sq) + + # update steps + + state['steps'] = steps + + # weight decay + + if has_weight_decay: + torch._foreach_mul_(params, 1. - lr * wd) + + # regenerative regularization + + if has_regenerative_reg: + torch._foreach_lerp_(params, params_init, lr / init_lr * regen_rate) + + # decay running averages + + torch._foreach_lerp_(exp_avgs, grads, 1. - beta1) + torch._foreach_lerp_(exp_avg_sqs, grad_squared, 1. - beta2) + + # clone for update + + updates = [t.clone() for t in exp_avgs] + den = [t.clone() for t in exp_avg_sqs] + + # calculate update atan2(exp_avg / bias_correct1, b * sqrt(exp_avg_sq / bias_correct2)) + + torch._foreach_mul_(updates, bias_correct1) + + torch._foreach_mul_(den, bias_correct2) + torch._foreach_sqrt_(den) + + self._foreach_atan2_(updates, den) + + # update params + + torch._foreach_add_(params, updates, alpha = -lr * a) + + return loss + +Adam = AdamAtan2 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/muon_adam_atan2.py b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/muon_adam_atan2.py new file mode 100644 index 0000000000000000000000000000000000000000..868831b9add35f59f9daf65e3cb27782340ee470 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/muon_adam_atan2.py @@ -0,0 +1,241 @@ +from __future__ import annotations +import math +from typing import Callable + +import torch +from torch import atan2, sqrt +from torch.optim.optimizer import Optimizer + +from einops import pack, unpack + +# functions + +def exists(val): + return val is not None + +def default(val, d): + return val if exists(val) else d + +# muon related + +def newtonschulz5( + t, + steps = 5, + eps = 1e-7, + coefs = (3.4445, -4.7750, 2.0315), + bypass_update_fn: Callable[[int], bool] | None = None +): + if exists(bypass_update_fn) and bypass_update_fn(t.ndim): + return t + + shape = t.shape + should_transpose = shape[-2] > shape[-1] + + if should_transpose: + t = t.transpose(-1, -2) + + t, packed_shape = pack([t], '* i j') + t = t / t.norm(dim = (-1, -2), keepdim = True).clamp(min = eps) + + a, b, c = coefs + + for _ in range(steps): + A = t @ t.transpose(-1, -2) + B = b * A + c * A @ A + t = a * t + B @ t + + t, = unpack(t, packed_shape, '* i j') + + if should_transpose: + t = t.transpose(-1, -2) + + return t + +# class + +class MuonAdamAtan2(Optimizer): + def __init__( + self, + muon_params, + params, + lr = 1e-4, + muon_lr = None, + betas: tuple[float, float] = (0.9, 0.99), + weight_decay = 0., + regen_reg_rate = 0., + decoupled_wd = False, + cautious_factor = 1., # set to 0. for zeroing out any updates not in same direction as gradient as in https://arxiv.org/abs/2411.16085 + a = 1.27, + b = 1., + muon_rms_factor = 0.2, + muon_steps = 5, + muon_beta1 = 0.95, + muon_newton_schulz5_coefs = (3.4445, -4.7750, 2.0315), + muon_eps = 1e-7, + muon_bypass_update_fn: Callable[[int], bool] | None = lambda ndim: ndim < 2 or ndim > 3, + remove_muon_params_from_params = True + ): + assert lr > 0. + assert all([0. <= beta <= 1. for beta in betas]) + assert weight_decay >= 0. + assert regen_reg_rate >= 0. + assert not (weight_decay > 0. and regen_reg_rate > 0.) + assert 0. <= cautious_factor <= 1. + + self._init_lr = lr + + muon_lr = default(muon_lr, lr) + self._init_muon_lr = muon_lr + + self.decoupled_wd = decoupled_wd + + beta1, beta2 = betas + + self.muon_bypass_update_fn = muon_bypass_update_fn + + defaults = dict( + lr = lr, + beta1 = beta1, + beta2 = beta2, + a = a, + b = b, + weight_decay = weight_decay, + regen_reg_rate = regen_reg_rate, + cautious_factor = cautious_factor, + use_muon = False, + muon_steps = muon_steps, + muon_newton_schulz5_coefs = muon_newton_schulz5_coefs, + muon_eps = muon_eps, + muon_rms_factor = muon_rms_factor, + ) + + if remove_muon_params_from_params: + params = list(set(params) - set(muon_params)) + + param_groups = [ + dict(params = params, lr = lr), + dict(params = muon_params, lr = muon_lr, beta1 = muon_beta1, rms_factor = muon_rms_factor, use_muon = True) + ] + + super().__init__(param_groups, defaults) + + @torch.no_grad() + def step( + self, + closure: Callable | None = None + ): + + loss = None + if exists(closure): + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + + for p in filter(lambda p: exists(p.grad), group['params']): + + use_muon = group['use_muon'] + + grad, lr, wd, regen_rate, cautious_factor, beta1, beta2, a, b, state, init_lr, init_muon_lr = p.grad, group['lr'], group['weight_decay'], group['regen_reg_rate'], group['cautious_factor'], group['beta1'], group['beta2'], group['a'], group['b'], self.state[p], self._init_lr, self._init_muon_lr + + param_init_lr = init_lr if not use_muon else init_muon_lr + + # set lr scale to 1. if muon update + + if use_muon: + a = 1. + + # maybe decoupled weight decay + + if self.decoupled_wd: + wd /= param_init_lr + + # weight decay + + if wd > 0.: + p.mul_(1. - lr * wd) + + # regenerative regularization from Kumar et al. https://arxiv.org/abs/2308.11958 + + if regen_rate > 0. and 'param_init' in state: + param_init = state['param_init'] + p.lerp_(param_init, lr / init_lr * regen_rate) + + # init state if needed + + if len(state) == 0: + state['steps'] = 0 + state['exp_avg'] = torch.zeros_like(grad) + + if not use_muon: + state['exp_avg_sq'] = torch.zeros_like(grad) + + if regen_rate > 0.: + state['param_init'] = p.clone() + + # get some of the states + + exp_avg, steps = state['exp_avg'], state['steps'] + + steps += 1 + + # bias corrections + + bias_correct1 = 1. - beta1 ** steps + + if not use_muon: + exp_avg_sq = state['exp_avg_sq'] + bias_correct2 = 1. - beta2 ** steps + + # decay running averages + + exp_avg.lerp_(grad, 1. - beta1) + + if not use_muon: + exp_avg_sq.lerp_(grad * grad, 1. - beta2) + + # the following line is the proposed change to the update rule + # using atan2 instead of a division with epsilon in denominator + # a * atan2(exp_avg / bias_correct1, b * sqrt(exp_avg_sq / bias_correct2)) + + den = exp_avg_sq.mul(b * b / bias_correct2).sqrt_() + update = exp_avg.mul(1. / bias_correct1).atan2_(den) + + # maybe cautious update - algorithm 2 in https://arxiv.org/abs/2411.16085 + else: + + muon_steps, muon_coefs, muon_eps, muon_rms_factor = group['muon_steps'], group['muon_newton_schulz5_coefs'], group['muon_eps'], group['muon_rms_factor'] + muon_bypass_update_fn = group.get('muon_bypass_update_fn', self.muon_bypass_update_fn) + + # Muon from Keller Jordan + # https://kellerjordan.github.io/posts/muon/ + + update = newtonschulz5( + exp_avg, + steps = muon_steps, + coefs = muon_coefs, + eps = muon_eps, + bypass_update_fn = muon_bypass_update_fn + ) + + # incorporate the match adam RMS from Kimi team + # https://kexue.fm/archives/11267 + + muon_update_scale = math.sqrt(max(exp_avg.shape[-2:])) * muon_rms_factor + + update = update * muon_update_scale + + if cautious_factor < 1.: + align_mask = (update * grad) > 0 + scale = torch.where(align_mask, torch.ones_like(grad), cautious_factor) + update *= (scale / scale.mean().clamp(min = 1e-5)) + + # update parameters + + p.add_(update, alpha = -lr * a) + + # increment steps + + state['steps'] = steps + + return loss diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/polar_adam_atan2.py b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/polar_adam_atan2.py new file mode 100644 index 0000000000000000000000000000000000000000..52505eae0a06aba37b15317be32c6345caf1f564 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/adam_atan2_pytorch/polar_adam_atan2.py @@ -0,0 +1,274 @@ +from __future__ import annotations +import math +from typing import Callable + +import torch +from torch import atan2, sqrt +from torch.optim.optimizer import Optimizer + +from einops import pack, unpack +from itertools import repeat + +# functions + +def exists(val): + return val is not None + +def default(val, d): + return val if exists(val) else d + +def transpose(t): + return t.transpose(-1, -2) + +# polar express variant +# https://arxiv.org/abs/2505.14387 + +POLAR_EXPRESS_COEFS = [ + (8.28721201814563, -23.595886519098837, 17.300387312530933), + (4.107059111542203, -2.9478499167379106, 0.5448431082926601), + (3.9486908534822946, -2.908902115962949, 0.5518191394370137), + (3.3184196573706015, -2.488488024314874, 0.51004894012372), + (2.300652019954817, -1.6689039845747493, 0.4188073119525673), + (1.891301407787398, -1.2679958271945868, 0.37680408948524835), + (1.8750014808534479, -1.2500016453999487, 0.3750001645474248), + (1.875, -1.25, 0.375), # subsequent coeffs equal this numerically +] + +# safety factor for numerical stability (but exclude last polynomial ) +POLAR_EXPRESS_COEFS = [(a / 1.01, b / 1.01**3, c / 1.01**5) for (a, b, c) in POLAR_EXPRESS_COEFS[:-1]] + [POLAR_EXPRESS_COEFS[-1]] + +def polar_express( + t, + steps = 5, + coefs = POLAR_EXPRESS_COEFS, + cast_bfloat16 = False, + eps = 1e-7, + bypass_update_fn: Callable[[int], bool] | None = None +): + if exists(bypass_update_fn) and bypass_update_fn(t.ndim): + return t + + shape = t.shape + should_transpose = shape[-2] > shape[-1] + + if should_transpose: + t = transpose(t) + + t, packed_shape = pack([t], '* i j') + + orig_dtype = t.dtype + + if cast_bfloat16: + t = t.bfloat16() + + t = t / t.norm(dim = (-1, -2), keepdim = True).clamp(min = eps) + t = t / 1.01 + + hs = coefs[:steps] + list(repeat(coefs[-1], max(0, steps - len(coefs)))) + + for a, b, c in hs: + A = t @ transpose(t) + B = b * A + c * A @ A + t = a * t + B @ t + + t, = unpack(t, packed_shape, '* i j') + + if should_transpose: + t = transpose(t) + + if cast_bfloat16: + t = t.to(orig_dtype) + + return t + +# class + +class PolarAdamAtan2(Optimizer): + def __init__( + self, + polar_params, + params, + lr = 1e-4, + polar_lr = None, + betas: tuple[float, float] = (0.9, 0.99), + weight_decay = 0., + regen_reg_rate = 0., + decoupled_wd = False, + cautious_factor = 1., # set to 0. for zeroing out any updates not in same direction as gradient as in https://arxiv.org/abs/2411.16085 + a = 1.27, + b = 1., + polar_rms_factor = 0.2, + polar_steps = 5, + polar_beta1 = 0.95, + polar_express_coefs = POLAR_EXPRESS_COEFS, + polar_eps = 1e-7, + polar_cast_bfloat16 = False, + polar_bypass_update_fn: Callable[[int], bool] | None = lambda ndim: ndim < 2 or ndim > 3, + remove_polar_params_from_params = True + ): + assert lr > 0. + assert all([0. <= beta <= 1. for beta in betas]) + assert weight_decay >= 0. + assert regen_reg_rate >= 0. + assert not (weight_decay > 0. and regen_reg_rate > 0.) + assert 0. <= cautious_factor <= 1. + + self._init_lr = lr + + polar_lr = default(polar_lr, lr) + self._init_polar_lr = polar_lr + + self.decoupled_wd = decoupled_wd + + beta1, beta2 = betas + + self.polar_bypass_update_fn = polar_bypass_update_fn + + defaults = dict( + lr = lr, + beta1 = beta1, + beta2 = beta2, + a = a, + b = b, + weight_decay = weight_decay, + regen_reg_rate = regen_reg_rate, + cautious_factor = cautious_factor, + use_polar = False, + polar_steps = polar_steps, + polar_express_coefs = polar_express_coefs, + polar_eps = polar_eps, + polar_rms_factor = polar_rms_factor, + polar_cast_bfloat16 = polar_cast_bfloat16, + ) + + if remove_polar_params_from_params: + params = list(set(params) - set(polar_params)) + + param_groups = [ + dict(params = params, lr = lr), + dict(params = polar_params, lr = polar_lr, beta1 = polar_beta1, rms_factor = polar_rms_factor, use_polar = True) + ] + + super().__init__(param_groups, defaults) + + @torch.no_grad() + def step( + self, + closure: Callable | None = None + ): + + loss = None + if exists(closure): + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + + for p in filter(lambda p: exists(p.grad), group['params']): + + use_polar = group.get('use_polar', False) + + grad, lr, wd, regen_rate, cautious_factor, beta1, beta2, a, b, state, init_lr, init_polar_lr = p.grad, group['lr'], group['weight_decay'], group['regen_reg_rate'], group['cautious_factor'], group['beta1'], group['beta2'], group['a'], group['b'], self.state[p], self._init_lr, self._init_polar_lr + + param_init_lr = init_lr if not use_polar else init_polar_lr + + # set lr scale to 1. if polar update + + if use_polar: + a = 1. + + # maybe decoupled weight decay + + if self.decoupled_wd: + wd /= param_init_lr + + # weight decay + + if wd > 0.: + p.mul_(1. - lr * wd) + + # regenerative regularization from Kumar et al. https://arxiv.org/abs/2308.11958 + + if regen_rate > 0. and 'param_init' in state: + param_init = state['param_init'] + p.lerp_(param_init, lr / init_lr * regen_rate) + + # init state if needed + + if len(state) == 0: + state['steps'] = 0 + state['exp_avg'] = torch.zeros_like(grad) + + if not use_polar: + state['exp_avg_sq'] = torch.zeros_like(grad) + + if regen_rate > 0.: + state['param_init'] = p.clone() + + # get some of the states + + exp_avg, steps = state['exp_avg'], state['steps'] + + steps += 1 + + # bias corrections + + bias_correct1 = 1. - beta1 ** steps + + if not use_polar: + exp_avg_sq = state['exp_avg_sq'] + bias_correct2 = 1. - beta2 ** steps + + # decay running averages + + exp_avg.lerp_(grad, 1. - beta1) + + if not use_polar: + exp_avg_sq.lerp_(grad * grad, 1. - beta2) + + # the following line is the proposed change to the update rule + # using atan2 instead of a division with epsilon in denominator + # a * atan2(exp_avg / bias_correct1, b * sqrt(exp_avg_sq / bias_correct2)) + + den = exp_avg_sq.mul(b * b / bias_correct2).sqrt_() + update = exp_avg.mul(1. / bias_correct1).atan2_(den) + + # maybe cautious update - algorithm 2 in https://arxiv.org/abs/2411.16085 + else: + + polar_steps, polar_coefs, polar_eps, polar_rms_factor, polar_cast_bfloat16 = group['polar_steps'], group['polar_express_coefs'], group['polar_eps'], group['polar_rms_factor'], group['polar_cast_bfloat16'] + polar_bypass_update_fn = group.get('polar_bypass_update_fn', self.polar_bypass_update_fn) + + # Polar Express from Amsel et al. + # https://arxiv.org/abs/2505.14387 + + update = polar_express( + exp_avg, + steps = polar_steps, + coefs = polar_coefs, + eps = polar_eps, + cast_bfloat16 = polar_cast_bfloat16, + bypass_update_fn = polar_bypass_update_fn + ) + + # incorporate the match adam RMS from Kimi team + # https://kexue.fm/archives/11267 + + polar_update_scale = math.sqrt(max(exp_avg.shape[-2:])) * polar_rms_factor + + update = update * polar_update_scale + + if cautious_factor < 1.: + align_mask = (update * grad) > 0 + scale = torch.where(align_mask, torch.ones_like(grad), cautious_factor) + update *= (scale / scale.mean().clamp(min = 1e-5)) + + # update parameters + + p.add_(update, alpha = -lr * a) + + # increment steps + + state['steps'] = steps + + return loss diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/INSTALLER b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/METADATA b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0d31a34a53c8f3f9aebe83c63d9675ed4b18b2d1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/METADATA @@ -0,0 +1,341 @@ +Metadata-Version: 2.4 +Name: colorlog +Version: 6.12.0 +Summary: Add colours to the output of Python's logging module. +Home-page: https://github.com/borntyping/python-colorlog +Author: Sam Clements +Author-email: sam@borntyping.co.uk +License: MIT License +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Terminals +Classifier: Topic :: Utilities +Requires-Python: >=3.6 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: colorama; sys_platform == "win32" +Provides-Extra: development +Requires-Dist: black; extra == "development" +Requires-Dist: flake8; extra == "development" +Requires-Dist: mypy; extra == "development" +Requires-Dist: pytest; extra == "development" +Requires-Dist: types-colorama; extra == "development" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-python +Dynamic: summary + +# Log formatting with colors! + +[![](https://img.shields.io/pypi/v/colorlog.svg)](https://pypi.org/project/colorlog/) +[![](https://img.shields.io/pypi/l/colorlog.svg)](https://pypi.org/project/colorlog/) + +Add colours to the output of Python's `logging` module. + +- [Source on GitHub](https://github.com/borntyping/python-colorlog) +- [Package on PyPI](https://pypi.org/pypi/colorlog/) + +## Status + +colorlog currently requires Python 3.6 or higher. Older versions (below 5.x.x) +support Python 2.6 and above. + +- colorlog 6.x requires Python 3.6 or higher. +- colorlog 5.x is an interim version that will warn Python 2 users to downgrade. +- colorlog 4.x is the final version supporting Python 2. + +[colorama] is included as a dependency on Windows, where it is automatically +initialised to support colored output. + +This library is over a decade old and supported a wide set of Python versions +for most of its life, which has made it a difficult library to add new features +to. colorlog 6 may break backwards compatibility so that newer features +can be added more easily, but may still not accept all changes or feature +requests. colorlog 4 might accept essential bugfixes but should not be +considered actively maintained and will not accept any major changes or new +features. + +## Installation + +Install from PyPI with: + +```bash +pip install colorlog +``` + +Several Linux distributions provide official packages ([Debian], [Arch], +[Fedora], [Gentoo], [OpenSuse] and [Ubuntu]), and others have user provided +packages ([BSD ports], [Conda]). + +## Usage + +```python +import colorlog + +handler = colorlog.StreamHandler() +handler.setFormatter(colorlog.ColoredFormatter()) + +logger = colorlog.getLogger('example') +logger.addHandler(handler) +``` + +### Arguments + +`ColoredFormatter` extends [`logging.Formatter`][formatter] and accepts the +following arguments: + +- `fmt` *(default=`None`)*: A format string used to output the message. If + `None`, a default format string is selected based on `style` (e.g. + `%(log_color)s%(levelname)s:%(name)s:%(message)s` for `%` style). +- `datefmt`, `style`, `validate`, `defaults`: see + [`logging.Formatter`][formatter]. +- `reset` *(default=`True`)*: Implicitly adds a color reset code to the + message output, unless the output already ends with one. +- `log_colors` *(default=`None`)*: A mapping of record level names to color + names. If `None`, `colorlog.default_log_colors` is used. +- `secondary_log_colors` *(default=`None`)*: A mapping of names to `log_colors` + style mappings, defining additional colors that can be used in format strings. + If `None`, an empty mapping is used. +- `stream` *(default=`None`)*: The stream being written to (e.g. `sys.stderr`). + Used to detect whether the output is a TTY. Colors are disabled automatically + on non-TTY streams unless `force_color` is set. +- `no_color` *(default=`False`)*: Disable color output. Can also be set via the + `NO_COLOR` environment variable. +- `force_color` *(default=`False`)*: Force color output even on non-TTY streams. + Takes precedence over `no_color`. Can also be set via the `FORCE_COLOR` + environment variable. + +### Color escape codes + +Color escape codes can be selected based on the log records level, by adding +parameters to the format string: + +- `log_color`: Return the color associated with the records level. +- `_log_color`: Return another color based on the records level if the + formatter has secondary colors configured (see `secondary_log_colors` below). + +Multiple escape codes can be used at once by joining them with commas when +configuring the color for a log level (but can't be used directly in the format +string). For example, `black,bg_white` would use the escape codes for black +text on a white background. + +The following escape codes are made available for use in the format string: + +- `{color}`, `fg_{color}`, `bg_{color}`: Foreground and background colors. +- `bold`, `bold_{color}`, `fg_bold_{color}`, `bg_bold_{color}`: Bold/bright + colors. +- `thin`, `thin_{color}`, `fg_thin_{color}`: Thin colors (terminal dependent). +- `reset`: Clear all formatting (both foreground and background colors). + +The available color names are: + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `purple` +- `cyan` +- `white` + +You can also use "bright" colors. These aren't standard ANSI codes, and +support for these varies wildly across different terminals. + +- `light_black` +- `light_red` +- `light_green` +- `light_yellow` +- `light_blue` +- `light_purple` +- `light_cyan` +- `light_white` + +In addition to pre-defined color names, you can use integers from 0 to 255 for +256-color support (e.g. `fg_196`, `bg_42`). + +## Examples + +![Example output](docs/example.png) + +The following snippet creates a `ColoredFormatter` for use in a logging setup, +with a custom format string and log colors: + +```python +from colorlog import ColoredFormatter + +formatter = ColoredFormatter( + "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", + log_colors={ + "DEBUG": "cyan", + "INFO": "green", + "WARNING": "yellow", + "ERROR": "red", + "CRITICAL": "red,bg_white", + } +) +``` + +*See `docs/example.py` for full example script.* + +### Using `secondary_log_colors` + +Secondary log colors are a way to have more than one color that is selected +based on the log level. Each key in `secondary_log_colors` adds an attribute +that can be used in format strings (`message` becomes `message_log_color`), and +has a corresponding value that is identical in format to the `log_colors` +argument. + +The following example highlights the level name using the default log colors, +and highlights the message in red for `error` and `critical` level log messages. + +```python +from colorlog import ColoredFormatter + +formatter = ColoredFormatter( + "%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s", + secondary_log_colors={ + 'message': { + 'ERROR': 'red', + 'CRITICAL': 'red' + } + } +) +``` + +### With [`dictConfig`][dictconfig] + +```python +logging.config.dictConfig({ + 'formatters': { + 'colored': { + '()': 'colorlog.ColoredFormatter', + 'format': "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s" + } + } +}) +``` + +A full example dictionary can be found in `tests/test_colorlog.py`. + +### With [`fileConfig`][fileconfig] + +```ini +... + +[formatters] +keys=color + +[formatter_color] +class=colorlog.ColoredFormatter +format=%(log_color)s%(levelname)-8s%(reset)s %(bg_blue)s[%(name)s]%(reset)s %(message)s from fileConfig +datefmt=%m-%d %H:%M:%S +``` + +An instance of ColoredFormatter created with those arguments will then be used +by any handlers that are configured to use the `color` formatter. + +A full example configuration can be found in `tests/test_config.ini`. + +### With custom log levels + +ColoredFormatter will work with custom log levels added with +[`logging.addLevelName`][addlevelname]: + +```python +import logging, colorlog +TRACE = 5 +logging.addLevelName(TRACE, 'TRACE') +formatter = colorlog.ColoredFormatter(log_colors={'TRACE': 'yellow'}) +handler = logging.StreamHandler() +handler.setFormatter(formatter) +logger = logging.getLogger('example') +logger.addHandler(handler) +logger.setLevel('TRACE') +logger.log(TRACE, 'a message using a custom level') +``` + +## Tests + +Tests similar to the above examples are found in `tests/test_colorlog.py`. + +## Status + +colorlog is in maintenance mode. I try and ensure bugfixes are published, +but compatibility a wide set of Python versions makes this a difficult +codebase to add features to. Any changes that might break backwards +compatibility for existing users will not be considered. + +## Alternatives + +There are some more modern libraries for improving Python logging you may +find useful. + +- [structlog] +- [jsonlog] + +## Projects using colorlog + +GitHub provides [a list of projects that depend on colorlog][dependents]. + +Some early adopters included [Errbot], [Pythran], and [zenlog]. + +## Licence + +Copyright (c) 2012-2025 Sam Clements + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +[addlevelname]: https://docs.python.org/3/library/logging.html#logging.addLevelName +[arch]: https://archlinux.org/packages/extra/any/python-colorlog/ +[bsd ports]: https://www.freshports.org/devel/py-colorlog/ +[colorama]: https://pypi.python.org/pypi/colorama +[conda]: https://anaconda.org/conda-forge/colorlog +[debian]: https://packages.debian.org/trixie/python3-colorlog +[dependents]: https://github.com/borntyping/python-colorlog/network/dependents?package_id=UGFja2FnZS01MDk3NDcyMQ%3D%3D +[dictconfig]: http://docs.python.org/3/library/logging.config.html#logging.config.dictConfig +[errbot]: http://errbot.io/ +[fedora]: https://src.fedoraproject.org/rpms/python-colorlog +[fileconfig]: http://docs.python.org/3/library/logging.config.html#logging.config.fileConfig +[formatter]: http://docs.python.org/3/library/logging.html#logging.Formatter +[gentoo]: https://packages.gentoo.org/packages/dev-python/colorlog +[jsonlog]: https://github.com/borntyping/jsonlog +[opensuse]: http://rpm.pbone.net/index.php3?stat=3&search=python-colorlog&srodzaj=3 +[pythran]: https://github.com/serge-sans-paille/pythran +[structlog]: https://www.structlog.org/en/stable/ +[ubuntu]: https://launchpad.net/python-colorlog +[zenlog]: https://github.com/ManufacturaInd/python-zenlog diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/RECORD b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..16a03fba9370cae11e8f03d64a23d0086718afee --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/RECORD @@ -0,0 +1,16 @@ +colorlog-6.12.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +colorlog-6.12.0.dist-info/METADATA,sha256=R3EMU2tsio6wdKCJI6iB4rp2Q3_2MxUWdUZsMVxcB7Y,11831 +colorlog-6.12.0.dist-info/RECORD,, +colorlog-6.12.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +colorlog-6.12.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91 +colorlog-6.12.0.dist-info/licenses/LICENSE,sha256=sdkIK8SDYj_Vn8cnm0V_DkDZQqdkJs3iVyOeBN_kElo,1107 +colorlog-6.12.0.dist-info/top_level.txt,sha256=CzNs7OLwLxUhbQzCCT2ore3b_ZzAXusw0tWIX79iWow,9 +colorlog/__init__.py,sha256=wzxah0vO2HpJheG0gXY4rMx_MyFYyfHsR8rTucg5PSI,1180 +colorlog/__pycache__/__init__.cpython-312.pyc,, +colorlog/__pycache__/escape_codes.cpython-312.pyc,, +colorlog/__pycache__/formatter.cpython-312.pyc,, +colorlog/__pycache__/wrappers.cpython-312.pyc,, +colorlog/escape_codes.py,sha256=lFpcWJqCo3d8kcVZpJFkuKrYbwtwdqdCeNFH9QnKA1Y,2438 +colorlog/formatter.py,sha256=3HjYFl5FXpBIaNFeR8Sm8Y9VcIK8ayvCRMljx36Td4Q,9130 +colorlog/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +colorlog/wrappers.py,sha256=onRQIxCBw8V1vA7zz_kavg4Mk25h8FH6vr8SQw4H6_Y,2399 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/REQUESTED b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/WHEEL b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1d472b6c22838de58d1c3c0dd2c795a5cde9e415 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (83.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/licenses/LICENSE b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ef3747bad8bc502664a46c8971e1ac6962ac60a8 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2012-2021 Sam Clements + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/top_level.txt b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..3d8df46d14496059ec31bd06e8928ef5050f46f2 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog-6.12.0.dist-info/top_level.txt @@ -0,0 +1 @@ +colorlog diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fb123b8bbe1985ef58c86eec996b8b100261ae71 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__init__.py @@ -0,0 +1,66 @@ +"""A logging formatter for colored output.""" + +import sys +import warnings + +from colorlog.formatter import ( + ColoredFormatter, + LevelFormatter, + TTYColoredFormatter, + default_log_colors, +) +from colorlog.wrappers import ( + CRITICAL, + DEBUG, + ERROR, + FATAL, + INFO, + NOTSET, + StreamHandler, + WARN, + WARNING, + basicConfig, + critical, + debug, + error, + exception, + getLogger, + info, + log, + root, + warning, +) + +__all__ = ( + "CRITICAL", + "DEBUG", + "ERROR", + "FATAL", + "INFO", + "NOTSET", + "WARN", + "WARNING", + "ColoredFormatter", + "LevelFormatter", + "StreamHandler", + "TTYColoredFormatter", + "basicConfig", + "critical", + "debug", + "default_log_colors", + "error", + "exception", + "exception", + "getLogger", + "info", + "log", + "root", + "warning", +) + +if sys.version_info < (3, 6): + warnings.warn( + "Colorlog requires Python 3.6 or above. Pin 'colorlog<5' to your dependencies " + "if you require compatibility with older versions of Python. See " + "https://github.com/borntyping/python-colorlog#status for more information." + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed0b1be4031740a8dc46915961c7aca7c78dc9ac Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/escape_codes.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/escape_codes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80434457245c2ab234d79b641d9869ad1070ccf2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/escape_codes.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/formatter.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/formatter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee8918ebc07a316d6485ad85b77d67370e6181aa Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/formatter.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/wrappers.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd88c2415622acaeace9c92c0537a00700263fc6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/__pycache__/wrappers.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/escape_codes.py b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/escape_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..185b947353fbd973728018e78ed4751d9129f083 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/escape_codes.py @@ -0,0 +1,105 @@ +""" +Generates a dictionary of ANSI escape codes. + +http://en.wikipedia.org/wiki/ANSI_escape_code + +Uses colorama as an optional dependency to support color on Windows +""" + +import sys + +try: + import colorama +except ImportError: + pass +else: + if sys.platform == "win32": + colorama.init(strip=False) + +__all__ = ("escape_codes", "parse_colors") + + +# Returns escape codes from format codes +def esc(*codes: int) -> str: + return "\033[" + ";".join(str(code) for code in codes) + "m" + + +escape_codes = { + "reset": esc(0), + "bold": esc(1), + "thin": esc(2), +} + +escape_codes_foreground = { + "black": 30, + "red": 31, + "green": 32, + "yellow": 33, + "blue": 34, + "purple": 35, + "cyan": 36, + "white": 37, + "light_black": 90, + "light_red": 91, + "light_green": 92, + "light_yellow": 93, + "light_blue": 94, + "light_purple": 95, + "light_cyan": 96, + "light_white": 97, +} + +escape_codes_background = { + "black": 40, + "red": 41, + "green": 42, + "yellow": 43, + "blue": 44, + "purple": 45, + "cyan": 46, + "white": 47, + "light_black": 100, + "light_red": 101, + "light_green": 102, + "light_yellow": 103, + "light_blue": 104, + "light_purple": 105, + "light_cyan": 106, + "light_white": 107, + # Bold background colors don't exist, + # but we used to provide these names. + "bold_black": 100, + "bold_red": 101, + "bold_green": 102, + "bold_yellow": 103, + "bold_blue": 104, + "bold_purple": 105, + "bold_cyan": 106, + "bold_white": 107, +} + +# Foreground without prefix +for name, code in escape_codes_foreground.items(): + escape_codes["%s" % name] = esc(code) + escape_codes["bold_%s" % name] = esc(1, code) + escape_codes["thin_%s" % name] = esc(2, code) + +# Foreground with fg_ prefix +for name, code in escape_codes_foreground.items(): + escape_codes["fg_%s" % name] = esc(code) + escape_codes["fg_bold_%s" % name] = esc(1, code) + escape_codes["fg_thin_%s" % name] = esc(2, code) + +# Background with bg_ prefix +for name, code in escape_codes_background.items(): + escape_codes["bg_%s" % name] = esc(code) + +# 256 colour support +for code in range(256): + escape_codes["fg_%d" % code] = esc(38, 5, code) + escape_codes["bg_%d" % code] = esc(48, 5, code) + + +def parse_colors(string: str) -> str: + """Return escape codes from a color sequence string.""" + return "".join(escape_codes[n] for n in string.split(",") if n) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/formatter.py b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/formatter.py new file mode 100644 index 0000000000000000000000000000000000000000..f67d44ed891a5533e185fa7b8733a9560f376b3d --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/formatter.py @@ -0,0 +1,251 @@ +"""The ColoredFormatter class.""" + +import logging +import os +import sys +import typing +import traceback +import io + +import colorlog.escape_codes + +__all__ = ( + "default_log_colors", + "ColoredFormatter", + "LevelFormatter", + "TTYColoredFormatter", +) + +# Type aliases used in function signatures. +EscapeCodes = typing.Mapping[str, str] +LogColors = typing.Mapping[str, str] +SecondaryLogColors = typing.Mapping[str, LogColors] +if sys.version_info >= (3, 8): + _FormatStyle = typing.Literal["%", "{", "$"] +else: + _FormatStyle = str + +# The default colors to use for the debug levels +default_log_colors = { + "DEBUG": "white", + "INFO": "green", + "WARNING": "yellow", + "ERROR": "red", + "CRITICAL": "bold_red", +} + +# The default format to use for each style +default_formats = { + "%": "%(log_color)s%(levelname)s:%(name)s:%(message)s", + "{": "{log_color}{levelname}:{name}:{message}", + "$": "${log_color}${levelname}:${name}:${message}", +} + + +class ColoredRecord: + """ + Wraps a LogRecord, adding escape codes to the internal dict. + + The internal dict is used when formatting the message (by the PercentStyle, + StrFormatStyle, and StringTemplateStyle classes). + """ + + def __init__(self, record: logging.LogRecord, escapes: EscapeCodes) -> None: + self.__dict__.update(record.__dict__) + self.__dict__.update(escapes) + + +class ColoredFormatter(logging.Formatter): + """ + A formatter that allows colors to be placed in the format string. + + Intended to help in creating more readable logging output. + """ + + def __init__( + self, + fmt: typing.Optional[str] = None, + datefmt: typing.Optional[str] = None, + style: _FormatStyle = "%", + log_colors: typing.Optional[LogColors] = None, + reset: bool = True, + secondary_log_colors: typing.Optional[SecondaryLogColors] = None, + validate: bool = True, + stream: typing.Optional[typing.IO] = None, + no_color: bool = False, + force_color: bool = False, + defaults: typing.Optional[typing.Mapping[str, typing.Any]] = None, + ) -> None: + """ + Set the format and colors the ColoredFormatter will use. + + The ``fmt``, ``datefmt``, ``style``, and ``default`` args are passed on to the + ``logging.Formatter`` constructor. + + The ``secondary_log_colors`` argument can be used to create additional + ``log_color`` attributes. Each key in the dictionary will set + ``{key}_log_color``, using the value to select from a different + ``log_colors`` set. + + :Parameters: + - fmt (str): The format string to use. + - datefmt (str): A format string for the date. + - log_colors (dict): + A mapping of log level names to color names. + - reset (bool): + Implicitly append a color reset to all records unless False. + - style ('%' or '{' or '$'): + The format style to use. + - secondary_log_colors (dict): + Map secondary ``log_color`` attributes. (*New in version 2.6.*) + - validate (bool) + Validate the format string. + - stream (typing.IO) + The stream formatted messages will be printed to. Used to toggle colour + on non-TTY outputs. Optional. + - no_color (bool): + Disable color output. + - force_color (bool): + Enable color output. Takes precedence over `no_color`. + """ + + # Select a default format if `fmt` is not provided. + fmt = default_formats[style] if fmt is None else fmt + + if sys.version_info >= (3, 10): + super().__init__(fmt, datefmt, style, validate, defaults=defaults) + elif sys.version_info >= (3, 8): + super().__init__(fmt, datefmt, style, validate) + else: + super().__init__(fmt, datefmt, style) + + self.log_colors = log_colors if log_colors is not None else default_log_colors + self.secondary_log_colors = ( + secondary_log_colors if secondary_log_colors is not None else {} + ) + self.reset = reset + self.stream = stream + self.no_color = no_color + self.force_color = force_color + + def formatMessage(self, record: logging.LogRecord) -> str: + """Format a message from a record object.""" + escapes = self._escape_code_map(record.levelname) + wrapper = ColoredRecord(record, escapes) + message = super().formatMessage(wrapper) # type: ignore + message = self._append_reset(message, escapes) + return message + + def _escape_code_map(self, item: str) -> EscapeCodes: + """ + Build a map of keys to escape codes for use in message formatting. + + If _color() returns False, all values will be an empty string. + """ + codes = {**colorlog.escape_codes.escape_codes} + codes.setdefault("log_color", self._get_escape_code(self.log_colors, item)) + for name, colors in self.secondary_log_colors.items(): + codes.setdefault("%s_log_color" % name, self._get_escape_code(colors, item)) + if not self._colorize(): + codes = {key: "" for key in codes.keys()} + return codes + + def _colorize(self): + """Return False if we should be prevented from printing escape codes.""" + if self.force_color or "FORCE_COLOR" in os.environ: + return True + + if self.no_color or "NO_COLOR" in os.environ: + return False + + if self.stream is not None and not self.stream.isatty(): + return False + + return True + + @staticmethod + def _get_escape_code(log_colors: LogColors, item: str) -> str: + """Extract a color sequence from a mapping, and return escape codes.""" + return colorlog.escape_codes.parse_colors(log_colors.get(item, "")) + + def _append_reset(self, message: str, escapes: EscapeCodes) -> str: + """Add a reset code to the end of the message, if it's not already there.""" + reset_escape_code = escapes["reset"] + + if self.reset and not message.endswith(reset_escape_code): + message += reset_escape_code + + return message + + if sys.version_info >= (3, 13): + + def formatException(self, ei) -> str: + """ + Format and return the specified exception information as a string. + + This is a copy of logging.Formatter.formatException that passes in + an appropriate value for colorize to print_exception. + """ + kwargs = dict(colorize=self._colorize()) + + sio = io.StringIO() + tb = ei[2] + traceback.print_exception(ei[0], ei[1], tb, limit=None, file=sio, **kwargs) + s = sio.getvalue() + sio.close() + if s[-1:] == "\n": + s = s[:-1] + return s + + +class LevelFormatter: + """An extension of ColoredFormatter that uses per-level format strings.""" + + def __init__(self, fmt: typing.Mapping[str, str], **kwargs: typing.Any) -> None: + """ + Configure a ColoredFormatter with its own format string for each log level. + + Supports fmt as a dict. All other args are passed on to the + ``colorlog.ColoredFormatter`` constructor. + + :Parameters: + - fmt (dict): + A mapping of log levels (represented as strings, e.g. 'WARNING') to + format strings. (*New in version 2.7.0) + + Levels that are not present in the mapping fall back to a default + formatter, so records logged at custom or unlisted levels are + formatted rather than raising a ``KeyError``. To customise the + fallback, provide a format string under the special ``"DEFAULT"`` + key; otherwise the default format for the chosen ``style`` is used. + (All other parameters are the same as in colorlog.ColoredFormatter) + + Example: + + formatter = colorlog.LevelFormatter( + fmt={ + "DEBUG": "%(log_color)s%(message)s (%(module)s:%(lineno)d)", + "INFO": "%(log_color)s%(message)s", + "WARNING": "%(log_color)sWRN: %(message)s (%(module)s:%(lineno)d)", + "ERROR": "%(log_color)sERR: %(message)s (%(module)s:%(lineno)d)", + "CRITICAL": "%(log_color)sCRT: %(message)s (%(module)s:%(lineno)d)", + } + ) + """ + self.formatters = { + level: ColoredFormatter(fmt=f, **kwargs) for level, f in fmt.items() + } + # Used for any level not present in ``fmt``. An explicit "DEFAULT" entry + # takes precedence; otherwise fall back to the default format string. + self.default_formatter = self.formatters.get( + "DEFAULT", ColoredFormatter(**kwargs) + ) + + def format(self, record: logging.LogRecord) -> str: + formatter = self.formatters.get(record.levelname, self.default_formatter) + return formatter.format(record) + + +# Provided for backwards compatibility. The features provided by this subclass are now +# included directly in the `ColoredFormatter` class. +TTYColoredFormatter = ColoredFormatter diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/py.typed b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/wrappers.py b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..e05756fbac347d215d2f6732f00f2e9fab991381 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/colorlog/wrappers.py @@ -0,0 +1,101 @@ +"""Wrappers around the logging module.""" + +import functools +import logging +import sys +import typing +from logging import ( + CRITICAL, + DEBUG, + ERROR, + FATAL, + INFO, + NOTSET, + StreamHandler, + WARN, + WARNING, + getLogger, + root, +) + +import colorlog.formatter + +__all__ = ( + "CRITICAL", + "DEBUG", + "ERROR", + "FATAL", + "INFO", + "NOTSET", + "WARN", + "WARNING", + "StreamHandler", + "basicConfig", + "critical", + "debug", + "error", + "exception", + "getLogger", + "info", + "log", + "root", + "warning", +) + + +def basicConfig( + style: colorlog.formatter._FormatStyle = "%", + log_colors: typing.Optional[colorlog.formatter.LogColors] = None, + reset: bool = True, + secondary_log_colors: typing.Optional[colorlog.formatter.SecondaryLogColors] = None, + format: str = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s", + datefmt: typing.Optional[str] = None, + **kwargs +) -> None: + """Call ``logging.basicConfig`` and override the formatter it creates.""" + logging.basicConfig(**kwargs) + + def _basicConfig(): + handler = logging.root.handlers[0] + handler.setFormatter( + colorlog.formatter.ColoredFormatter( + fmt=format, + datefmt=datefmt, + style=style, + log_colors=log_colors, + reset=reset, + secondary_log_colors=secondary_log_colors, + stream=kwargs.get("stream", None), + ) + ) + + if sys.version_info >= (3, 13): + with logging._lock: # type: ignore + _basicConfig() + else: + logging._acquireLock() # type: ignore + try: + _basicConfig() + finally: + logging._releaseLock() # type: ignore + + +def ensure_configured(func): + """Modify a function to call our basicConfig() first if no handlers exist.""" + + @functools.wraps(func) + def wrapper(*args, **kwargs): + if len(logging.root.handlers) == 0: + basicConfig() + return func(*args, **kwargs) + + return wrapper + + +debug = ensure_configured(logging.debug) +info = ensure_configured(logging.info) +warning = ensure_configured(logging.warning) +error = ensure_configured(logging.error) +critical = ensure_configured(logging.critical) +log = ensure_configured(logging.log) +exception = ensure_configured(logging.exception) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/__pycache__/conf.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/__pycache__/conf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f92e9e5db47cc585f366f03663b3da4b503bfcc Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/__pycache__/conf.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/__pycache__/generate_compiled_code.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/__pycache__/generate_compiled_code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aec04b5d980e3958ff5477d363d8055d92b9defd Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/__pycache__/generate_compiled_code.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/conf.py b/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa7838481a6533b01bf125be8f4682e0fc5300b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/conf.py @@ -0,0 +1,52 @@ +# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Project information ----------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information + +import os +import subprocess +import sys + +project = "einx" +copyright = "Florian Fervers" +author = 'Florian Fervers' + +# -- General configuration --------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration + +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.mathjax", + "sphinx.ext.napoleon", + "sphinx.ext.viewcode", + "sphinx_autodoc_typehints", +] + +templates_path = [] +exclude_patterns = [] + +autosummary_generate = True + +# TODO: +autodoc_type_aliases = {"ArrayLike": "numpy.typing.ArrayLike"} +autodoc_typehints_format = "fully-qualified" + +# -- Options for HTML output ------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output + +html_theme = "sphinx_book_theme" + +html_theme_options = {"show_toc_level": 1, "repository_url": "https://github.com/fferflo/einx", "use_repository_button": True} + + +# def run(app): +# subprocess.check_call([sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), "generate_compiled_code.py")]) + + +# def setup(app): +# app.connect("builder-inited", run) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/generate_compiled_code.py b/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/generate_compiled_code.py new file mode 100644 index 0000000000000000000000000000000000000000..e4d0dd9e0e8faa55266953c77c7953afc76054bf --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/docs/source/generate_compiled_code.py @@ -0,0 +1,166 @@ +import einx +import numpy as np +import os +import jax.numpy as jnp +import torch +import array_api_compat + +report = "" + + +def generate_op(func_str): + func_str = func_str.strip().split("\n") + + rst = "" + + func_str_rst = "".join(["\n " + line.strip() for line in func_str if line.strip()]) + rst += "The operation\n\n" + rst += f".. code-block:: Python\n{func_str_rst}\n\n" + rst += "compiles to the following code:\n\n" + return rst + + +def generate_code(func_str, backend=None): + if backend is not None: + backend = f', backend="{backend}"' + else: + backend = "" + func_str = func_str.strip().split("\n") + + rst = "" + + func_str[-1] = "code = " + func_str[-1] + func_str = "\n".join(func_str) + func_str = func_str.strip() + assert func_str.endswith(")") + func_str = func_str[:-1] + f", graph=True{backend})" + + locals_globals = {"jnp": jnp, "einx": einx, "np": np} + exec(func_str, locals_globals, locals_globals) + code = eval("code", locals_globals, locals_globals) + + code = code.strip().split("\n") + code = "".join(["\n " + line for line in code if line.strip()]) + + rst += "\n\n" + rst += f".. code-block:: Python\n{code}" + rst += "\n\n" + return rst + + +def generate(func_str): + rst = "" + + rst += generate_op(func_str) + rst += generate_code(func_str) + + return rst + + +def underline(text, char): + return f"\n{text}\n{char * len(text)}\n\n" + + +report += underline("Examples of compiled code", "#") + +report += """ +The following are examples of various einx operations along with the Python code snippet that einx compiles for them, using either +the default backend or explicitly specifying a backend. The compiled code can be inspected by passing ``graph=True`` to the einx operation. +""" + + +report += underline("Axis permutation", "=") + +code = """ +x = np.zeros((10, 5, 2)) +einx.id("a b c -> b c a", x) +""".strip() + +report += generate_op(code) + +report += underline('With ``backend="numpy"``', "-") +report += generate_code(code, backend="numpy") + +report += underline('With ``backend="torch"``', "-") +report += generate_code(code, backend="torch") + +report += underline('With ``backend="jax"``', "-") +report += generate_code(code, backend="jax") + +report += underline('With ``backend="arrayapi"``', "-") +report += generate_code(code, backend="arrayapi") + + +report += underline("Axis flattening", "=") +report += generate(""" +x = np.zeros((10, 5)) +einx.id("(a b) c -> a (b c)", x, b=2) +""") + + +report += underline("No-op", "=") +report += generate(""" +x = np.zeros((10, 5)) +einx.id("a b -> a b", x) +""") + + +report += underline("Element-wise multiplication", "=") + +code = """ +x = jnp.zeros((2, (5 * 6))) +y = jnp.zeros((4, 3, 6)) +einx.multiply("a (d e), c b e -> a b c d e", x, y) +""" + +report += generate_op(code) + +report += underline('With ``backend="jax.numpylike"``', "-") +report += generate_code(code, backend="jax.numpylike") + +report += underline('With ``backend="jax.vmap"``', "-") +report += generate_code(code, backend="jax.vmap") + +report += underline('With ``backend="jax.einsum"``', "-") +report += generate_code(code, backend="jax.einsum") + + +report += underline("Dot-product", "=") + +code = """ +x = jnp.zeros((2, 3)) +y = jnp.zeros((4, 3)) +einx.dot("a [b], c [b] -> c a", x, y) +""" + +report += generate_op(code) + +report += underline('With ``backend="jax.numpylike"``', "-") +report += generate_code(code, backend="jax.numpylike") + +report += underline('With ``backend="jax.vmap"``', "-") +report += generate_code(code, backend="jax.vmap") + +report += underline('With ``backend="jax.einsum"``', "-") +report += generate_code(code, backend="jax.einsum") + + +report += underline("Indexing", "=") + +code = """ +x = jnp.zeros((2, 128, 128, 3)) +y = jnp.zeros((50, 2)) +einx.get_at("b [h w] c, p [2] -> b p c", x, y) +""" + +report += generate_op(code) + +report += underline('With ``backend="jax.numpylike"``', "-") +report += generate_code(code, backend="jax.numpylike") + +report += underline('With ``backend="jax.vmap"``', "-") +report += generate_code(code, backend="jax.vmap") + + +with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "more", "compiledcode.rst"), "w") as f: + f.write(report) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/INSTALLER b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/METADATA b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c7fb37d823d702cea3d4ccfb583995cf5a38c33b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/METADATA @@ -0,0 +1,174 @@ +Metadata-Version: 2.4 +Name: einx +Version: 0.4.3 +Summary: Universal Notation for Tensor Operations in Python +Author-email: Florian Fervers +License-Expression: MIT +Project-URL: Homepage, https://github.com/fferflo/einx +Project-URL: Source, https://github.com/fferflo/einx +Project-URL: Documentation, https://einx.readthedocs.io +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: numpy +Requires-Dist: sympy +Requires-Dist: frozendict +Provides-Extra: torch +Requires-Dist: torch>=2.2; extra == "torch" +Provides-Extra: mlx +Requires-Dist: mlx; extra == "mlx" +Dynamic: license-file + +# *einx* - Universal Notation for Tensor Operations + +[![pytest](https://github.com/fferflo/einx/actions/workflows/run_pytest.yml/badge.svg)](https://github.com/fferflo/einx/actions/workflows/run_pytest.yml) +[![Documentation](https://img.shields.io/badge/documentation-link-blue.svg)](https://einx.readthedocs.io) +[![PyPI version](https://img.shields.io/pypi/v/einx.svg?color=blue)](https://pypi.org/project/einx/) +[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/release/python-3100/) + +einx is a notation and Python library that provides a universal interface to formulate tensor operations in frameworks such as Numpy, PyTorch, Jax, Tensorflow, and MLX. + +* [Quickstart](#quickstart) +* [What does einx look like?](#what-does-einx-look-like) +* [How does the notation work?](#how-does-the-notation-work) +* [How are einx operations implemented?](#how-are-einx-operations-implemented) +* [Which operations are supported?](#which-operations-are-supported) + +## Quickstart + +**Installation:** + +```python +pip install einx +``` + +**Example code:** + +```python +import einx +import numpy as np + +x = np.ones((10, 20, 30)) # Create some tensor (numpy/torch/jax/tensorflow/mlx/...) + +y = einx.sum("a [b] c", x) # Call an einx operation + +print(y.shape) +``` + +**Documentation and tutorials:** [https://einx.readthedocs.io](https://einx.readthedocs.io) + +## What does einx look like? + +```python +z = einx.id("a (b c) -> (b a) c", x, b=2) # Permute and (un)flatten axes +z = einx.sum("a [b]", x) # Sum-reduction along second axis +z = einx.flip("... (g [c])", x, c=2) # Flip pairs of values along the last axis +z = einx.mean("b [...] c", x) # Spatial mean-pooling +z = einx.multiply("a..., b... -> (a b)...", x, y) # Kronecker product +z = einx.sum("b (s [ds])... c", x, ds=(2, 2)) # Sum-pooling with 2x2 kernel +z = einx.add("a, b -> a b", x, y) # Outer sum +z = einx.dot("a [b], [b] c -> a c", x, y) # Matrix multiplication +z = einx.get_at("b [h w] c, b i [2] -> b i c", x, y) # Gather values at coordinates +z = einx.id("b (q + k) -> b q, b k", x, q=2) # Split +z = einx.id("b c, -> b (c + 1)", x, 42) # Append number to each channel +``` + +See the [documentation](https://einx.readthedocs.io/en/latest/more/operations.html) for more examples. + +## How does the notation work? + +An einx operation consists of (1) an elementary operation and (2) an einx expression that describes how the elementary operation is vectorized. For example, +the code + +```python +z = einx.{OP}("[c d] a, b -> a [e] b", x, y) +``` + +vectorizes the elementary operation ``{OP}`` according to the expression ``"[c d] a, b -> a [e] b"``. + +The meaning of the string expression is defined by analogy with loop notation as follows. The full operation ``einx.{OP}`` will yield the same output as if the elementary +operation ``{OP}`` were invoked in an analogous loop expression: + +```python +for a in range(...): + for b in range(...): + z[a, :, b] = {OP}(x[:, :, a], y[b]) +``` + +See the [tutorial](https://einx.readthedocs.io/en/latest/gettingstarted/basics.html) for how an einx expression is mapped to the analogous loop expression. + +## How are einx operations implemented? + +The analogy with loop notation is used only to define what the output of an operation will be. Internally, einx operations are compiled to Python code snippets that invoke operations from the respective tensor framework, rather than using for loops. + +The compiled code snippet can be inspected by passing `graph=True` to the einx operation. For example: + +```python +>>> x = np.zeros((2, 3)) +>>> y = np.zeros((3, 4)) +>>> code = einx.add("a b, b c -> c b a", x, y, graph=True) +>>> print(code) + +import numpy as np +def op(a, b): + a = np.transpose(a, (1, 0)) + a = np.reshape(a, (1, 3, 2)) + b = np.transpose(b, (1, 0)) + b = np.reshape(b, (4, 3, 1)) + c = np.add(a, b) + return c +``` + +Different [backends](https://einx.readthedocs.io/en/latest/gettingstarted/backends.html) may be used to compile an operation to different implementations, for example following Numpy-like notation, vmap-based notation, or einsum notation. + +## Which operations are supported? + +**Operations in the API:** einx supports a large set of tensor operations in the namespace ``einx.*``, including reduction, scalar, indexing, some shape-preserving operations, identity map and dot-product. See the [documentation](https://einx.readthedocs.io/en/latest/api/operations.html) for a complete list. + +**Operations *not* in the API:** einx additionally allows adapting custom Python functions to einx notation using einx adapters. For example: + +```python +# Define a custom elementary operation +def myoperation(x, y): + x = 2 * x + z = x + torch.sum(y) + return z + +# Adapt the operation to einx notation +einmyoperation = einx.torch.adapt_with_vmap(myoperation) + +# Invoke as einx operation +z = einmyoperation("a [c], b [c] -> a b [c]", x, y) +``` + +This will yield the same output as if ``myoperation`` were invoked in loop notation: + +```python +for a in range(...): + for b in range(...): + z[a, b, :] = myoperation(x[a, :], y[b, :]) +``` + +The interface of ``einmyoperation`` matches that of other einx operations. For example, the compiled code snippet can be inspected using ``graph=True``: + +```python +>>> code = einmyoperation("a [c], b [c] -> a b [c]", x, y, graph=True) +>>> print(code) +# Constant const1: +import torch +def op(a, b): + def c(d, e): + f = const1(d, e) + assert isinstance(f, torch.Tensor), "Expected 1st return value of the adapted function to be a tensor" + assert (tuple(f.shape) == (3,)), "Expected 1st return value of the adapted function to be a tensor with shape (3,)" + return f + c = torch.vmap(c, in_dims=(None, 0), out_dims=0) + c = torch.vmap(c, in_dims=(0, None), out_dims=0) + g = c(a, b) + return g +``` + +See the [documentation](https://einx.readthedocs.io/en/latest/api/adapters.html) for a list of supported adapters. diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/RECORD b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f421f0adb48ffaca073c396ee6d1a38622276ad1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/RECORD @@ -0,0 +1,258 @@ +docs/source/__pycache__/conf.cpython-312.pyc,, +docs/source/__pycache__/generate_compiled_code.cpython-312.pyc,, +docs/source/conf.py,sha256=OG8aRRsCZnr5wbMze7rZSXLEAxr5ofdXtxhqM-WH3NI,1635 +docs/source/generate_compiled_code.py,sha256=_mhwg-OMoNUQx_YR3lmEEQQHjc-jzrbSlt3yMjoagSM,4163 +einx-0.4.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +einx-0.4.3.dist-info/METADATA,sha256=lW_S2qT9Pbl9z4QHhJwVgvRc7sNk5EGBCX1pYwDQKs4,6918 +einx-0.4.3.dist-info/RECORD,, +einx-0.4.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +einx-0.4.3.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +einx-0.4.3.dist-info/licenses/LICENSE,sha256=YCNGi6KXU5MCmmPoqCT4NB3T5VpU2gqkZ5yFQUXPF_c,1094 +einx-0.4.3.dist-info/top_level.txt,sha256=Ljfnoa_bu1eJ0CSb-KQEtFuBwTaBJRbcaMcZpLtjN3o,15 +einx/__init__.py,sha256=hcrNMP8goQ6-Udr6BZev_mVshW0DqPZbZT6HZ47YgpQ,3046 +einx/__pycache__/__init__.cpython-312.pyc,, +einx/__pycache__/arrayapi.cpython-312.pyc,, +einx/__pycache__/backend.cpython-312.pyc,, +einx/__pycache__/errors.cpython-312.pyc,, +einx/__pycache__/jax.cpython-312.pyc,, +einx/__pycache__/mlx.cpython-312.pyc,, +einx/__pycache__/nn.cpython-312.pyc,, +einx/__pycache__/numpy.cpython-312.pyc,, +einx/__pycache__/tensorflow.cpython-312.pyc,, +einx/__pycache__/tinygrad.cpython-312.pyc,, +einx/__pycache__/torch.cpython-312.pyc,, +einx/_src/adapter/__init__.py,sha256=KnHe6t5DnwHiu-krjjm3CE5E_4tV0N5FSPnREsG9f34,1543 +einx/_src/adapter/__pycache__/__init__.cpython-312.pyc,, +einx/_src/adapter/__pycache__/_util.cpython-312.pyc,, +einx/_src/adapter/__pycache__/classical_from_classical.cpython-312.pyc,, +einx/_src/adapter/__pycache__/classical_from_einsum.cpython-312.pyc,, +einx/_src/adapter/__pycache__/decomposednamedtensor_from_classical.cpython-312.pyc,, +einx/_src/adapter/__pycache__/decomposednamedtensor_from_einsum.cpython-312.pyc,, +einx/_src/adapter/__pycache__/decomposednamedtensor_from_vmap.cpython-312.pyc,, +einx/_src/adapter/__pycache__/einx_from_namedtensor.cpython-312.pyc,, +einx/_src/adapter/__pycache__/elementary_from_classical.cpython-312.pyc,, +einx/_src/adapter/__pycache__/namedtensor_calltensorfactory.cpython-312.pyc,, +einx/_src/adapter/__pycache__/namedtensor_from_decomposednamedtensor.cpython-312.pyc,, +einx/_src/adapter/__pycache__/ops.cpython-312.pyc,, +einx/_src/adapter/_util.py,sha256=q4iI_DRAsA4BSZ9nxcO0JU9tYNLHuCU9vOaX8pdePr4,12692 +einx/_src/adapter/arrayapi/__pycache__/classical_from_arrayapi.cpython-312.pyc,, +einx/_src/adapter/arrayapi/__pycache__/einsum_from_arrayapi.cpython-312.pyc,, +einx/_src/adapter/arrayapi/__pycache__/namespacestack.cpython-312.pyc,, +einx/_src/adapter/arrayapi/__pycache__/tensortype_from_arrayapi.cpython-312.pyc,, +einx/_src/adapter/arrayapi/classical_from_arrayapi.py,sha256=fyQQTLude9kfI0dCYwEU5xtfPRulb81OO6A6MXsETzY,6502 +einx/_src/adapter/arrayapi/einsum_from_arrayapi.py,sha256=iST0MqQcerPX51puFqAcFdR7NFzor18jIIT0K2hxdMc,371 +einx/_src/adapter/arrayapi/namespacestack.py,sha256=dQAVn54quTISGR0Cpmk6SJ-OmreBeZtnaG8Cgn6ng0Q,1609 +einx/_src/adapter/arrayapi/tensortype_from_arrayapi.py,sha256=n2LdE5WEebK8MJH5dO2BuRaHOkJ5LkRNHfUj9T0uWUE,337 +einx/_src/adapter/classical_from_classical.py,sha256=e7548DgaRWQHmMw5GqL_KAOZdlv0Y9QfSF7IHFXWq60,2416 +einx/_src/adapter/classical_from_einsum.py,sha256=Oln-i-Ge3HczWShZfDq4kZ9HiBy1zJgAu-dwa2cOnUA,954 +einx/_src/adapter/decomposednamedtensor_from_classical.py,sha256=hqAcp7VOOrj90Fme7_3jDyqyb8HnJW2Llxg9w1eD8ww,17077 +einx/_src/adapter/decomposednamedtensor_from_einsum.py,sha256=Qlng3vCM3ay3yRunUEOSTx7p1IcVRTkk2v19kacd0aQ,2730 +einx/_src/adapter/decomposednamedtensor_from_vmap.py,sha256=4sIv-kMu9Z_VPVHqjzcjZok60UVLkrF1EZ8BalDRxGA,2908 +einx/_src/adapter/einx_from_namedtensor.py,sha256=Yh4xQZJOwXLTBKpEoXAlOpjnJohxT3NGNI-TAWNd6oU,39197 +einx/_src/adapter/elementary_from_classical.py,sha256=RmF2J78I8gqP4gzcDhkuYyiSdIqBRC-0Z3Co-HCoC90,3215 +einx/_src/adapter/functorchdim/__pycache__/namedtensor_from_functorchdim.cpython-312.pyc,, +einx/_src/adapter/functorchdim/namedtensor_from_functorchdim.py,sha256=0NUgg-wJkLi3VFLkLhP8Tn6-WM-OZiQ4S1TA3pro62U,7465 +einx/_src/adapter/jax/__pycache__/classical_from_jax.cpython-312.pyc,, +einx/_src/adapter/jax/__pycache__/einsum_from_jax.cpython-312.pyc,, +einx/_src/adapter/jax/__pycache__/vmap_from_jax.cpython-312.pyc,, +einx/_src/adapter/jax/classical_from_jax.py,sha256=K5QWDA_tz-crdOnNWziTPXvRhU6Jl34V4lxg4ueMcMY,6675 +einx/_src/adapter/jax/einsum_from_jax.py,sha256=1XWZNeBjc3L4ysQRvR9IAZ8d_71t99TEdhJh0qf9F-w,364 +einx/_src/adapter/jax/vmap_from_jax.py,sha256=C7qhDcbZH6OO4ImpZsjgmaYjP8vz4sJcc2wRn3wGnwY,672 +einx/_src/adapter/mlx/__pycache__/classical_from_mlx.cpython-312.pyc,, +einx/_src/adapter/mlx/__pycache__/einsum_from_mlx.cpython-312.pyc,, +einx/_src/adapter/mlx/__pycache__/vmap_from_mlx.cpython-312.pyc,, +einx/_src/adapter/mlx/classical_from_mlx.py,sha256=nx_Ifz5kPOWjUzssDLfLrSECWrDZEPmIIy2J7t6ERtQ,6506 +einx/_src/adapter/mlx/einsum_from_mlx.py,sha256=pmp3h0xBzbZCnnzIiPmh05t3G9kjCKVzwNkIuQtU3I8,410 +einx/_src/adapter/mlx/vmap_from_mlx.py,sha256=pIToDMlPucjZrbOXVkx7EPlxKkCWaOdsBdrtDRuCxH4,396 +einx/_src/adapter/namedtensor_calltensorfactory.py,sha256=f3NrobZ084O4zb3eWGGmO8j8PQzz0hCmzX0g9dbIIKo,3467 +einx/_src/adapter/namedtensor_from_decomposednamedtensor.py,sha256=_RgAdlKQGvQq5a7y77I3NPpj7UThP4G2C391Sioyb-0,10370 +einx/_src/adapter/numpy/__pycache__/classical_from_numpy.cpython-312.pyc,, +einx/_src/adapter/numpy/__pycache__/einsum_from_numpy.cpython-312.pyc,, +einx/_src/adapter/numpy/classical_from_numpy.py,sha256=_yGPtzMlE2-G7ClOOOsttuU0Jo0l_As_H4doJkhcZb0,17085 +einx/_src/adapter/numpy/einsum_from_numpy.py,sha256=NsIwtKgBZq5NzXxy92VRUDc1i-MIjtNa1nEsmklrs_E,2120 +einx/_src/adapter/ops.py,sha256=pLWZ10bwu1cTgZpbWk8ioUxgG4mSrulZjF3YSQtq2b0,705 +einx/_src/adapter/tensorflow/__pycache__/classical_from_tensorflow.cpython-312.pyc,, +einx/_src/adapter/tensorflow/__pycache__/einsum_from_tensorflow.cpython-312.pyc,, +einx/_src/adapter/tensorflow/classical_from_tensorflow.py,sha256=K-uOaCFQJBULQeaDAVX9mR5UTiCr0v9K_Ij6cFmcMmg,8317 +einx/_src/adapter/tensorflow/einsum_from_tensorflow.py,sha256=nhKbfpx-ND2zzpikfTYk_24JfQQELxMKd8wBIiUafTM,356 +einx/_src/adapter/tinygrad/__pycache__/classical_from_tinygrad.cpython-312.pyc,, +einx/_src/adapter/tinygrad/__pycache__/einsum_from_tinygrad.cpython-312.pyc,, +einx/_src/adapter/tinygrad/classical_from_tinygrad.py,sha256=NBdUaFnOYZF-MiCbjSJvqKzjZI12gRjTXjLkya_j97s,9678 +einx/_src/adapter/tinygrad/einsum_from_tinygrad.py,sha256=L_lb3Vnv0fNnJlQZWCbD0ZTj0nYMq3YF4iJu6mPj1Wk,439 +einx/_src/adapter/torch/__pycache__/classical_from_torch.cpython-312.pyc,, +einx/_src/adapter/torch/__pycache__/devicestack.cpython-312.pyc,, +einx/_src/adapter/torch/__pycache__/einsum_from_torch.cpython-312.pyc,, +einx/_src/adapter/torch/__pycache__/vmap_from_torch.cpython-312.pyc,, +einx/_src/adapter/torch/classical_from_torch.py,sha256=TRAYKjV73x96kAInRjBQ3b7FXnH_NgqKcp8RyE3mCW4,10315 +einx/_src/adapter/torch/devicestack.py,sha256=nSnHrWJJnlOVGgOWuKRTKOZnD8fMlLq18qTqCNp_g4E,1665 +einx/_src/adapter/torch/einsum_from_torch.py,sha256=INgSWfhXajcWnvgegXkZeeiRRB39t2t9jtRGe7nPQoY,399 +einx/_src/adapter/torch/vmap_from_torch.py,sha256=S63Yz4FMr5dEsK-xcA5MCd2aE--ynt2cWcZlh6Fsxt8,461 +einx/_src/frontend/__pycache__/api.cpython-312.pyc,, +einx/_src/frontend/__pycache__/backend.cpython-312.pyc,, +einx/_src/frontend/__pycache__/errors.cpython-312.pyc,, +einx/_src/frontend/__pycache__/ops.cpython-312.pyc,, +einx/_src/frontend/__pycache__/removed_ops.cpython-312.pyc,, +einx/_src/frontend/__pycache__/types.cpython-312.pyc,, +einx/_src/frontend/__pycache__/util.cpython-312.pyc,, +einx/_src/frontend/api.py,sha256=k3UjpOToWSu9gL-HpRF54alMy4CA6NdfeXbLnrVnFM0,8630 +einx/_src/frontend/backend.py,sha256=w1DhVu8b-Waw3_bIIrPDL4vwd_tYNJv-5tZ7NnmNjqE,12319 +einx/_src/frontend/errors.py,sha256=L6Sv5zznM6Bxqn2j-SadVvUZ-QPus3Hw7CdXHiVJ0zg,9065 +einx/_src/frontend/impl/__pycache__/_docs.cpython-312.pyc,, +einx/_src/frontend/impl/__pycache__/_util.cpython-312.pyc,, +einx/_src/frontend/impl/__pycache__/arrayapi.cpython-312.pyc,, +einx/_src/frontend/impl/__pycache__/functorchdim.cpython-312.pyc,, +einx/_src/frontend/impl/__pycache__/jax.cpython-312.pyc,, +einx/_src/frontend/impl/__pycache__/mlx.cpython-312.pyc,, +einx/_src/frontend/impl/__pycache__/numpy.cpython-312.pyc,, +einx/_src/frontend/impl/__pycache__/tensorflow.cpython-312.pyc,, +einx/_src/frontend/impl/__pycache__/tinygrad.cpython-312.pyc,, +einx/_src/frontend/impl/__pycache__/torch.cpython-312.pyc,, +einx/_src/frontend/impl/_docs.py,sha256=b5gX-Y5nbZh1x5TeGQHDVyekuWcD7h16VgIDgAaHVnE,2345 +einx/_src/frontend/impl/_util.py,sha256=Z8YqaXu8SXEsKnT3qBKBO5XFcsg_u52fgkLk-fbRhus,999 +einx/_src/frontend/impl/arrayapi.py,sha256=pI23ADtc_yjLa4F5i7wXFMtT7BQNFgeerPHSYoMjmRs,6088 +einx/_src/frontend/impl/functorchdim.py,sha256=_UwrNdwft0bMUHik6OB-x7kz7tZ8_LPDmlVa7lgbBuY,1576 +einx/_src/frontend/impl/jax.py,sha256=L_xsQQPeaF1RGddgCFwYJPGqxS2xH8jAvvG6E7BVG4M,6898 +einx/_src/frontend/impl/mlx.py,sha256=IVj4Vew14zmc0Xet6cTf5QGgCMYjXVH1yJDgpOGh894,6683 +einx/_src/frontend/impl/numpy.py,sha256=62CqJJa07rF0gfR0SFJZ0QOJ2Z3obAjGRmkJaVaS9lY,5251 +einx/_src/frontend/impl/tensorflow.py,sha256=xPimldtw_Es4jedNOEPP6akPvRdKaemIU3cPxliVCt4,5418 +einx/_src/frontend/impl/tinygrad.py,sha256=Unv2t6v-Lzl7TV0SEhQUYqV6ZboF7_yHal4tQOZ5OAM,5481 +einx/_src/frontend/impl/torch.py,sha256=R7fkmu-t1CgQyBTxi5G4BPgmhOmgRFLzjoSo72iLfxE,9388 +einx/_src/frontend/ops.py,sha256=GD_FnMv13nGSIWOWpNk2yhkY71d2C5C64Pwuooq_bSo,27337 +einx/_src/frontend/removed_ops.py,sha256=R3RLBNImBoEeQaw_tJ67DsNIlCq50xZw9AM6w0tl_Ag,1735 +einx/_src/frontend/types.py,sha256=ZZ6UlWYZJZYaNBRpuEQUl94KOKHrllTVX5xM0P4da4M,246 +einx/_src/frontend/util.py,sha256=vVzmg_h6jUuUjq4Jxyr36AFSEN6LK8vnR8GdYn8Lumg,5962 +einx/_src/namedtensor/__init__.py,sha256=vI61ECx12rJ1PHV1P6apt7hrC_UaD-5ssibW1Xga5eQ,100 +einx/_src/namedtensor/__pycache__/__init__.cpython-312.pyc,, +einx/_src/namedtensor/__pycache__/namedtensor.cpython-312.pyc,, +einx/_src/namedtensor/__pycache__/solve.cpython-312.pyc,, +einx/_src/namedtensor/__pycache__/util.cpython-312.pyc,, +einx/_src/namedtensor/namedtensor.py,sha256=uZpR0E4Ck06qs_StsZlm01rrVrG0A_NqRYphoTTxJy0,660 +einx/_src/namedtensor/solve.py,sha256=1zsZ3oZZ8Hg9DA9lNRKYW6_kx2LmblUQzFt6bGsdcUU,4714 +einx/_src/namedtensor/stage1/__init__.py,sha256=q1My6Hy_IxZBWB_VPu88L595wTMJMUXDI5C3dY3KNgo,471 +einx/_src/namedtensor/stage1/__pycache__/__init__.cpython-312.pyc,, +einx/_src/namedtensor/stage1/__pycache__/parse.cpython-312.pyc,, +einx/_src/namedtensor/stage1/__pycache__/transform.cpython-312.pyc,, +einx/_src/namedtensor/stage1/__pycache__/tree.cpython-312.pyc,, +einx/_src/namedtensor/stage1/parse.py,sha256=AmTqM9LlFSrJqP_o9YS4yCXYnhFybOUkUPvGRFzYHnM,18078 +einx/_src/namedtensor/stage1/transform.py,sha256=Fo2-GcrN3bz1FrPNZmdxpHNtfnN7b2DiNe8cF0T3KTQ,4110 +einx/_src/namedtensor/stage1/tree.py,sha256=pscyQd_qYHBoy-v4-iV0W0PeDiBzwNv7Vi9XuejJcGg,10626 +einx/_src/namedtensor/stage2/__init__.py,sha256=dfm-TMNY0Is-L5p5g-CgNPzJPXrfm3KEiP8gtBe0KNg,284 +einx/_src/namedtensor/stage2/__pycache__/__init__.cpython-312.pyc,, +einx/_src/namedtensor/stage2/__pycache__/cse.cpython-312.pyc,, +einx/_src/namedtensor/stage2/__pycache__/solve.cpython-312.pyc,, +einx/_src/namedtensor/stage2/__pycache__/transform.cpython-312.pyc,, +einx/_src/namedtensor/stage2/__pycache__/tree.cpython-312.pyc,, +einx/_src/namedtensor/stage2/cse.py,sha256=_-Px2Eg2mk1lsBzcU8qad-OlwBEk-CRghXKgfAVhwME,9621 +einx/_src/namedtensor/stage2/solve.py,sha256=T7FERG-huagtwWeUNN8LPbc0wiER0QrcJWXc4zg-3lk,26077 +einx/_src/namedtensor/stage2/transform.py,sha256=94dFPzXM0EnGTdfL1pAipoUJ_8znF5o1uri9JjQtqCo,525 +einx/_src/namedtensor/stage2/tree.py,sha256=QOI6L0yZvaJikSVBpcpm6JXmAfqyEiLQC-MwbgNSGXg,6502 +einx/_src/namedtensor/stage3/__init__.py,sha256=fth6hW-u6Zs1xHT65Om66ErXLB49rH2VAdlZD0ZST8U,319 +einx/_src/namedtensor/stage3/__pycache__/__init__.cpython-312.pyc,, +einx/_src/namedtensor/stage3/__pycache__/solve.cpython-312.pyc,, +einx/_src/namedtensor/stage3/__pycache__/transform.cpython-312.pyc,, +einx/_src/namedtensor/stage3/__pycache__/tree.cpython-312.pyc,, +einx/_src/namedtensor/stage3/solve.py,sha256=IzVvn9I9EYq9WaVkzcx7Q1tXAS0MWVfn3u7YgeXufL0,6695 +einx/_src/namedtensor/stage3/transform.py,sha256=efasxH55TjpOSevp9yK4vsbPYjoWhGvub3BqA_Lb-Nk,2279 +einx/_src/namedtensor/stage3/tree.py,sha256=dzk7bygWw8SGVrDaukZLMmEpSelWirvWIVNJknvKzZY,6626 +einx/_src/namedtensor/util.py,sha256=fs-PvrwIdffbBmMQ-T7VzgHYMnoqn9d3nxQnHrrpVzo,3056 +einx/_src/tracer/__init__.py,sha256=qrfuDzUf-NEc6_xvqv0VXBFbucgIC6pXQpOHyt7X1ek,110 +einx/_src/tracer/__pycache__/__init__.cpython-312.pyc,, +einx/_src/tracer/__pycache__/graph.cpython-312.pyc,, +einx/_src/tracer/__pycache__/visualize.cpython-312.pyc,, +einx/_src/tracer/compiler/__init__.py,sha256=OnlVnHsKhKDKBdB2Eclp1sMOXvshSDt3PMgDJX12xaw,39 +einx/_src/tracer/compiler/__pycache__/__init__.cpython-312.pyc,, +einx/_src/tracer/compiler/__pycache__/run.cpython-312.pyc,, +einx/_src/tracer/compiler/python/__init__.py,sha256=fdxBsMGjWsP5vPJYlCFvQZ_EZZXS6bKoJBE6shiH1bU,25862 +einx/_src/tracer/compiler/python/__pycache__/__init__.cpython-312.pyc,, +einx/_src/tracer/compiler/python/__pycache__/scope.cpython-312.pyc,, +einx/_src/tracer/compiler/python/__pycache__/usage.cpython-312.pyc,, +einx/_src/tracer/compiler/python/scope.py,sha256=q15nuyNGEqhIEmPyv4X5LQqn-qK3VfmOrFjKt7EsEJQ,7176 +einx/_src/tracer/compiler/python/usage.py,sha256=4_G2lxN6SEa6RjJPuA9ITfpZtApbWwXfkrU2OJQDWWc,1525 +einx/_src/tracer/compiler/run.py,sha256=1yBWA007n9zsyRoJVYF-8fiiENfzfDxkqoDxTVDI1ow,4485 +einx/_src/tracer/graph.py,sha256=M-YWhH9dorkK89PnoW9PzPnDwXXAWpik4Gi26FME_gw,2638 +einx/_src/tracer/optimizer/__init__.py,sha256=8d81SiPX54ch7ZVOlywlCpm5AaADiEKtwzCsiRBJ0sw,83 +einx/_src/tracer/optimizer/__pycache__/__init__.cpython-312.pyc,, +einx/_src/tracer/optimizer/__pycache__/_util.cpython-312.pyc,, +einx/_src/tracer/optimizer/__pycache__/classical.cpython-312.pyc,, +einx/_src/tracer/optimizer/__pycache__/graph.cpython-312.pyc,, +einx/_src/tracer/optimizer/__pycache__/optimizer.cpython-312.pyc,, +einx/_src/tracer/optimizer/_util.py,sha256=9i1WONlvMcSgs4uyi8_KY1li3QvbYvjEDNA8gB5C1EY,696 +einx/_src/tracer/optimizer/classical.py,sha256=KMASQRXAPB6uHuew32sxX4_VIWFeW4uQk-FHIYNLO-A,3757 +einx/_src/tracer/optimizer/graph.py,sha256=9UW9FRTqgkNq-aZjEDV6RCy6MI0GnomfL11nK02gWIM,1641 +einx/_src/tracer/optimizer/optimizer.py,sha256=gY-Yom1UNHA3xGF8SpbdSO-U9HMoHE6ndtSOPttIkO8,2608 +einx/_src/tracer/signature/__init__.py,sha256=zGkxOYO-jqecwYSRw642JwbTwIhF4vqvhHpukVR2C1w,331 +einx/_src/tracer/signature/__pycache__/__init__.cpython-312.pyc,, +einx/_src/tracer/signature/__pycache__/python.cpython-312.pyc,, +einx/_src/tracer/signature/classical/__init__.py,sha256=DnI2THHk0kZQr3qN1QI2npJUGmaRNiGDXkAz00Bl_a4,656 +einx/_src/tracer/signature/classical/__pycache__/__init__.cpython-312.pyc,, +einx/_src/tracer/signature/classical/__pycache__/arrayapi.cpython-312.pyc,, +einx/_src/tracer/signature/classical/__pycache__/functions.cpython-312.pyc,, +einx/_src/tracer/signature/classical/__pycache__/jax.cpython-312.pyc,, +einx/_src/tracer/signature/classical/__pycache__/mlx.cpython-312.pyc,, +einx/_src/tracer/signature/classical/__pycache__/numpy.cpython-312.pyc,, +einx/_src/tracer/signature/classical/__pycache__/tensor.cpython-312.pyc,, +einx/_src/tracer/signature/classical/__pycache__/tensorflow.cpython-312.pyc,, +einx/_src/tracer/signature/classical/__pycache__/tinygrad.cpython-312.pyc,, +einx/_src/tracer/signature/classical/__pycache__/torch.cpython-312.pyc,, +einx/_src/tracer/signature/classical/arrayapi.py,sha256=LZG5Sa7-330GrTx-IlMvOnuFoixRTFDOPbRlM-cZ-MA,4538 +einx/_src/tracer/signature/classical/functions.py,sha256=VQXhMIlvS_aIDhdDdp73iOCSbh-oAqbgdmPuMy6DKtw,18105 +einx/_src/tracer/signature/classical/jax.py,sha256=RBsPilwQo8Fypt4JQsg1V7sk0Nk8uEyralLUoLQOxBA,793 +einx/_src/tracer/signature/classical/mlx.py,sha256=nrBOlnnnJq5VI29o5_VSQ8s81AYs6ekPPwDSwCNeB-8,4603 +einx/_src/tracer/signature/classical/numpy.py,sha256=lg_TaGT54fMtDbI8QKGumi_MaXk4MDm61yTTREUZFYE,4064 +einx/_src/tracer/signature/classical/tensor.py,sha256=WMFovqg75zRJMhXn8vM8u6elPkZqYelke-NcWbeqbPk,1640 +einx/_src/tracer/signature/classical/tensorflow.py,sha256=LOUbsXWGK2pvlwqSu0EG_pSue2RPBNEvukjBjou6_3I,5096 +einx/_src/tracer/signature/classical/tinygrad.py,sha256=LRMn-hdzr8z9z-kLlP0q_Zg8GIIRELE6ruxGjEVm1iM,4966 +einx/_src/tracer/signature/classical/torch.py,sha256=_tWgAUpI4QAqf1g9X9rTjuiQmNgL9pISv6j2SAhtLwA,5836 +einx/_src/tracer/signature/functorchdim/__init__.py,sha256=zX6CLp8JsH_1SVcJpTdcw59sPfLhlY0ND9eDa1IcQxA,27 +einx/_src/tracer/signature/functorchdim/__pycache__/__init__.cpython-312.pyc,, +einx/_src/tracer/signature/functorchdim/__pycache__/tensor.cpython-312.pyc,, +einx/_src/tracer/signature/functorchdim/tensor.py,sha256=tOloF9CPRp-AaRhpMMAwF6rjeCAxi6HBtU0-5k9TuP4,761 +einx/_src/tracer/signature/python.py,sha256=dUD4-rxWNN_aNieOUG6k_Q6unoujkXFsP69Pe_fJoqw,11532 +einx/_src/tracer/visualize.py,sha256=Lw2yvJo2RXkQys6lEi9hskUSXpulN28hLwVGPXf951w,4665 +einx/_src/util/__pycache__/functools.cpython-312.pyc,, +einx/_src/util/__pycache__/lru_cache.cpython-312.pyc,, +einx/_src/util/__pycache__/pytree.cpython-312.pyc,, +einx/_src/util/__pycache__/rwlock.cpython-312.pyc,, +einx/_src/util/__pycache__/solver.cpython-312.pyc,, +einx/_src/util/functools.py,sha256=kMJcCIg9y7iNlSlRqHYWFfkLpepkhrjQ-cVute4Zd2M,1135 +einx/_src/util/lru_cache.py,sha256=b1SvhqcTLuOwlzpWDVjFhdY5nDAV_Y8DK8QX3XV6IQo,3932 +einx/_src/util/pytree.py,sha256=5ix8EYBaMkI2wQkAHzZohwOsvhG6Yk1onM07Iu9r-GA,2144 +einx/_src/util/rwlock.py,sha256=Tji3XGScprQoQSq8WTzvCIVt4mOs0FbxeSnx-gnkI4s,1122 +einx/_src/util/solver.py,sha256=MyQN8HbGWevfqf0WB9xYSWGZvJwCFhUHyejAg0-Esrs,10062 +einx/arrayapi.py,sha256=2C6q09hg43CS6liHrmCLeE0aiv1_J2NokwIk98z9eHo,141 +einx/backend.py,sha256=ohNZ3TUfJtczMPmObs22F1pOzo9ovbXApQGJICqXbjs,81 +einx/errors.py,sha256=qhgVo9B9004jdRgrBrGyLWkHpSgoqwsRBj0jiNJJuhI,490 +einx/experimental/__init__.py,sha256=8o0-CKNoAJXVpCnBHyo6gXL-eBcobuyeohe5k-bXXzI,27 +einx/experimental/__pycache__/__init__.cpython-312.pyc,, +einx/experimental/__pycache__/functorchdim.cpython-312.pyc,, +einx/experimental/functorchdim.py,sha256=hYpZ-FojzgjdAcF83nNFxnYbI232soKc_IAKZowNe9Q,55 +einx/jax.py,sha256=PrVWBQ2sTq0zDZd0Eq9Ypk8NR29_TTh70IyfOn4MvC0,187 +einx/mlx.py,sha256=nCtjab5juAICnbMe128sEQdvXKe3zqR9w_7uyeAor1A,187 +einx/nn.py,sha256=XXreirNBA-1xnhW4dCyhm4ypTfAQvUhn48QFuqD1P5Y,147 +einx/numpy.py,sha256=IdbSmf1Z1NS0oSf4xussDJ5ArJ1a279x2jFDGXz29rQ,135 +einx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +einx/tensorflow.py,sha256=Fwptzf6xr7xM-7F0oBKHkE_Vaoj-hGq87oHySkrd-OQ,145 +einx/tinygrad.py,sha256=p-9NHUGE-SttE3DQ_O4gZC5AO6sAxS5xxbhVScM2ZTE,141 +einx/torch.py,sha256=9G7axmoHCi5ejOLO2SJqfO4rsvBLodIINkTXXalS3QA,193 +test/__pycache__/conftest.cpython-312.pyc,, +test/__pycache__/test_adapt.cpython-312.pyc,, +test/__pycache__/test_backend_resolution.cpython-312.pyc,, +test/__pycache__/test_compare_libs.cpython-312.pyc,, +test/__pycache__/test_compilation.cpython-312.pyc,, +test/__pycache__/test_experimental.cpython-312.pyc,, +test/__pycache__/test_invalid_backend.cpython-312.pyc,, +test/__pycache__/test_invalid_backend_version.cpython-312.pyc,, +test/__pycache__/test_shapes.cpython-312.pyc,, +test/__pycache__/test_tensor_conversion.cpython-312.pyc,, +test/__pycache__/test_values.cpython-312.pyc,, +test/conftest.py,sha256=mUEy-1rHl-JjjltbQzd5aHmavIYzyCEdSMu5e1zKFW0,20650 +test/test_adapt.py,sha256=S1INbmyCQg_VoqoNk0MAL0c9LAiMLgAFpHsICe0ZqXI,3973 +test/test_backend_resolution.py,sha256=b4lOO5ri_shz4HB3eKxC2f5kIKQkSHdDEf6y2PsGlc0,865 +test/test_compare_libs.py,sha256=dUCYdDEn2Yq-tTcxApU7akB2yQZcvdFyzEZbchJXcgE,28067 +test/test_compilation.py,sha256=voN2U5CWrIZkemsgxb5cIPItsv3un99kZg8VbR93cqw,1291 +test/test_experimental.py,sha256=FhF-kr8lX3vDnl5Co0alGBOOWA-VlOD4BP2O5GtoAjg,855 +test/test_invalid_backend.py,sha256=5I1myJdVuryMo04ekI3sjdsxIGpJnFnf0kPKVpZJNcg,564 +test/test_invalid_backend_version.py,sha256=IJJnrfCXE5wMqp_CcOuAtOj8KBLhSOkGnuhhV3E-OmI,681 +test/test_shapes.py,sha256=VZh0D3eOA4U8FGw28nFWfvTxBAW74w1iVy2gPNq11H4,62209 +test/test_tensor_conversion.py,sha256=xp8TmrHAT0apB0pu2-ixyT9QWzFhEYCisE4Ybn6-u38,13481 +test/test_values.py,sha256=4-8awpOzuxdVi_yNznLcchGyV9iG3BRLepc6WuwAmhg,9477 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/REQUESTED b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/WHEEL b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/licenses/LICENSE b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..62142df05e1d3d45f8f7159ec20fab2f5316346f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023- Florian Fervers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/top_level.txt b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..8f43d5ab81c56abc144a07b9f6bf4b2c4633174e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx-0.4.3.dist-info/top_level.txt @@ -0,0 +1,3 @@ +docs +einx +test diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7d3b6cf4c95f7f4b104d57bf11e9ade867fbfdb0 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__init__.py @@ -0,0 +1,100 @@ +from einx._src.frontend.types import Tensor + +from einx._src.frontend.ops import id + +from einx._src.frontend.ops import sum +from einx._src.frontend.ops import mean +from einx._src.frontend.ops import var +from einx._src.frontend.ops import std +from einx._src.frontend.ops import prod +from einx._src.frontend.ops import count_nonzero +from einx._src.frontend.ops import any +from einx._src.frontend.ops import all +from einx._src.frontend.ops import max +from einx._src.frontend.ops import min +from einx._src.frontend.ops import logsumexp + +from einx._src.frontend.ops import add +from einx._src.frontend.ops import subtract +from einx._src.frontend.ops import multiply +from einx._src.frontend.ops import true_divide +from einx._src.frontend.ops import floor_divide +from einx._src.frontend.ops import divide +from einx._src.frontend.ops import logical_and +from einx._src.frontend.ops import logical_or +from einx._src.frontend.ops import where +from einx._src.frontend.ops import maximum +from einx._src.frontend.ops import minimum +from einx._src.frontend.ops import less +from einx._src.frontend.ops import less_equal +from einx._src.frontend.ops import greater +from einx._src.frontend.ops import greater_equal +from einx._src.frontend.ops import equal +from einx._src.frontend.ops import not_equal +from einx._src.frontend.ops import logaddexp + +from einx._src.frontend.ops import dot + +from einx._src.frontend.ops import get_at +from einx._src.frontend.ops import set_at +from einx._src.frontend.ops import add_at +from einx._src.frontend.ops import subtract_at + +from einx._src.frontend.ops import softmax +from einx._src.frontend.ops import log_softmax +from einx._src.frontend.ops import sort +from einx._src.frontend.ops import argsort +from einx._src.frontend.ops import flip +from einx._src.frontend.ops import roll + +from einx._src.frontend.ops import argmax +from einx._src.frontend.ops import argmin + +from einx._src.frontend.removed_ops import rearrange +from einx._src.frontend.removed_ops import vmap +from einx._src.frontend.removed_ops import vmap_with_axis +from einx._src.frontend.removed_ops import reduce +from einx._src.frontend.removed_ops import elementwise +from einx._src.frontend.removed_ops import arange + +from einx._src.frontend.util import matches +from einx._src.frontend.util import solve +from einx._src.frontend.util import solve_shapes +from einx._src.frontend.util import solve_axes +from einx._src.frontend.util import check + +from einx._src.frontend.impl import numpy + +del numpy +from einx._src.frontend.impl import torch + +del torch +from einx._src.frontend.impl import jax + +del jax +from einx._src.frontend.impl import mlx + +del mlx +from einx._src.frontend.impl import tensorflow + +del tensorflow +from einx._src.frontend.impl import arrayapi + +del arrayapi +from einx._src.frontend.impl import tinygrad + +del tinygrad + +from . import backend +from . import numpy +from . import jax +from . import torch +from . import mlx +from . import tensorflow +from . import arrayapi +from . import tinygrad + +from . import errors +from . import experimental + +__version__ = "0.4.3" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3768c0ba0a60b2f84f64157655312df329b3cd8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/arrayapi.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/arrayapi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..537c393a5743012ae1552eef6844e3ee14f9a655 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/arrayapi.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/backend.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/backend.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8af0977a4ea6671aa1c042cee49706b0ced13f8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/backend.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/errors.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/errors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6639b9f583333a3c2c54f16839db24d84b40adb Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/errors.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/jax.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/jax.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe572a417d5293fcd24f8f7441f9501a5f1cb165 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/jax.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/mlx.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/mlx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e48d8a530fdcde33605e6f783acf9e872cd6668 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/mlx.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/nn.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/nn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..235288f3f19975dfd84593d3e33bde3064b7e332 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/nn.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/numpy.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/numpy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3307d832ddbc88717645c3fb47abfa7b9e5f99ef Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/numpy.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/tensorflow.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/tensorflow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51c56f5c7367f2150f6ebd20475153523afab70e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/tensorflow.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/tinygrad.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/tinygrad.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6cb2a8d902aad5370b2772d013fefa7b65a4cf7 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/tinygrad.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/torch.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a104a2e4afcfd993a9067e837500d31c96b3687 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/__pycache__/torch.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2aad0de69ba70c9db1c05c7366488c0493625c6c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__init__.py @@ -0,0 +1,42 @@ +from . import ops + +from . import einx_from_namedtensor +from . import namedtensor_from_decomposednamedtensor +from . import decomposednamedtensor_from_classical +from . import decomposednamedtensor_from_einsum +from . import decomposednamedtensor_from_vmap +from . import elementary_from_classical +from . import classical_from_classical +from . import classical_from_einsum + +from .namedtensor_calltensorfactory import namedtensor_calltensorfactory + +from .numpy import classical_from_numpy +from .numpy.einsum_from_numpy import einsum_from_numpy + +from .jax import classical_from_jax +from .jax.einsum_from_jax import einsum_from_jax +from .jax.vmap_from_jax import vmap_from_jax + +from .torch import classical_from_torch +from .torch.einsum_from_torch import einsum_from_torch +from .torch.vmap_from_torch import vmap_from_torch +from .torch.devicestack import TorchDeviceStack + +from .mlx import classical_from_mlx +from .mlx.einsum_from_mlx import einsum_from_mlx +from .mlx.vmap_from_mlx import vmap_from_mlx + +from .tensorflow import classical_from_tensorflow +from .tensorflow.einsum_from_tensorflow import einsum_from_tensorflow + +from .arrayapi import classical_from_arrayapi +from .arrayapi.einsum_from_arrayapi import einsum_from_arrayapi +from .arrayapi.tensortype_from_arrayapi import tensortype_from_arrayapi +from .arrayapi.namespacestack import ArrayApiNamespaceStack + +from .tinygrad import classical_from_tinygrad +from .tinygrad.einsum_from_tinygrad import einsum_from_tinygrad + +# Experimental: +from .functorchdim import namedtensor_from_functorchdim diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ea5ad057c0de9e1a638e2422fb2cd60d4309a6c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/_util.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05a6a35b53795e7e1f7a05806a7302bdeba1de92 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/_util.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/classical_from_classical.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/classical_from_classical.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..189cf5bd65faaed08af775cd1d7249c24da8ec27 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/classical_from_classical.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/classical_from_einsum.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/classical_from_einsum.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa6b1c91a6d6301904b25a64c7f0e923c1ebc9a4 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/classical_from_einsum.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/decomposednamedtensor_from_classical.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/decomposednamedtensor_from_classical.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3ed04bdb1e71852a742d23cd4e06f1de0babc03 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/decomposednamedtensor_from_classical.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/decomposednamedtensor_from_einsum.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/decomposednamedtensor_from_einsum.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54fb91f4bf75c83d7d93fcdb8f40db7d267b99c8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/decomposednamedtensor_from_einsum.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/decomposednamedtensor_from_vmap.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/decomposednamedtensor_from_vmap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..417d10c7e58aac6adf8664dcf1791d7e525bddd7 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/decomposednamedtensor_from_vmap.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/einx_from_namedtensor.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/einx_from_namedtensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7189b8e693d507d2df5949fed82182b4464c279 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/einx_from_namedtensor.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/elementary_from_classical.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/elementary_from_classical.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bec66e2b154f1fa406624029141a5a96ec6f92d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/elementary_from_classical.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/namedtensor_calltensorfactory.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/namedtensor_calltensorfactory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..261aaf8b51817dd7f6b14a9d24fba38b973933e0 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/namedtensor_calltensorfactory.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/namedtensor_from_decomposednamedtensor.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/namedtensor_from_decomposednamedtensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3742501457972e7007d3922676f1548434aaadf Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/namedtensor_from_decomposednamedtensor.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/ops.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82c8f475feb6d6bf375cf2cce64006f22af0a3c1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/__pycache__/ops.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/_util.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..eebdb3b89dbe4589c6dc87e8ef6167b884fcc7ca --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/_util.py @@ -0,0 +1,302 @@ +import einx._src.namedtensor.stage3 as stage3 +import numpy as np +import functools +import einx._src.tracer as tracer +import einx._src.util.pytree as pytree +from einx._src.util.functools import use_name_of +from einx._src.frontend.errors import OperationNotSupportedError + + +def _axis_to_axisint(axis, name="axis"): + if isinstance(axis, int | np.integer): + return axis + elif isinstance(axis, list | tuple | np.ndarray): + if len(axis) != 1: + raise ValueError(f"Expected {name} to be a single integer or a list/tuple/array of length 1, but got {axis}") + return axis[0] + else: + raise ValueError(f"Expected {name} to be an integer or a list/tuple/array, but got {type(axis)}") + + +def _axis_to_axistuple(axis, name="axis"): + if isinstance(axis, int | np.integer): + return (axis,) + elif isinstance(axis, list | tuple | np.ndarray): + return tuple(axis) + else: + raise ValueError(f"Expected {name} to be an integer or a list/tuple/array, but got {type(axis)}") + + +def _associative_binary_to_nary(binary_op): + def nary_op(*args): + x = args[0] + for y in args[1:]: + x = binary_op(x, y) + return x + + return nary_op + + +def _unsqueeze(classical, tensor, axis): + if axis < 0: + axis += tensor.ndim + 1 + if axis < 0 or axis > tensor.ndim: + raise ValueError(f"Axis {axis} is out of bounds for tensor with {tensor.ndim} dimensions.") + + new_shape = list(tensor.shape) + new_shape.insert(axis, 1) + return classical.reshape(tensor, new_shape) + + +def _stack(classical, tensors, axis): + if axis < 0: + axis += len(tensors[0].shape) + 1 + if axis < 0 or axis > len(tensors[0].shape): + raise ValueError(f"Axis {axis} is out of bounds for tensors with {len(tensors[0].shape)} dimensions.") + + tensors = [_unsqueeze(classical, tensor, axis) for tensor in tensors] + return classical.concatenate(tensors, axis=axis) + + +def _squeeze_transpose_broadcast(classical, expr_in, tensor, expr_out, broadcast_to_unitary=False): + # Squeeze axes if necessary + squeezable_in_axes = [a.name for a in expr_in.nodes() if isinstance(a, stage3.Axis) and a.value == 1] + out_axes = [a.name for a in expr_out.nodes() if isinstance(a, stage3.Axis)] + squeeze_axes = set(squeezable_in_axes) - set(out_axes) + if len(squeeze_axes) > 0: + expr_in = stage3.remove(expr_in, lambda a: isinstance(a, stage3.Axis) and a.name in squeeze_axes, keep_children=False) + tensor = classical.reshape(tensor, expr_in.shape) + + # Transpose axes if necessary + def _to_axis_ids(expr): + counts = {} + axes = [] + for a in expr.nodes(): + if isinstance(a, stage3.Axis): + c = counts.get(a.name, 0) + axes.append((a.name, c)) + counts[a.name] = c + 1 + return axes + + in_axes = _to_axis_ids(expr_in) + out_axes = _to_axis_ids(expr_out) + out_axes_intersect = [a for a in out_axes if a in in_axes] + if set(out_axes_intersect) != set(in_axes): + invalid_axes = set(in_axes) - set(out_axes_intersect) + invalid_axes = {name for name, count in invalid_axes} + if len(invalid_axes) == 1: + invalid_axes = f"axis {invalid_axes.pop()} does" + else: + invalid_axes = f"axes {', '.join(invalid_axes)} do" + raise ValueError(f"The input {invalid_axes} not appear in the corresponding output expression.") + + perm = [in_axes.index(out_axis) for out_axis in out_axes_intersect] + tensor = classical.transpose(tensor, tuple(perm)) + + # Expand and broadcast missing output dimensions if necessary + in_axes = [a.name for a in expr_in.nodes() if isinstance(a, stage3.Axis)] + out_axes = [a.name for a in expr_out.nodes() if isinstance(a, stage3.Axis)] + out_axes_broadcast = [a for a in out_axes if a not in in_axes] + if len(out_axes_broadcast) > 0: + pre_broadcast_shape = tuple(1 if a.name in out_axes_broadcast else a.value for a in expr_out.nodes() if isinstance(a, stage3.Axis)) + tensor = classical.reshape(tensor, pre_broadcast_shape) + if not broadcast_to_unitary: + tensor = classical.broadcast_to(tensor, expr_out.shape) + + if broadcast_to_unitary: + expr_out = stage3.List.create([(axis if axis.name in in_axes else stage3.Axis.new_unnamed(1)) for axis in expr_out]) + return expr_out, tensor + + +def _squeeze_shape(shape): + return tuple(s for s in shape if s != 1) + + +def _squeeze_unsqueeze(classical, tensor, shape): + if _squeeze_shape(tensor.shape) != _squeeze_shape(shape): + raise ValueError(f"Expected tensor with shape {tensor.shape} to have the same squeezed shape as {shape}") + return classical.reshape(tensor, shape) + + +def _unravel(classical, tensor, ravel_shape, axis): + # 1D does not need to be unravelled + if len(ravel_shape) == 1: + if axis is None: + return tensor + else: + return _unsqueeze(classical, tensor, axis) + + out_indices = [None] * len(ravel_shape) + for i, s in reversed(list(enumerate(ravel_shape))): + tensor, out_indices[i] = classical.divmod(tensor, s) + + out_indices = _stack(classical, out_indices, axis=axis) + + return out_indices + + +def _to_ord_str(i): + if i == 0: + return "1st" + elif i == 1: + return "2nd" + elif i == 2: + return "3rd" + else: + return f"{i + 1}th" + + +def _ensure_output(op, expected_out_shapes, expected_type=None, allow_squeeze_unsqueeze=False, classical=None): + if allow_squeeze_unsqueeze: + if classical is None: + raise ValueError("classical must be provided if allow_squeeze_unsqueeze=True") + expected_type2 = expected_type + + @use_name_of(op) + def inner(*args, **kwargs): + expected_type = expected_type2 + if callable(expected_type) and not isinstance(expected_type, type) and not isinstance(expected_type, tracer.Tracer): + expected_type = expected_type() + + tensors_out = op(*args, **kwargs) + if isinstance(tensors_out, tracer.Tracer): + # Create list of tracers + if len(expected_out_shapes) == 1: + tensors_out = [tensors_out] + else: + tensors_out = tracer.signature.python.assert_( + tensors_out, + tracer.signature.python.builtins.isinstance(tensors_out, tracer.signature.python.builtins.tuple), + f"Expected the adapted function to return a tuple of length {len(expected_out_shapes)}", + ) + tensors_out = tracer.signature.python.assert_( + tensors_out, + tracer.signature.python.equal(tracer.signature.python.builtins.len(tensors_out), len(expected_out_shapes)), + f"Expected the adapted function to return a tuple of length {len(expected_out_shapes)}", + ) + tensors_out = tracer.cast(tensors_out, lambda origin: [tracer.signature.python.Value(origin) for _ in range(len(expected_out_shapes))]) + elif isinstance(tensors_out, tuple) and all(isinstance(t, tracer.Tracer) for t in tensors_out): + # Return value already is a tuple of tracers + if len(tensors_out) != len(expected_out_shapes): + raise ValueError(f"Expected the adapted function to return a tuple of length {len(expected_out_shapes)}, but got length {len(tensors_out)}") + else: + raise ValueError(f"Expected the adapted function to return a tracer or a tuple of tracers, but got {pytree.map(type, tensors_out)}") + + tensors_out2 = [] + for i, (tensor, expected_out_shape) in enumerate(zip(tensors_out, expected_out_shapes, strict=False)): + if isinstance(tensor, tracer.signature.classical.Tensor | tracer.signature.classical.ConvertibleTensor): + # Return type is a tensor -> ensure that the static shape is correct + t = _squeeze_shape if allow_squeeze_unsqueeze else tuple + if t(tensor.shape) != t(expected_out_shape): + raise ValueError( + f"Expected {_to_ord_str(i)} return value of the adapted function to be a tensor with shape {expected_out_shape}, " + f"but got shape {tensor.shape}" + ) + if allow_squeeze_unsqueeze: + tensor = _squeeze_unsqueeze(classical, tensor, expected_out_shape) + else: + # Return type is a general tracer object -> ensure that it has the correct type and that the shape is correct at runtime. + # Then cast to expected shape + if expected_type is not None: + tensor = tracer.signature.python.assert_( + tensor, + tracer.signature.python.builtins.isinstance(tensor, expected_type), + f"Expected {_to_ord_str(i)} return value of the adapted function to be a tensor", + ) + if allow_squeeze_unsqueeze: + raise ValueError( + "allow_squeeze_unsqueeze=True cannot currently be used if return type of the adapted function is a general tracer object, not a tensor." + ) + tensor = tracer.signature.python.assert_( + tensor, + tracer.signature.python.equal(tracer.signature.python.builtins.tuple(tensor.shape), expected_out_shape), + f"Expected {_to_ord_str(i)} return value of the adapted function to be a tensor with shape {expected_out_shape}", + ) + tensor = tracer.cast(tensor, lambda origin: tracer.signature.classical.Tensor(origin, shape=expected_out_shape)) + tensors_out2.append(tensor) + tensors_out = tensors_out2 + + if len(tensors_out) == 1: + return tensors_out[0] + else: + return tuple(tensors_out) + + return inner + + +def _make_concrete_types(concrete_types): + concrete_types2 = [] + for t in concrete_types: + if isinstance(t, str): + if t == "scalar": + concrete_types2.extend([int, float, bool, np.integer, np.floating, np.bool_]) + elif t == "numpy": + concrete_types2.append(np.ndarray) + else: + raise ValueError(f"Unknown concrete type string: {t}") + elif isinstance(t, tracer.Tracer): + pass + else: + assert isinstance(t, type) + concrete_types2.append(t) + return tuple(concrete_types2) + + +def _has_type(x, types): + types = _make_concrete_types(types) + return isinstance(x, types) or (isinstance(x, tracer.signature.classical.ConvertibleTensor) and issubclass(x.concrete.type, types)) + + +def _is_scalar(x): + return isinstance(x, int | float | bool | np.integer | np.floating | np.bool_) + + +def _get_shape(x): + if _is_scalar(x): + return () + elif isinstance(x, np.ndarray): + return x.shape + elif isinstance(x, tracer.signature.classical.Tensor | tracer.signature.classical.ConvertibleTensor): + return x.shape + else: + raise ValueError(f"Cannot determine shape of object with type {type(x)}.") + + +def _to_tensor(to_tensor, forward, convert): + _to_tensor = to_tensor + forward = _make_concrete_types(forward) + convert = _make_concrete_types(convert) + + def to_tensor(x): + if isinstance(x, (*forward, tracer.signature.classical.Tensor)): + return x + elif isinstance(x, tracer.signature.classical.ConvertibleTensor): + if issubclass(x.concrete.type, forward): + return x + elif issubclass(x.concrete.type, convert): + shape = x.shape + x = _to_tensor(x) + x = tracer.cast(x, lambda origin: tracer.signature.classical.Tensor(origin, shape=shape)) + return x + else: + raise ValueError(f"An object of type {x.concrete.type} cannot be used as a tensor") + elif isinstance(x, (*convert,)): + shape = _get_shape(x) + x = _to_tensor(x) + x = tracer.cast(x, lambda origin: tracer.signature.classical.Tensor(origin, shape=shape)) + return x + else: + raise ValueError(f"Expected a tensor, but got {type(x)}") + + return to_tensor + + +def _unsupported_op(name, backend, message=None): + def op(*args, **kwargs): + message2 = f"{name} operation is not supported by the {backend} backend." + if message is not None: + message2 += " " + message + raise OperationNotSupportedError(message2) + + op.__name__ = name + return op diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/classical_from_arrayapi.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/classical_from_arrayapi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..679bed040280ca7d03b7066a58977f3adea4cf00 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/classical_from_arrayapi.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/einsum_from_arrayapi.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/einsum_from_arrayapi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a14394e22fd8cae2e1b773cec361b4ed71815a94 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/einsum_from_arrayapi.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/namespacestack.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/namespacestack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae08a6813f4393e26c134bb6a51f5c4115f9da8e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/namespacestack.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/tensortype_from_arrayapi.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/tensortype_from_arrayapi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..385c66441da5f6d17f07beb7498487414e252633 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/__pycache__/tensortype_from_arrayapi.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/classical_from_arrayapi.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/classical_from_arrayapi.py new file mode 100644 index 0000000000000000000000000000000000000000..1881bd294a29801f10641faa943c9baa45b1da8d --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/classical_from_arrayapi.py @@ -0,0 +1,89 @@ +import einx._src.adapter as adapter +import numpy as np +from functools import partial +from einx._src.util.functools import use_name_of +from .._util import _associative_binary_to_nary, _to_tensor, _unsupported_op + + +class ops: + def __init__(self, xp): + def to_tensor_all(*args): + to_tensor_one = _to_tensor(xp.asarray, forward=[adapter.tensortype_from_arrayapi(xp)], convert=["numpy", "scalar"]) + return [to_tensor_one(arg) for arg in args] + + def _to_dtype(x): + if isinstance(x, str): + return getattr(xp, x) + else: + return x + + self.reshape = adapter.classical_from_numpy.reshape(xp.reshape, to_tensor=to_tensor_all) + self.transpose = adapter.classical_from_numpy.transpose(xp.permute_dims, to_tensor=to_tensor_all) + self.broadcast_to = adapter.classical_from_numpy.broadcast_to(xp.broadcast_to, to_tensor=to_tensor_all) + self.diagonal = adapter.classical_from_numpy.diagonal(xp.linalg.diagonal, self.transpose, to_tensor=to_tensor_all, axis_always_last=True) + self.stop_gradient = lambda x: x + + self.add = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(xp.add), to_tensor=to_tensor_all) + self.subtract = adapter.classical_from_numpy.elementwise(xp.subtract, to_tensor=to_tensor_all) + self.multiply = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(xp.multiply), to_tensor=to_tensor_all) + self.true_divide = adapter.classical_from_numpy.elementwise(xp.true_divide, to_tensor=to_tensor_all) + self.floor_divide = adapter.classical_from_numpy.elementwise(xp.floor_divide, to_tensor=to_tensor_all) + self.divide = adapter.classical_from_numpy.elementwise(xp.divide, to_tensor=to_tensor_all) + self.logaddexp = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(xp.logaddexp), to_tensor=to_tensor_all) + self.logical_and = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(xp.logical_and), to_tensor=to_tensor_all) + self.logical_or = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(xp.logical_or), to_tensor=to_tensor_all) + self.where = adapter.classical_from_numpy.elementwise(xp.where, to_tensor=to_tensor_all) + self.maximum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(xp.maximum), to_tensor=to_tensor_all) + self.minimum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(xp.minimum), to_tensor=to_tensor_all) + self.less = adapter.classical_from_numpy.elementwise(xp.less, to_tensor=to_tensor_all) + self.less_equal = adapter.classical_from_numpy.elementwise(xp.less_equal, to_tensor=to_tensor_all) + self.greater = adapter.classical_from_numpy.elementwise(xp.greater, to_tensor=to_tensor_all) + self.greater_equal = adapter.classical_from_numpy.elementwise(xp.greater_equal, to_tensor=to_tensor_all) + self.equal = adapter.classical_from_numpy.elementwise(xp.equal, to_tensor=to_tensor_all) + self.not_equal = adapter.classical_from_numpy.elementwise(xp.not_equal, to_tensor=to_tensor_all) + self.exp = adapter.classical_from_numpy.elementwise(xp.exp, to_tensor=to_tensor_all) + self.log = adapter.classical_from_numpy.elementwise(xp.log, to_tensor=to_tensor_all) + self.negative = adapter.classical_from_numpy.elementwise(xp.negative, to_tensor=to_tensor_all) + self.divmod = adapter.classical_from_numpy.elementwise(lambda x, y: (xp.floor_divide(x, y), xp.remainder(x, y)), to_tensor=to_tensor_all) + + self.sum = adapter.classical_from_numpy.reduce(xp.sum, to_tensor=to_tensor_all) + self.mean = adapter.classical_from_numpy.reduce(xp.mean, to_tensor=to_tensor_all) + self.var = adapter.classical_from_numpy.reduce(xp.var, to_tensor=to_tensor_all) + self.std = adapter.classical_from_numpy.reduce(xp.std, to_tensor=to_tensor_all) + self.prod = adapter.classical_from_numpy.reduce(xp.prod, to_tensor=to_tensor_all) + self.count_nonzero = adapter.classical_from_numpy.reduce(xp.count_nonzero, to_tensor=to_tensor_all) + self.any = adapter.classical_from_numpy.reduce(xp.any, to_tensor=to_tensor_all) + self.all = adapter.classical_from_numpy.reduce(xp.all, to_tensor=to_tensor_all) + self.max = adapter.classical_from_numpy.reduce(xp.max, to_tensor=to_tensor_all) + self.min = adapter.classical_from_numpy.reduce(xp.min, to_tensor=to_tensor_all) + self.logsumexp = adapter.classical_from_classical.logsumexp(self) + self.argmax = adapter.classical_from_numpy.reduce(xp.argmax, to_tensor=to_tensor_all) + self.argmin = adapter.classical_from_numpy.reduce(xp.argmin, to_tensor=to_tensor_all) + + self.sort = adapter.classical_from_numpy.sort(xp.sort, to_tensor=to_tensor_all) + self.argsort = adapter.classical_from_numpy.sort(xp.argsort, to_tensor=to_tensor_all) + self.roll = adapter.classical_from_numpy.roll(xp.roll, to_tensor=to_tensor_all) + self.flip = adapter.classical_from_numpy.preserve_shape(xp.flip, to_tensor=to_tensor_all) + self.softmax = adapter.classical_from_classical.softmax(self) + self.log_softmax = adapter.classical_from_classical.log_softmax(self) + + def to_tensor_index(x, *args): + x = _to_tensor(xp.asarray, forward=[adapter.tensortype_from_arrayapi(xp)], convert=["numpy", "scalar"])(x) + args = [_to_tensor(xp.asarray, forward=[adapter.tensortype_from_arrayapi(xp), "scalar"], convert=["numpy"])(a) for a in args] + return x, *args + + if hasattr(xp, "getitem"): + getitem = xp.getitem + else: + getitem = lambda x, indices: x[indices] + + self.get_at = adapter.classical_from_numpy.get_at(getitem, xp.take, to_tensor=to_tensor_index, reshape=self.reshape) + self.set_at = _unsupported_op("set_at", "arrayapi") + self.add_at = _unsupported_op("add_at", "arrayapi") + self.subtract_at = _unsupported_op("subtract_at", "arrayapi") + + self.arange = adapter.classical_from_numpy.arange(xp.arange, to_dtype=_to_dtype) + self.split = _unsupported_op("split", "arrayapi") + self.concatenate = adapter.classical_from_numpy.concatenate(xp.concat, to_tensor=to_tensor_all) + self.dot = adapter.classical_from_numpy.dot(xp.dot, to_tensor=to_tensor_all) + self.matmul = adapter.classical_from_numpy.matmul(xp.matmul, to_tensor=to_tensor_all) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/einsum_from_arrayapi.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/einsum_from_arrayapi.py new file mode 100644 index 0000000000000000000000000000000000000000..d6cb5d026706a7370a6c6cd1382f34bd15049c6d --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/einsum_from_arrayapi.py @@ -0,0 +1,10 @@ +import einx._src.adapter as adapter +from .._util import _to_tensor + + +def einsum_from_arrayapi(xp): + def to_tensor(*args): + to_tensor_one = _to_tensor(xp.asarray, forward=[adapter.tensortype_from_arrayapi(xp)], convert=["numpy", "scalar"]) + return [to_tensor_one(arg) for arg in args] + + return adapter.einsum_from_numpy(xp.einsum, to_tensor=to_tensor) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/namespacestack.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/namespacestack.py new file mode 100644 index 0000000000000000000000000000000000000000..00f646063538656104072390f44eb6d142b9efaa --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/namespacestack.py @@ -0,0 +1,54 @@ +from einx._src.util.functools import use_name_of +import threading +from contextlib import contextmanager +import einx._src.tracer as tracer +import types + + +class ArrayApiNamespaceStack: + def __init__(self): + self._thread_local = threading.local() + self.namedtensor = types.SimpleNamespace(op=self._wrap_namedtensor_op, ops=self._wrap_namedtensor_ops) + self.array_api_compat = tracer.signature.python.import_("array_api_compat") + + def get_xp(self): + stack = self._get_stack() + assert len(stack) > 0 + return stack[-1] + + def _wrap_namedtensor_op(self, op): + @use_name_of(op) + def inner(*tensors, out, **kwargs): + self._enter([t.value for t in tensors]) + try: + return op(*tensors, out=out, **kwargs) + finally: + self._exit([t.value for t in tensors]) + + return inner + + def _wrap_namedtensor_ops(self, ops): + return {name: self._wrap_namedtensor_op(op) for name, op in ops.items()} + + def _get_stack(self): + if not hasattr(self._thread_local, "stack"): + self._thread_local.stack = [] + return self._thread_local.stack + + def _enter(self, tensors): + xp = self.array_api_compat.array_namespace(*tensors) + stack = self._get_stack() + stack.append(xp) + + def _exit(self, tensors): + stack = self._get_stack() + assert len(stack) > 0 + stack.pop() + + @contextmanager + def __call__(self, tensors): + self._enter(tensors) + try: + yield + finally: + self._exit(tensors) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/tensortype_from_arrayapi.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/tensortype_from_arrayapi.py new file mode 100644 index 0000000000000000000000000000000000000000..c593e78f76a199fb37b25396f3197af769504fc1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/arrayapi/tensortype_from_arrayapi.py @@ -0,0 +1,12 @@ +import einx._src.tracer as tracer + + +def tensortype_from_arrayapi(xp): + if hasattr(xp, "_get_xp"): + typing = tracer.signature.python.import_("typing") + type = typing.get_type_hints(xp._get_xp().asarray)["return"] + else: + import typing + + type = typing.get_type_hints(xp.asarray)["return"] + return type diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/classical_from_classical.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/classical_from_classical.py new file mode 100644 index 0000000000000000000000000000000000000000..3be42eabd4ae6318552b551e0793e6bd566d63c2 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/classical_from_classical.py @@ -0,0 +1,84 @@ +from ._util import _axis_to_axistuple + + +def logsumexp(classical): + def logsumexp(x, axis=None, keepdims=False): + if axis is None: + axes = tuple(range(x.ndim)) + else: + axes = _axis_to_axistuple(axis) + + x_max_keepdims = classical.max(x, axis=axis, keepdims=True) + x_max_keepdims = classical.stop_gradient(x_max_keepdims) + x_max_dropdims = classical.reshape(x_max_keepdims, tuple(s for i, s in enumerate(x_max_keepdims.shape) if i not in axes)) + + x = classical.subtract(x, x_max_keepdims) + x = classical.log(classical.sum(classical.exp(x), axis=axis, keepdims=keepdims)) + x = classical.add(x, x_max_keepdims if keepdims else x_max_dropdims) + + return x + + return logsumexp + + +def logaddexp(classical): + def logaddexp(*xs): + x_max = classical.maximum(*xs) + x_max = classical.stop_gradient(x_max) + + xs = [classical.subtract(x, x_max) for x in xs] + x = classical.log(classical.add(*[classical.exp(x) for x in xs])) + x = classical.add(x, x_max) + + return x + + return logaddexp + + +def softmax(classical): + def softmax(x, axis=None): + x_max = classical.max(x, axis=axis, keepdims=True) + x_max = classical.stop_gradient(x_max) + x = classical.subtract(x, x_max) + + x_exp = classical.exp(x) + + return classical.divide(x_exp, classical.sum(x_exp, axis=axis, keepdims=True)) + + return softmax + + +def log_softmax(classical): + def log_softmax(x, axis=None): + return classical.subtract(x, logsumexp(classical)(x, axis=axis, keepdims=True)) + + return log_softmax + + +def count_nonzero(classical): + def count_nonzero(x, axis=None): + return classical.sum(classical.not_equal(x, 0), axis=axis) + + return count_nonzero + + +def flip(classical, getitem): + def flip(x, axis=None): + if isinstance(axis, int): + axis = (axis,) + if axis is None: + axis = tuple(range(x.ndim)) + + def _shift(axis): + if axis < -x.ndim or axis >= x.ndim: + raise ValueError(f"Invalid axis {axis} for array with {x.ndim} dimensions.") + if axis < 0: + axis += x.ndim + return axis + + axis = tuple(_shift(a) for a in axis) + + x = getitem(x, tuple(slice(None) if i not in axis else slice(None, None, -1) for i in range(x.ndim))) + return x + + return flip diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/classical_from_einsum.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/classical_from_einsum.py new file mode 100644 index 0000000000000000000000000000000000000000..7b5526922fb6b913f8973d0f6be7d8aa4755f22c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/classical_from_einsum.py @@ -0,0 +1,36 @@ +def _einsum_diag_string(ndim, axes_in, axis_out): + _next_ord = 1 + + def get_input_name_at(idx): + nonlocal _next_ord + if idx in axes_in: + return "a" + else: + result = chr(ord("a") + _next_ord) + _next_ord += 1 + return result + + einsum_str_input = "".join(get_input_name_at(i) for i in range(ndim)) + + _next_ord = 1 + + def get_output_name_at(idx): + nonlocal _next_ord + if idx == axis_out: + return "a" + else: + result = chr(ord("a") + _next_ord) + _next_ord += 1 + return result + + einsum_str_output = "".join(get_output_name_at(i) for i in range(ndim - len(axes_in) + 1)) + + return einsum_str_input + "->" + einsum_str_output + + +def diagonal(einsum): + def diagonal(x, axes_in, axis_out): + einsum_str = _einsum_diag_string(x.ndim, axes_in, axis_out) + return einsum(einsum_str, x) + + return diagonal diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/decomposednamedtensor_from_classical.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/decomposednamedtensor_from_classical.py new file mode 100644 index 0000000000000000000000000000000000000000..91a8e1c1fa027ee80dfccbca390fbcdb63bc439c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/decomposednamedtensor_from_classical.py @@ -0,0 +1,452 @@ +import einx._src.namedtensor.stage3 as stage3 +from einx._src.namedtensor import NamedTensor +from ._util import _squeeze_transpose_broadcast +from ._util import _ensure_output +from ._util import _stack +from ._util import _unsqueeze +from ._util import _unravel +import functools +import numpy as np +from einx._src.util.functools import use_name_of +import einx._src.tracer as tracer +import einx._src.adapter as adapter +from einx._src.frontend.errors import OperationNotSupportedError + + +def _expr_to_axis(expr): + idxs = [] + for idx, axis in enumerate(expr): + if stage3.is_in_brackets(axis): + idxs.append(idx) + return tuple(idxs) + + +def _join_exprs(exprs): + axisname_to_value = {axis.name: axis.value for expr in exprs for axis in expr.nodes() if isinstance(axis, stage3.Axis)} + + axes = [[expr for expr in expr.nodes() if isinstance(expr, stage3.Axis) and expr.value != 1] for expr in exprs] + + def take_one(): + def get_count(name): + return sum((1 if name == axis.name else 0) for axes2 in axes for axis in axes2) + + first_axisnames = list({axes2[0].name for axes2 in axes if len(axes2) > 0}) + counts = [get_count(name) for name in first_axisnames] + idx = np.argmax(counts) + axisname = first_axisnames[idx] + return axisname + + def remove(axes, name): + return [axis for axis in axes if axis.name != name] + + joined_axisnames = [] + while any(len(axes2) > 0 for axes2 in axes): + axisname = take_one() + joined_axisnames.append(axisname) + axes = [remove(axes2, axisname) for axes2 in axes] + + return stage3.List.create([stage3.Axis(name, axisname_to_value[name]) for name in joined_axisnames]) + + +def _ravel(classical, expr_tensor, coords, expr_coords, expr_out, verbose=False): + # (1) Example shapes here: + # expr_tensor: a [b c] d + # coords: a [1] d e, [1] d f + # expr_out: a d e f + + if verbose: + print("Step 0") + print(f" tensor: {expr_tensor}") + print(f" coords: {[str(c) for c in expr_coords]}") + print(f" out: {expr_out}") + + # Convert list of ND coords to list of 1D coords without brackets + coords2 = [] + expr_coords2 = [] + for coord, expr_coord in zip(coords, expr_coords, strict=False): + axis = _expr_to_axis(expr_coord) + expr_coord_without_brackets = stage3.remove(expr_coord, stage3.Brackets, keep_children=False) + if len(axis) == 0: + # No axis is marked -> contains coordinate for 1 axis + coords2.append(coord) + expr_coords2.append(expr_coord) + elif len(axis) == 1: + # One axis is marked -> contains coordinates for ndim axes + shape = tuple(a.value for a in expr_coord) + ndim = shape[axis[0]] + if ndim == 1: + coord = classical.reshape(coord, shape[: axis[0]] + shape[axis[0] + 1 :]) + coords2.append(coord) + expr_coords2.append(expr_coord_without_brackets) + else: + assert ndim > 1 + for i in range(ndim): + coord_i = classical.get_at(coord, i, axis=axis[0]) + coords2.append(coord_i) + expr_coords2.append(expr_coord_without_brackets) + else: + raise AssertionError() + coords = coords2 + expr_coords = expr_coords2 + + if verbose: + print("Step 1") + print(f" tensor: {expr_tensor}") + print(f" coords: {[str(c) for c in expr_coords]}") + print(f" out: {expr_out}") + + # (2) Example shapes here: + # expr_tensor: a [b c] d + # coords: a d e, d f + # expr_out: a d e f + + # Get coord dtype + if hasattr(classical, "dtype"): + tensor_types = (tracer.signature.classical.Tensor, classical.tensor) if isinstance(classical.tensor, type) else (tracer.signature.classical.Tensor,) + for coord in coords: + if isinstance(coord, tensor_types): + coord_dtype = classical.dtype(coord) + break + else: + coord_dtype = classical.dtype(coords[0]) + else: + coord_dtype = "int32" + + # Add aranged coords for all vectorized axes + coords2 = [] + expr_coords2 = [] + for axis in expr_tensor: + assert isinstance(axis, stage3.Axis) + if stage3.is_in_brackets(axis): + # Axis is in brackets -> use coordinate argument + coords2.append(coords[0]) + expr_coords2.append(expr_coords[0]) + coords = coords[1:] + expr_coords = expr_coords[1:] + else: + # Axis is not in brackets -> use np.arange + coord = classical.arange(axis.value, dtype=coord_dtype) + expr_coord = axis.__deepcopy__() + coords2.append(coord) + expr_coords2.append(expr_coord) + coords = coords2 + expr_coords = expr_coords2 + + if verbose: + print("Step 2") + print(f" tensor: {expr_tensor}") + print(f" coords: {[str(c) for c in expr_coords]}") + print(f" out: {expr_out}") + + # (3) Example shapes here: + # expr_tensor: a [b c] d + # coords: a, a d e, d f, d + # expr_out: a d e f + + # Compute indices into flattened tensor by ravelling coordinates (-> row-major formula) + multiplier = 1 + coords2 = [] + for coord, axis in reversed(list(zip(coords, expr_tensor, strict=False))): + if multiplier != 1: + coord = classical.multiply(coord, multiplier) + coords2.insert(0, coord) + multiplier *= axis.value + coords = coords2 + + elementwise_add = elementwise(classical.add, classical) + coords = elementwise_add(*[NamedTensor(coord, expr) for coord, expr in zip(coords, expr_coords, strict=False)], out=expr_out).value + + # (4) Example shapes here: + # expr_tensor: a [b c] d + # coords: a d e f + # expr_out: a d e f + + return coords + + +def reduce(op, expected_type=None): + op_in = op + + @use_name_of(op) + def inner(tensor, out, **kwargs): + expr_in = tensor.expr + tensor = tensor.value + expr_out = stage3.remove(expr_in, stage3.Brackets, keep_children=False) + + op = _ensure_output(op_in, (expr_out.shape,), expected_type=expected_type) + tensor = op(tensor, axis=_expr_to_axis(expr_in), **kwargs) + + return NamedTensor(tensor, expr_out) + + return inner + + +def preserve_shape(op): + @use_name_of(op) + def inner(tensor, out, **kwargs): + expr = tensor.expr + tensor = tensor.value + + tensor = op(tensor, axis=_expr_to_axis(expr), **kwargs) + + return NamedTensor(tensor, expr) + + return inner + + +def argfind(op, classical): + @use_name_of(op) + def inner(tensor, out, **kwargs): + expr = tensor.expr + tensor = tensor.value + + # Identify marked axes + marked_axes = [idx for idx, axis in enumerate(expr) if stage3.is_in_brackets(axis)] + ravel_shape = tuple(axis.value for axis in expr if stage3.is_in_brackets(axis)) + marked_axes_length = int(np.prod([axis.value for axis in expr if stage3.is_in_brackets(axis)])) + + # Rearrange marked axes to the back if they are not contiguous + is_contiguous = len(marked_axes) < 2 or all(marked_axes[i] + 1 == marked_axes[i + 1] for i in range(len(marked_axes) - 1)) + if not is_contiguous: + # Transpose all marked axes to the back + perm = [] + new_expr = [] + for idx, axis in enumerate(expr): + if not stage3.is_in_brackets(axis): + perm.append(idx) + new_expr.append(axis) + for idx, axis in enumerate(expr): + if stage3.is_in_brackets(axis): + perm.append(idx) + new_expr.append(stage3.Brackets(axis)) + marked_axes = list(range(len(expr) - len(marked_axes), len(expr))) + expr = stage3.List.create(new_expr) + tensor = classical.transpose(tensor, perm) + unmarked_expr = stage3.remove(expr, stage3.Brackets, keep_children=False) + + # Flatten all marked axes to a single axis + new_shape = [] + for axis in range(tensor.ndim): + if axis in marked_axes: + if axis == marked_axes[0]: + new_shape.append(marked_axes_length) + else: + new_shape.append(tensor.shape[axis]) + tensor = classical.reshape(tensor, new_shape) + axis = marked_axes[0] + + # Apply argfind operation to remove marked axis + tensor = op(tensor, axis=axis, **kwargs) + assert tensor.shape == unmarked_expr.shape + + # Rearrange to output expression + out_expr_without_brackets = stage3.remove(out, stage3.Brackets, keep_children=False) + unmarked_expr, tensor = _squeeze_transpose_broadcast(classical, unmarked_expr, tensor, out_expr_without_brackets) + + # Unravel and stack along marked axis in output + marked_out_axes_pos = [idx for idx, axis in enumerate(out) if isinstance(axis, stage3.Axis) and stage3.is_in_brackets(axis)] + if len(marked_out_axes_pos) == 0: + axis = None + elif len(marked_out_axes_pos) == 1: + axis = marked_out_axes_pos[0] + else: + raise ValueError("At most one marked axis is allowed in the output expression.") + tensor = _unravel(classical, tensor, ravel_shape, axis=axis) + + return NamedTensor(tensor, out) + + return inner + + +def elementwise(op, classical, expected_type=None): + op_in = op + + @use_name_of(op) + def inner(*tensors, out, **kwargs): + exprs_in = [t.expr for t in tensors] + tensors = [t.value for t in tensors] + + # (1) Example shapes here: + # tensors: a, b + # out: a b c + + # Transpose tensors and insert unitary dimensions to match output expression + tensors2 = [] + exprs_in2 = [] + for tensor, expr_in in zip(tensors, exprs_in, strict=False): + expr_in, tensor = _squeeze_transpose_broadcast(classical, expr_in, tensor, out, broadcast_to_unitary=True) + tensors2.append(tensor) + exprs_in2.append(expr_in) + tensors = tensors2 + exprs_in = exprs_in2 + + # (2) Example shapes here: + # tensors: a 1 1, 1 b 1 + # out: a b c + + # Apply operation + in_axes = [[axis for axis in expr.nodes() if isinstance(axis, stage3.Axis)] for expr in exprs_in] + assert len({len(a) for a in in_axes}) == 1 + out_axes = [] + for i in range(len(in_axes[0])): + in_axes_i = [axes[i] for axes in in_axes] + idx = np.argmax([axis.value for axis in in_axes_i]) + out_axis_i = in_axes_i[idx].__deepcopy__() + out_axes.append(out_axis_i) + expr_out = stage3.List.create(out_axes) + op = _ensure_output(op_in, (expr_out.shape,), expected_type=expected_type) + tensor = op(*tensors, **kwargs) + + # (3) Example shapes here: + # tensors: a b 1 + # out: a b c + + return NamedTensor(tensor, expr_out) + + return inner + + +def dot(classical): + def dot(*tensors, out): + if len(tensors) != 2: + raise OperationNotSupportedError("dot operation with numpylike backend does not support more than two argument tensors.") + tensor1, tensor2 = tensors + + # Follows the algorithm described here: https://github.com/jcmgray/einsum_bmm/blob/main/einsum_bmm.py#L139 + + id = adapter.namedtensor_from_decomposednamedtensor.id(None, classical) + expr1 = tensor1.expr + expr2 = tensor2.expr + tensor1 = tensor1.value + tensor2 = tensor2.value + + # Get axes: left, right -> out + left_axis_names = [axis.name for axis in expr1.nodes() if isinstance(axis, stage3.Axis)] + right_axis_names = [axis.name for axis in expr2.nodes() if isinstance(axis, stage3.Axis)] + out_axis_names = [axis.name for axis in out.nodes() if isinstance(axis, stage3.Axis)] + + # Classify axes into: batch, contracted, left-keep, right-keep + batch_axis_names = [] + contract_axis_names = [] + left_keep_axis_names = [] + right_keep_axis_names = [] + for axis in left_axis_names: + if axis in right_axis_names: + if axis in out_axis_names: + batch_axis_names.append(axis) + else: + contract_axis_names.append(axis) + else: + assert axis in out_axis_names + left_keep_axis_names.append(axis) + for axis in right_axis_names: + if axis not in left_axis_names: + assert axis in out_axis_names + right_keep_axis_names.append(axis) + + # Build new expressions for left, right, out + lengths = {axis.name: axis.value for expr in [expr1, expr2, out] for axis in expr.nodes() if isinstance(axis, stage3.Axis)} + left_matmul_expr = stage3.List.create([ + stage3.FlattenedAxis.create(stage3.List.create([stage3.Axis(name, lengths[name]) for name in batch_axis_names])), + stage3.FlattenedAxis.create(stage3.List.create([stage3.Axis(name, lengths[name]) for name in left_keep_axis_names])), + stage3.FlattenedAxis.create(stage3.List.create([stage3.Axis(name, lengths[name]) for name in contract_axis_names])), + ]) + right_matmul_expr = stage3.List.create([ + stage3.FlattenedAxis.create(stage3.List.create([stage3.Axis(name, lengths[name]) for name in batch_axis_names])), + stage3.FlattenedAxis.create(stage3.List.create([stage3.Axis(name, lengths[name]) for name in contract_axis_names])), + stage3.FlattenedAxis.create(stage3.List.create([stage3.Axis(name, lengths[name]) for name in right_keep_axis_names])), + ]) + out_matmul_expr = stage3.List.create([ + stage3.FlattenedAxis.create(stage3.List.create([stage3.Axis(name, lengths[name]) for name in batch_axis_names])), + stage3.FlattenedAxis.create(stage3.List.create([stage3.Axis(name, lengths[name]) for name in left_keep_axis_names])), + stage3.FlattenedAxis.create(stage3.List.create([stage3.Axis(name, lengths[name]) for name in right_keep_axis_names])), + ]) + + # Rearrange tensors to matmul expressions + left = id(NamedTensor(tensor1, expr1), out=left_matmul_expr).value + right = id(NamedTensor(tensor2, expr2), out=right_matmul_expr).value + assert left.ndim == 3 and right.ndim == 3 + + # Perform batched matmul + tensor = classical.matmul(left, right) + expr = out_matmul_expr + + # Rearrange to output expression + tensor = id(NamedTensor(tensor, expr), out=out).value + + return NamedTensor(tensor, out) + + return dot + + +def get_at_ravelled(classical): + def get_at(tensor, *coordinates, out): + expr_tensor = tensor.expr + tensor = tensor.value + expr_coords = [c.expr for c in coordinates] + coords = [c.value for c in coordinates] + + # (1) Example shapes here: + # tensor: a [b c] d + # coords (ND): a [1] d e, [1] d f + # out: a d e f + + coords = _ravel(classical, expr_tensor, coords, expr_coords, out) + + # (2) Example shapes here: + # tensor: a [b c] d + # coords (1D-ravelled): a d e f + # out: a d e f + + # Flatten tensor and retrieve values + tensor = classical.reshape(tensor, (expr_tensor.value,)) + tensor = classical.get_at(tensor, coords, axis=0) + + # (3) Example shapes here: + # tensor: a d e f + # out: a d e f + + return NamedTensor(tensor, out) + + return get_at + + +def update_at_ravelled(op, classical): + @use_name_of(op) + def inner(*tensors, out): + expr_tensor = tensors[0].expr + tensor = tensors[0].value + expr_updates = tensors[-1].expr + updates = tensors[-1].value + expr_coords = [c.expr for c in tensors[1:-1]] + coords = [c.value for c in tensors[1:-1]] + + expr_intermediate = _join_exprs([ # TODO: what order of axes should be chosen here? + stage3.remove(expr, lambda expr: isinstance(expr, stage3.Brackets), keep_children=False) for expr in expr_coords + [expr_updates, expr_tensor] + ]) + + # (1) Example shapes here: + # tensor: a [b c] d + # coords (ND): a [1] d e, [1] d f + # updates: a d f + # expr_intermediate: a d e f + + coords = _ravel(classical, expr_tensor, coords, expr_coords, expr_intermediate) + expr_updates, updates = _squeeze_transpose_broadcast(classical, expr_updates, updates, expr_intermediate, broadcast_to_unitary=True) + + # (2) Example shapes here: + # tensor: a [b c] d + # coords (1D-ravelled): a d e f + # updates: a d 1 f + + # Update values in flattened tensor + tensor = classical.reshape(tensor, (expr_tensor.value,)) + tensor = op(tensor, coords, updates) + tensor = classical.reshape(tensor, expr_tensor.shape) + + # (3) Example shapes here: + # tensor: a [b c] d + + return NamedTensor(tensor, expr_tensor) + + return inner diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/decomposednamedtensor_from_einsum.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/decomposednamedtensor_from_einsum.py new file mode 100644 index 0000000000000000000000000000000000000000..5f606d90739807e71285cfe19fdb1908079b69b3 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/decomposednamedtensor_from_einsum.py @@ -0,0 +1,86 @@ +import einx._src.namedtensor.stage3 as stage3 +from einx._src.namedtensor import NamedTensor + + +def _expr_to_einsumstr(exprs_in, expr_out, allow_repeat_axes=False): + einsum_variables = {} + + next_ord = ord("a") + + def get_einsum_variable(key, make_new): + if not make_new and key in einsum_variables: + return einsum_variables[key] + else: + nonlocal next_ord + if next_ord > ord("z"): + raise ValueError(f"The function only supports up to {ord('z') - ord('a') + 1} unique input axes") + v = chr(next_ord) + next_ord += 1 + einsum_variables[key] = v + return v + + def to_einsum(expr, make_new): + axes = [a for a in expr if isinstance(a, stage3.Axis)] + einsum_str = "" + for a in axes: + einsum_str += get_einsum_variable(a.name, make_new=make_new) + return einsum_str + + einsum_str_in = ",".join(to_einsum(expr, make_new=allow_repeat_axes) for expr in exprs_in) + einsum_str_out = to_einsum(expr_out, make_new=False) + einsum_str = einsum_str_in + "->" + einsum_str_out + return einsum_str + + +def _op(einsum, name, allow_repeat_axes=False): + def op(*tensors, out): + exprs_in = [t.expr for t in tensors] + tensors = [t.value for t in tensors] + + tensor = einsum(_expr_to_einsumstr(exprs_in, out, allow_repeat_axes=allow_repeat_axes), *tensors) + + return NamedTensor(tensor, out) + + op.__name__ = name + return op + + +def dot(einsum): + return _op(einsum, "dot") + + +def sum(einsum): + return _op(einsum, "sum", allow_repeat_axes=True) + + +def multiply(einsum): + return _op(einsum, "multiply") + + +def id(einsum): + def id(*tensors, out): + if len(tensors) == 1: + assert isinstance(out, stage3.Expression) + out = [out] + assert len(tensors) == len(out) + + def _single_id(tensor, out): + expr = tensor.expr + tensor = tensor.value + + # Ignore broadcasting axes -> are handled by namedtensor_from_decomposednamedtensor + input_axis_names = {axis.name for axis in expr.nodes() if isinstance(axis, stage3.Axis)} + out = stage3.List.create([axis for axis in out.nodes() if isinstance(axis, stage3.Axis) if axis.name in input_axis_names]) + + einsum_str = _expr_to_einsumstr([expr], out) + tokens = einsum_str.split("->") + if tokens[0] != tokens[1]: + tensor = einsum(_expr_to_einsumstr([expr], out), tensor) + + return NamedTensor(tensor, out) + + tensors = [_single_id(tensor, out) for tensor, out in zip(tensors, out, strict=False)] + + return tensors if len(tensors) > 1 else tensors[0] + + return id diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/decomposednamedtensor_from_vmap.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/decomposednamedtensor_from_vmap.py new file mode 100644 index 0000000000000000000000000000000000000000..88b5443a0c61853a5b80c2ff4d47775c6a49e74c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/decomposednamedtensor_from_vmap.py @@ -0,0 +1,76 @@ +import einx._src.namedtensor.stage3 as stage3 +from functools import partial +from einx._src.namedtensor import NamedTensor +import einx._src.tracer as tracer +import functools +from ._util import _ensure_output +from einx._src.util.functools import use_name_of + + +def op(op, vmap, expected_type=None, allow_squeeze_unsqueeze=False, classical=None): + op_in = op + + @use_name_of(op) + def inner(*tensors, out, **kwargs): + if isinstance(out, list | tuple): + exprs_out = out + else: + exprs_out = [out] + + exprs_in = [t.expr for t in tensors] + tensors = [t.value for t in tensors] + + # TODO: In what order should vmap be called over multiple axes? + vectorized_axisnames = [] + for expr in list(exprs_in) + list(exprs_out): + for axis in expr.nodes(): + if isinstance(axis, stage3.Axis) and not stage3.is_in_brackets(axis) and axis.name not in vectorized_axisnames: + vectorized_axisnames.append(axis.name) + + def get_pos_in_expr(axisname, expr): + for i, node in enumerate(expr): + if isinstance(node, stage3.Axis) and node.name == axisname: + return i + return None + + def get_pos_in_exprs(axisname, exprs): + axis = tuple(get_pos_in_expr(axisname, expr) for expr in exprs) + if len(axis) == 1: + return axis[0] + else: + return axis + + def remove_axis(expr, axisname): + return stage3.remove(expr, pred=lambda x: isinstance(x, stage3.Axis) and x.name == axisname) + + # Determine arguments to the vmap calls + vmaps = [] + exprs_in_left = list(exprs_in) + exprs_out_left = list(exprs_out) + expected_out_shapes_inner = [expr.shape for expr in exprs_out_left] + for axis in vectorized_axisnames: + in_axes = get_pos_in_exprs(axis, exprs_in_left) + out_axes = get_pos_in_exprs(axis, exprs_out_left) + + exprs_in_left = [remove_axis(expr, axis) for expr in exprs_in_left] + exprs_out_left = [remove_axis(expr, axis) for expr in exprs_out_left] + + expected_out_shapes_inner = [expr.shape for expr in exprs_out_left] + + vmaps.append((in_axes, out_axes)) + + # Create vmapped function + op = op_in + op = partial(op, **kwargs) + op = _ensure_output(op, expected_out_shapes_inner, expected_type=expected_type, allow_squeeze_unsqueeze=allow_squeeze_unsqueeze, classical=classical) + for in_axes, out_axes in reversed(vmaps): + op = vmap(op, in_axes=in_axes, out_axes=out_axes) + + tensors = op(*tensors) + + if len(exprs_out) == 1: + return NamedTensor(tensors, exprs_out[0]) + else: + return tuple(NamedTensor(tensor, expr) for tensor, expr in zip(tensors, exprs_out, strict=False)) + + return inner diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/einx_from_namedtensor.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/einx_from_namedtensor.py new file mode 100644 index 0000000000000000000000000000000000000000..bb967b3bf5885b10157114cfd82bc88d1fa1ccdd --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/einx_from_namedtensor.py @@ -0,0 +1,829 @@ +import einx._src.namedtensor.stage1 as stage1 +import einx._src.namedtensor.stage2 as stage2 +import einx._src.namedtensor.stage3 as stage3 +from einx._src.namedtensor import solve +from einx._src.namedtensor import NamedTensor +from einx._src.frontend.types import Tensor +import numpy as np +import functools +import types +import einx._src.tracer as tracer +import einx._src.adapter as adapter +import uuid +from functools import partial +from einx._src.frontend.errors import SemanticError +from collections import defaultdict +from einx._src.util.functools import use_name_of + + +def _tensor_to_string(tensor): + if tensor.shape is None: + return "Tensor factory" + else: + return f"Tensor with shape {tensor.shape}" + + +def _kwarg_to_string(v): + s = str(v) + if len(s) < 20: + return s + else: + return "..." + + +class Invocation: + def __init__(self, expression, name, tensors, kwargs): + self.expression = expression + self.name = name + self.tensors = tensors + self.kwargs = kwargs + + from einx._src.namedtensor import ExpressionIndicator + + self.indicator = ExpressionIndicator(expression) + + def to_call_signature_string(self): + message = "The operation was called with the following arguments:\n" + for i, tensor in enumerate(self.tensors): + message += f" - Positional argument #{i + 1}: {_tensor_to_string(tensor)}\n" + for k, v in self.kwargs.items(): + message += f" - Keyword argument '{k}': {_kwarg_to_string(v)}\n" + return message + + +def _to_el_expr(expr): + if isinstance(expr, list): + newlist = [_to_el_expr(e) for e in expr] + newlist = [expr for expr in newlist if expr.ndim != 0] + return newlist + elif isinstance(expr, stage1.List): + return stage1.List.create(_to_el_expr(expr.children), expr.begin_pos, expr.end_pos) + elif isinstance(expr, stage1.Axis): + return stage1.List([]) + elif isinstance(expr, stage1.FlattenedAxis): + inner = _to_el_expr(expr.inner) + if inner.ndim == 0: + return stage1.List([]) + else: + return stage1.FlattenedAxis.create(inner, expr.begin_pos, expr.end_pos) + elif isinstance(expr, stage1.ConcatenatedAxis): + # ConcatenatedAxis cannot be used with brackets + assert not any(stage1.is_in_brackets(c) for c in expr.nodes()) + return stage1.List([]) + elif isinstance(expr, stage1.Brackets): + return expr.inner.__deepcopy__() + elif isinstance(expr, stage1.Ellipsis): + return stage1.Ellipsis.create(_to_el_expr(expr.inner), expr.begin_pos, expr.end_pos, expr.ellipsis_id) + elif isinstance(expr, stage1.Op): + return stage1.Op([_to_el_expr(c) for c in expr.children], expr.begin_pos, expr.end_pos) + elif isinstance(expr, stage1.Args): + return stage1.Args([_to_el_expr(c) for c in expr.children], expr.begin_pos, expr.end_pos) + else: + raise TypeError(f"Invalid expression type {type(expr)}") + + +def _parse_op(description, el_op, invocation, allow_concat=False, implicit_output=None, mark_reduced_axes=False, allow_duplicate_el_axes=True, keepdims=False): + if not isinstance(description, str): + raise ValueError("The operation description must be a string.") + if keepdims is None: + keepdims = False + op = stage1.parse_op(description) + + if not allow_concat: + # Disallow concatenation + if any(isinstance(expr, stage1.ConcatenatedAxis) for expr in op.nodes()): + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_concat(op), + message="The concatenation operator (+) is not allowed in this function.\n%EXPR%", + ) + + exprs_in = op.children[0].children + + # Get signature that is expected by the elementary operation + el_subop = _to_el_expr(op) + if el_op is None: + # No signature is explicitly provided -> extract the signature from the expression itself + if len(el_subop.children) != 2: + raise SemanticError(invocation=invocation, message="The operation expects an output expression, but no '->' was found.\n%EXPR%") + el_op = el_subop + elif isinstance(el_op, str): + el_op = stage1.parse_op(el_op) + elif callable(el_op): + el_op = el_op(el_subop) + el_op = stage1.parse_op(el_op) + else: + raise ValueError(f"Invalid type for el_op: {type(el_op)}.") + assert len(el_op.children) == 2 + + # Check number of input and output expressions + if len(el_op.children[0].children) != len(el_subop.children[0].children): + raise SemanticError( + invocation=invocation, + message=f"The operation expects {len(el_op.children[0].children)} input expression(s), but found {len(el_subop.children[0].children)}.\n%EXPR%", + ) + if len(el_subop.children) > 1 and len(el_op.children[1].children) != len(el_subop.children[1].children): + raise SemanticError( + invocation=invocation, + message=f"The operation expects {len(el_op.children[1].children)} output expression(s), but found {len(el_subop.children[1].children)}.\n%EXPR%", + ) + + # Determin output expression if it is not given + if len(op.children) == 1: + if implicit_output == "bijective": + if len(el_op.children[0].children) == 1 and len(el_op.children[1].children) == 1 and el_op.children[0] == el_op.children[1]: + # single input == single output + # -> Use input expression as output expression + exprs_out = [expr_in.__deepcopy__() for expr_in in exprs_in] + elif len(el_op.children[0].children) == 1 and len(el_op.children[1].children) == 1 and el_op.children[1].children[0].ndim == 0: + # Single input and single scalar output + # -> Remove brackets from input expression for output expression + if keepdims: + + def _replace(expr): + if isinstance(expr, stage1.Brackets): + return stage1.FlattenedAxis.create(stage1.List.create([])) + + exprs_out = [stage1.map(expr_in, _replace, include_children=True) for expr_in in exprs_in] + else: + exprs_out = [stage1.remove(expr_in, stage1.Brackets, keep_children=False) for expr_in in exprs_in] + elif all(c.ndim == 0 for c in list(el_op.children[0].children) + list(el_op.children[1].children)): + # Scalar inputs and outputs + # -> Find superset expression + if len(exprs_in) == 1: + # Only one input -> use it as output + exprs_out = [exprs_in[0].__deepcopy__()] + else: + # Use one of the input expression if it contains the axis names of + # all others and if this choice is unique + in_axis_names = [{expr.name for expr in root.nodes() if isinstance(expr, stage1.Axis) and expr.value != 1} for root in exprs_in] + + valid_parents = set() + for i, parent in enumerate(in_axis_names): + for j, child in enumerate(in_axis_names): + if i != j and not child.issubset(parent): + break + else: + # Found valid parent + valid_parents.add(exprs_in[i]) + + if len(valid_parents) != 1: + raise SemanticError( + invocation=invocation, + message="The output expression is missing in this operation. einx allows implicitly determining the output expression" + " in this operation according to the rule: If one of the input expressions contains the axis names of all other input" + " expressions (excluding 1s) and if this choice is unique, then this expression is used as output expression. However, no unique" + " input expression was found.\n%EXPR%", + ) + exprs_out = [valid_parents.pop().__deepcopy__()] + elif len(el_op.children[0].children) == 1 and len(el_op.children[1].children) == 1: + # Single input and single output + # -> Replace single input bracket with single output bracket + def _to_output(expr): + bracket_num = len([e for e in expr.nodes() if isinstance(e, stage1.Brackets)]) + assert bracket_num > 0 + if bracket_num == 1: + + def _replace(expr): + if isinstance(expr, stage1.Brackets): + return stage1.Brackets.create(stage1.Axis.create("output.axis")) + + return stage1.map(expr, _replace, include_children=False) + else: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_brackets(expr), + message=( + "The output expression is missing in this operation. The output expression can only be determined implicitly, " + "if the input expression contains exactly one usage of brackets ([]).\n%EXPR%" + ), + ) + + exprs_out = [_to_output(expr_in) for expr_in in exprs_in] + else: + raise SemanticError(invocation=invocation, message="The operation expects an output expression, but no '->' was found.\n%EXPR%") + elif isinstance(implicit_output, int): + exprs_out = [exprs_in[implicit_output].__deepcopy__()] + elif isinstance(implicit_output, tuple | list) and all(isinstance(i, int) for i in implicit_output): + exprs_out = [exprs_in[i].__deepcopy__() for i in implicit_output] + elif implicit_output is None: + raise SemanticError(invocation=invocation, message="The operation expects an output expression, but no '->' was found.\n%EXPR%") + else: + raise ValueError(f"Invalid value for implicit_output: {implicit_output}") + else: + exprs_out = op.children[1].children + op = stage1.Op([stage1.Args(exprs_in), stage1.Args(exprs_out)]) + el_subop = _to_el_expr(op) + assert len(el_op.children[0].children) == len(el_subop.children[0].children) + assert len(el_op.children[1].children) == len(el_subop.children[1].children) + + # Check bracket usage + def _to_ordinal_str(i): + if i == 0: + return "1st" + elif i == 1: + return "2nd" + elif i == 2: + return "3rd" + else: + return f"{i + 1}th" + + def check(i, el_arg, el_subarg, arg, inoutput): + if el_arg.ndim == 0 and el_subarg.ndim != 0: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_brackets(arg), + message=f"Brackets ([]) are not allowed in the {_to_ordinal_str(i)} {inoutput} expression of this operation.\n%EXPR%", + ) + elif el_arg.ndim != 0 and el_subarg.ndim == 0: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_exprs(arg), + message=f"The {_to_ordinal_str(i)} {inoutput} expression of this operation requires brackets, but no brackets were found.\n%EXPR%", + ) + + for i, (el_arg, el_subarg, arg) in enumerate(zip(el_op.children[0].children, el_subop.children[0].children, op.children[0].children, strict=False)): + check(i, el_arg, el_subarg, arg, "input") + for i, (el_arg, el_subarg, arg) in enumerate(zip(el_op.children[1].children, el_subop.children[1].children, op.children[1].children, strict=False)): + check(i, el_arg, el_subarg, arg, "output") + + marking_reduced_axes = mark_reduced_axes and not any(isinstance(expr, stage1.Brackets) for expr_in in exprs_in for expr in expr_in.nodes()) + if marking_reduced_axes: + # Check that no axis name is used twice per input + for expr_in in exprs_in: + counts = defaultdict(lambda: 0) + for axis in expr_in.nodes(): + if isinstance(axis, stage1.Axis): + counts[axis.name] += 1 + duplicates = [name for name, count in counts.items() if count > 1] + if len(duplicates) > 0: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames([expr_in], duplicates), + message=( + "If no axes are marked with brackets in this operation, brackets are placed automatically around all axes that do not appear " + "in the output expression. Since this mode is used here, no axis name may appear more than once in the same input tensor (to avoid " + f"confusion with diagonal extraction). However, the following axis names are used more than once: {', '.join(duplicates)}.\n%EXPR%" + ), + ) + + assert len(exprs_out) == 1 + expr_out = exprs_out[0] + + # If no brackets appear in exprs_in, mark all axes that don't appear in expr_out. + axes_names_out = {axis.name for axis in expr_out.nodes() if isinstance(axis, stage1.Axis)} + + def _mark(expr): + if isinstance(expr, stage1.Axis) and expr.name not in axes_names_out: + return True + else: + return False + + exprs_in = [stage1.map(expr_in, lambda expr: stage1.Brackets(expr) if _mark(expr) else None, include_children=False) for expr_in in exprs_in] + + # Check that no two vectorized axes in any (unconcatenated) output have the same name + for expr_out in exprs_out: + for expr_out in stage1.split_concatenated_axes(expr_out): + axis_names = [expr.name for expr in expr_out.nodes() if isinstance(expr, stage1.Axis) and not stage1.is_in_brackets(expr)] + if len(axis_names) != len(set(axis_names)): + duplicates = {name for name in axis_names if axis_names.count(name) > 1} + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames([expr_out], duplicates), + message="The output expression must not contain multiple vectorized axes with the same name (after splitting concatenated axes).\n%EXPR%", + ) + + if not allow_duplicate_el_axes: + # Check that no two marked axes in any tensor have the same name + for expr in exprs_in + exprs_out: + axis_names = [expr.name for expr in expr.nodes() if isinstance(expr, stage1.Axis) and stage1.is_in_brackets(expr)] + if len(axis_names) != len(set(axis_names)): + duplicates = {name for name in axis_names if axis_names.count(name) > 1} + + message = "The expression must not contain multiple axes with the same name in brackets ([]).\n%EXPR%" + raise SemanticError(invocation=invocation, pos=invocation.indicator.get_pos_for_axisnames([expr], duplicates), message=message) + + return exprs_in, exprs_out + + +def _semantic_checks_dot(exprs_in, exprs_out, invocation): + expr_out = exprs_out[0] + + # Ensure at least two inputs + if len(exprs_in) < 2: + raise SemanticError( + invocation=invocation, message=f"The dot operation requires at least 2 input expressions, but only {len(exprs_in)} is given.\n%EXPR%" + ) + + # Ensure that all marked axes appear in exactly two input expressions + + def is_marked_axis(expr): + return isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr) + + marked_axis_names = {expr.name for expr_in in exprs_in for expr in expr_in.nodes() if is_marked_axis(expr)} + invalid_axis_names = [] + for axis_name in marked_axis_names: + count = 0 + for expr_in in exprs_in: + if axis_name in {axis.name for axis in expr_in.nodes() if isinstance(axis, stage3.Axis)}: + count += 1 + if count != 2: + invalid_axis_names.append(axis_name) + if len(invalid_axis_names) > 0: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(exprs_in + [expr_out], invalid_axis_names), + message="All contracted axes must appear in exactly two input expressions.\n%EXPR%", + ) + + +def _semantic_checks_get_at(exprs_in, exprs_out, invocation): + expr_out = exprs_out[0] + if len(exprs_in) < 2: + raise SemanticError(invocation=invocation, message=f"The operation expects at least 2 input expressions, but found {len(exprs_in)}.\n%EXPR%") + all_exprs = list(exprs_in) + [expr_out] + tensor_expr = exprs_in[0] + coords_exprs = exprs_in[1:] + + # Ensure that at most one axis is marked in each coordinate expression + for coord_expr in coords_exprs: + marked_axisnames = [expr.name for expr in coord_expr.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)] + if len(marked_axisnames) > 1: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(all_exprs, marked_axisnames), + message="Each coordinate expression must contain at most one axis in brackets.\n%EXPR%", + ) + + # Ensure that summed number of coordinates is equal to the number of marked axes in first input expression + n = 0 + for coord_expr in coords_exprs: + marked_axis = [expr for expr in coord_expr.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)] + assert len(marked_axis) <= 1 + if len(marked_axis) == 1: + n += marked_axis[0].value + else: + n += 1 + marked_axes = [expr for expr in tensor_expr.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)] + if len(marked_axes) != n: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(all_exprs, [expr.name for expr in marked_axes]), + message="The number of coordinates must match the number of axes in brackets in the first input expression.\n%EXPR%", + ) + + +def _semantic_checks_sort(exprs_in, exprs_out, invocation): + assert len(exprs_in) == 1 and len(exprs_out) == 1 + for expr in exprs_in + exprs_out: + marked_axisnames = [expr.name for expr in expr.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)] + if len(marked_axisnames) != 1: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(exprs_in + exprs_out, marked_axisnames), + message="The expression for this operation must contain exactly one axis in brackets.\n%EXPR%", + ) + + +def _semantic_checks_update_at(exprs_in, exprs_out, invocation): + expr_out = exprs_out[0] + if len(exprs_in) < 2: + raise SemanticError(invocation=invocation, message=f"The operation expects at least 3 input expressions, but found {len(exprs_in)}.\n%EXPR%") + + all_exprs = list(exprs_in) + [expr_out] + tensor_expr = exprs_in[0] + coords_exprs = exprs_in[1:-1] + update_expr = exprs_in[-1] + + # Ensure same set of axes is marked in first input and output expression + input_axisnames = {expr.name for expr in tensor_expr.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)} + output_axisnames = {expr.name for expr in expr_out.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)} + if input_axisnames != output_axisnames: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(all_exprs, input_axisnames.symmetric_difference(output_axisnames)), + message="The first input and output expressions must have the same set of axes in brackets.\n%EXPR%", + ) + + # Ensure that at most one axis is marked in each coordinate expression (aside from reduced axes that are also marked in updates) + for coord_expr in coords_exprs: + marked_axisnames = {expr.name for expr in coord_expr.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)} + if len(marked_axisnames) > 1: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(all_exprs, marked_axisnames), + message="Each coordinate expression must contain at most one coordinate axis in brackets.\n%EXPR%", + ) + + # Ensure marked axes in (1) target tensor, and (2) coordinate and update expressions are non-overlapping + target_axisnames = {expr.name for expr in tensor_expr.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)} + coordupdate_axisnames = { + expr.name for expr in coords_exprs + [update_expr] for expr in expr.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr) + } + intersection = target_axisnames.intersection(coordupdate_axisnames) + if len(intersection) > 0: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(all_exprs, intersection), + message="Axes may not appear in brackets both in the first input tensor and in a coordinate or update expression.\n%EXPR%", + ) + + # Ensure that summed number of coordinates is equal to the number of marked axes in first input expression + n = 0 + for coord_expr in coords_exprs: + marked_axis = {expr for expr in coord_expr.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)} + assert len(marked_axis) <= 1 + if len(marked_axis) == 1: + n += marked_axis.pop().value + else: + n += 1 + marked_axes = [expr for expr in tensor_expr.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)] + if len(marked_axes) != n: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(all_exprs, [expr.name for expr in marked_axes]), + message="The number of coordinates must match the number of axes in brackets in the first input expression.\n%EXPR%", + ) + + +def _semantic_checks_argfind(exprs_in, exprs_out, invocation): + if len(exprs_in) != 1: + raise SemanticError(invocation=invocation, message=f"The operation expects exactly one input expression, but found {len(exprs_in)}.\n%EXPR%") + if len(exprs_out) != 1: + raise SemanticError(invocation=invocation, message=f"The operation expects exactly one output expression, but found {len(exprs_in)}.\n%EXPR%") + expr_in = exprs_in[0] + expr_out = exprs_out[0] + all_exprs = [expr_in, expr_out] + + # Ensure that at most one axis is marked in output expression + marked_output_axes = [expr for expr in expr_out.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)] + if len(marked_output_axes) > 1: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(all_exprs, [a.name for a in marked_output_axes]), + message="The output expression must contain at most one axis in brackets.\n%EXPR%", + ) + marked_output_axis = marked_output_axes[0] if len(marked_output_axes) == 1 else None + + # Ensure that number of marked axes in input expression is equal to value of marked axis in output expression + marked_input_axes = [expr for expr in expr_in.nodes() if isinstance(expr, stage3.Axis) and stage3.is_in_brackets(expr)] + if marked_output_axis is None: + if len(marked_input_axes) != 1: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(all_exprs, [expr.name for expr in marked_input_axes]), + message=( + f"If no axis is marked in the output expression, exactly one axis must be marked in the input expression, " + f"but found {len(marked_input_axes)} marked axes.\n%EXPR%" + ), + ) + else: + if len(marked_input_axes) != marked_output_axis.value: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(all_exprs, [a.name for a in marked_input_axes] + [marked_output_axis.name]), + message=( + f"The number of axes in brackets in the input expression ({len(marked_input_axes)}) must match the value " + "of the marked axis in the output expression ({marked_output_axis.value}).\n%EXPR%" + ), + ) + + +def _cast_shape(tensor, expr): + if tensor.shape is None: + assert isinstance(tensor, tracer.signature.classical.ConvertibleTensor) + return tracer.cast(tensor, lambda origin: tracer.signature.classical.ConvertibleTensor(origin, tensor.concrete, expr.shape)) + else: + assert tuple(tensor.shape) == tuple(expr.shape) + return tensor + + +def op( + op, + el_op=None, + allow_concat=False, + implicit_output=None, + mark_reduced_axes=False, + add_keepdims_param=False, + check=None, + cse_in_brackets=True, + iskwarg=lambda name: False, + equations_stage3=None, + allow_nontrivial_unmarked_reduced_axes=False, + allow_duplicate_el_axes=True, + no_el_axis_permute=False, +): + if isinstance(iskwarg, list | tuple | set): + iskwarg = lambda name, iskwarg=iskwarg: name in iskwarg + + def inner(description, *tensors: Tensor, **kwargs): + invocation = Invocation( + description, name=op.__name__ if hasattr(op, "__name__") else "operation", tensors=tensors, kwargs=kwargs + ) # Used for error reporting + + if add_keepdims_param: + keepdims = {"keepdims": kwargs["keepdims"] if "keepdims" in kwargs else False} + kwargs.pop("keepdims", None) + else: + keepdims = {} + + exprs_in, exprs_out = _parse_op( + description, + el_op, + invocation=invocation, + allow_concat=allow_concat, + implicit_output=implicit_output, + mark_reduced_axes=mark_reduced_axes, + allow_duplicate_el_axes=allow_duplicate_el_axes, + **keepdims, + ) + + if len(exprs_in) != len(tensors): + + def choose_s(i): + return "s" if i != 1 else "" + + raise ValueError( + f"The operation is defined with {len(exprs_in)} input expression{choose_s(len(exprs_in))}, but {len(tensors)} " + f"input tensor{choose_s(len(tensors))} {'are' if len(tensors) != 1 else 'is'} given as argument{choose_s(len(tensors))}." + ) + + used_axis_names = {expr.name for expr in exprs_in + exprs_out for expr in expr.nodes() if isinstance(expr, stage1.Axis)} + if any(iskwarg(name) for name in used_axis_names): + invalid_kwargnames = [name for name in used_axis_names if iskwarg(name)] + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(exprs_in + exprs_out, invalid_kwargnames), + message=( + f"The following axis names may not be used in the expression, since they are keyword arguments of the elementary " + f"operation: {', '.join(invalid_kwargnames)}.\n%EXPR%" + ), + ) + + # Split kwargs from axis parameters + parameters = {} + new_kwargs = {} + for key, value in kwargs.items(): + if iskwarg(key): + new_kwargs[key] = value + else: + parameters[key] = value + kwargs = new_kwargs + del new_kwargs + + if no_el_axis_permute: + for expr_in, expr_out in zip(exprs_in, exprs_out, strict=False): + axisnames_in = [] + for axis in expr_in.nodes(): + if isinstance(axis, stage1.Axis) and stage1.is_in_brackets(axis): + axisnames_in.append(axis.name) + axisnames_out = [] + for axis in expr_out.nodes(): + if isinstance(axis, stage1.Axis) and stage1.is_in_brackets(axis): + axisnames_out.append(axis.name) + if axisnames_in != axisnames_out: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(exprs_in + exprs_out, set(axisnames_in).union(set(axisnames_out))), + message="All axes marked with brackets must appear in the same order in the inputs and outputs of this operation.\n%EXPR%", + ) + + exprs_in, exprs_out = solve( + exprs_in, + exprs_out, + [tensor.shape for tensor in tensors], + invocation, + parameters, + cse_in_brackets=cse_in_brackets, + equations_stage3=partial(equations_stage3, invocation=invocation) if equations_stage3 is not None else None, + ) + + if not allow_nontrivial_unmarked_reduced_axes: + axis_names_in = { + axis.name + for expr_in in exprs_in + for axis in expr_in.nodes() + if isinstance(axis, stage3.Axis) and not stage3.is_in_brackets(axis) and axis.value != 1 + } + axis_names_out = { + axis.name + for expr_out in exprs_out + for axis in expr_out.nodes() + if isinstance(axis, stage3.Axis) and not stage3.is_in_brackets(axis) and axis.value != 1 + } + axis_names_reduced = axis_names_in - axis_names_out + if len(axis_names_reduced) > 0: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(exprs_in + exprs_out, axis_names_reduced), + message=f"The input axes {axis_names_reduced} must appear in the output expression.\n%EXPR%", + ) + + if check is not None: + check(exprs_in, exprs_out, invocation) + + tensors = [_cast_shape(tensor, expr_in) for tensor, expr_in in zip(tensors, exprs_in, strict=False)] + + tensors = [NamedTensor(tensor, expr_in) for tensor, expr_in in zip(tensors, exprs_in, strict=False)] + try: + tensors = op(*tensors, out=exprs_out[0] if len(exprs_out) == 1 else exprs_out, **kwargs) + except SemanticError as e: + raise SemanticError(invocation=invocation, pos=e.pos, message=str(e)) from e + + if len(exprs_out) > 1: + return tuple(t.value for t in tensors) + else: + return tensors.value + + inner.__name__ = op.__name__ + inner.__qualname__ = op.__qualname__ + inner.__doc__ = op.__doc__ + inner.__module__ = op.__module__ + return inner + + +def id(op, **kwargs): + if "allow_concat" not in kwargs: + kwargs["allow_concat"] = True + + def el_op(op): + n_in = len(op.children[0].children) + n_out = n_in if len(op.children) == 1 else len(op.children[1].children) + args_in = ", ".join("" for i in range(n_in)) + args_out = ", ".join("" for i in range(n_out)) + return f"{args_in} -> {args_out}" + + return globals()["op"](op, el_op=el_op, implicit_output="bijective", **kwargs) + + +def elementwise(op, **kwargs): + def el_op(op): + n_in = len(op.children[0].children) + args_in = ", ".join("" for i in range(n_in)) + return f"{args_in} ->" + + return globals()["op"](op, el_op=el_op, implicit_output="bijective", **kwargs) + + +def dot(op, **kwargs): + def el_op(op): + return f"{op.children[0]} ->" + + return globals()["op"]( + op, el_op=el_op, implicit_output="bijective", mark_reduced_axes=True, allow_duplicate_el_axes=False, check=_semantic_checks_dot, **kwargs + ) + + +def _equations_stage3_index_at(exprs_in, exprs_out, invocation, is_update): + if len(exprs_in) <= 1: + return [] + + tensor_expr = exprs_in[0] + coord_exprs = exprs_in[1:-1] if is_update else exprs_in[1:] + coords_axes = [] + for coord_expr in coord_exprs: + marked_axes = [expr for expr in coord_expr.nodes() if isinstance(expr, stage2.Axis) and stage2.is_in_brackets(expr)] + if len(marked_axes) == 0: + coords_axes.append(stage2.Axis(f"unnamed.{uuid.uuid4().int}", 1, ellipsis_indices=[])) + elif len(marked_axes) == 1: + coords_axes.append(marked_axes[0]) + else: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(exprs_in + exprs_out, [expr.name for expr in marked_axes]), + message="Each coordinate expression must contain at most one axis in brackets.\n%EXPR%", + ) + marked_coord_axis = stage2.ConcatenatedAxis.create(coords_axes, ellipsis_indices=[]) + marked_axes_in = [expr for expr in tensor_expr.nodes() if isinstance(expr, stage2.Axis) and stage2.is_in_brackets(expr)] + + if marked_coord_axis.value is not None and marked_coord_axis.value != len(marked_axes_in): + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(exprs_in + exprs_out, [marked_coord_axis.name] + [expr.name for expr in marked_axes_in]), + message=( + f"The sum of the lengths of marked coordinate axes ({marked_coord_axis.value}) must match the number of marked axes " + f"in the first input expression ({len(marked_axes_in)}).\n%EXPR%" + ), + ) + + return [stage3.Equation(marked_coord_axis, stage2.Axis(f"unnamed.{uuid.uuid4().int}", len(marked_axes_in), ellipsis_indices=[]))] + + +def get_at(op, **kwargs): + def el_op(op): + return ", ".join(str(c) for c in op.children[0].children) + " ->" + + return globals()["op"]( + op, + el_op=el_op, + implicit_output="bijective", + check=_semantic_checks_get_at, + equations_stage3=partial(_equations_stage3_index_at, is_update=False), + **kwargs, + ) + + +def update_at(op, **kwargs): + def el_op(op): + return ", ".join(str(c) for c in op.children[0].children[:-1]) + f", -> {op.children[0].children[0]}" + + op = globals()["op"]( + op, + el_op=el_op, + implicit_output=0, + check=_semantic_checks_update_at, + equations_stage3=partial(_equations_stage3_index_at, is_update=True), + allow_nontrivial_unmarked_reduced_axes=True, + no_el_axis_permute=True, + **kwargs, + ) + + @use_name_of(op) + def op_with_zerosized_args(description, *tensors: Tensor, **kwargs): + if len(tensors) > 0 and any(int(i) == 0 for tensor in [t for t in tensors[1:] if t.shape is not None] for i in tensor.shape): + return tensors[0] # TODO: remove this when dynamic dimensions are supported? + else: + return op(description, *tensors, **kwargs) + + return op_with_zerosized_args + + +def reduce(op, **kwargs): + def el_op(op): + return f"{op.children[0].children[0]} ->" + + return globals()["op"](op, el_op=el_op, implicit_output="bijective", mark_reduced_axes=True, add_keepdims_param=True, **kwargs) + + +def _equations_stage3_argfind(exprs_in, exprs_out, invocation): + marked_axes_in = [expr for expr in exprs_in[0].nodes() if isinstance(expr, stage2.Axis) and stage2.is_in_brackets(expr)] + marked_axes_out = [expr for expr in exprs_out[0].nodes() if isinstance(expr, stage2.Axis) and stage2.is_in_brackets(expr)] + if len(marked_axes_out) == 0: + if len(marked_axes_in) != 1: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(exprs_in + exprs_out, [a.name for a in marked_axes_in]), + message=( + f"If no axis is marked with brackets in the output expression, exactly one axis must be marked in the " + f"input expression, but found {len(marked_axes_in)} marked axes.\n%EXPR%" + ), + ) + return [] + elif len(marked_axes_out) == 1: + marked_axis_out = marked_axes_out[0] + if marked_axis_out.value is not None and marked_axis_out.value != len(marked_axes_in): + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(exprs_in + exprs_out, [marked_axis_out.name] + [a.name for a in marked_axes_in]), + message=( + f"The value of the marked axis in the output expression ({marked_axis_out.value}) must match the number of marked " + f"axes in the input expression ({len(marked_axes_in)}).\n%EXPR%" + ), + ) + return [stage3.Equation(marked_axis_out, stage2.Axis(f"unnamed.{uuid.uuid4().int}", len(marked_axes_in), ellipsis_indices=[]))] + else: + raise SemanticError( + invocation=invocation, + pos=invocation.indicator.get_pos_for_axisnames(exprs_in + exprs_out, [a.name for a in marked_axes_out]), + message="The output expression must contain at most one axis in brackets.\n%EXPR%", + ) + + +def argfind(op, **kwargs): + def el_op(op): + if len(op.children) == 1 or op.children[1].children[0].ndim != 0: + return f"{op.children[0].children[0]} -> a{uuid.uuid4().int}" + else: + return f"{op.children[0].children[0]} ->" + + return globals()["op"](op, el_op=el_op, implicit_output="bijective", check=_semantic_checks_argfind, equations_stage3=_equations_stage3_argfind, **kwargs) + + +def preserve_shape(op, **kwargs): + def el_op(op): + return f"{op.children[0].children[0]} -> {op.children[0].children[0]}" + + return globals()["op"](op, el_op=el_op, implicit_output="bijective", no_el_axis_permute=True, **kwargs) + + +_name_to_op = ( + {name: elementwise for name in adapter.ops.elementwise} + | {name: partial(reduce, cse_in_brackets=True) for name in adapter.ops.reduce} + | {name: update_at for name in adapter.ops.update_at} + | {name: argfind for name in adapter.ops.argfind} + | { + "get_at": get_at, + "dot": dot, + "id": id, + "roll": partial(preserve_shape, iskwarg=["shift"]), + "flip": preserve_shape, + "sort": partial(preserve_shape, check=_semantic_checks_sort), + "argsort": partial(preserve_shape, check=_semantic_checks_sort), + "softmax": preserve_shape, + "log_softmax": preserve_shape, + } +) + + +def ops(namedtensor_ops, **kwargs): + return {name: _name_to_op[name](namedtensor_ops[name], **kwargs) for name in namedtensor_ops.keys()} diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/elementary_from_classical.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/elementary_from_classical.py new file mode 100644 index 0000000000000000000000000000000000000000..182691726d7f8f6125f0831df28c6b88cf672071 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/elementary_from_classical.py @@ -0,0 +1,107 @@ +import functools +import einx._src.adapter as adapter +import numpy as np +from ._util import _unravel +from einx._src.util.functools import use_name_of + + +def id(*args): + if len(args) == 1: + return args[0] + else: + return tuple(args) + + +def reduce(op): + @use_name_of(op) + def reduce(tensor): + return op(tensor) + + return reduce + + +def preserve_shape(op): + @use_name_of(op) + def preserve_shape(tensor, **kwargs): + return op(tensor, **kwargs) + + return preserve_shape + + +def elementwise(op): + @use_name_of(op) + def elementwise(*tensors): + if any(tensor.ndim != 0 for tensor in tensors): + raise ValueError("All tensors must be scalars for elementwise operation.") + return op(*tensors) + + return elementwise + + +def dot(classical): + return classical.dot + + +def get_at(classical): + def get_at(tensor, *coordinates): + coords2 = [] + for coord in coordinates: + if coord.ndim == 0: + coords2.append(coord) + elif coord.ndim == 1: + for i in range(coord.shape[0]): + coords2.append(classical.get_at(coord, i, axis=0)) + else: + raise ValueError("Coordinate tensors must be scalars or 1D arrays.") + if tensor.ndim != len(coords2): + raise ValueError("Number of coordinates must match the number of dimensions of the tensor.") + return classical.get_at(tensor, tuple(coords2)) + + return get_at + + +def update_at(op, classical): + @use_name_of(op) + def update_at(*tensors): + tensor = tensors[0] + coordinates = tensors[1:-1] + updates = tensors[-1] + + coords2 = [] + for coord in coordinates: + if coord.ndim == 0: + coords2.append(coord) + elif coord.ndim == 1: + for i in range(coord.shape[0]): + coords2.append(classical.get_at(coord, i, axis=0)) + else: + raise ValueError("Coordinate tensors must be scalars or 1D arrays.") + if tensor.ndim != len(coords2): + raise ValueError("Number of coordinates must match the number of dimensions of the tensor.") + + return op(tensor, tuple(coords2), updates) + + return update_at + + +def argfind(op, classical): + @use_name_of(op) + def argfind(tensor): + idx = op(classical.reshape(tensor, (np.prod(tensor.shape),))) + if tensor.ndim == 0: + raise ValueError("Tensor must have at least one dimension for argfind operation.") + else: + return _unravel(classical, idx, tensor.shape, axis=0) + + return argfind + + +def ops(classical): + return ( + {name: elementwise(getattr(classical, name)) for name in adapter.ops.elementwise} + | {name: reduce(getattr(classical, name)) for name in adapter.ops.reduce} + | {name: preserve_shape(getattr(classical, name)) for name in adapter.ops.preserve_shape} + | {name: argfind(getattr(classical, name), classical) for name in adapter.ops.argfind} + | {name: update_at(getattr(classical, name), classical) for name in adapter.ops.update_at} + | {"get_at": get_at(classical), "dot": dot(classical), "id": id} + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/functorchdim/__pycache__/namedtensor_from_functorchdim.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/functorchdim/__pycache__/namedtensor_from_functorchdim.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7eb9bec6062ae4a414cd747e0eba443760f45093 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/functorchdim/__pycache__/namedtensor_from_functorchdim.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/functorchdim/namedtensor_from_functorchdim.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/functorchdim/namedtensor_from_functorchdim.py new file mode 100644 index 0000000000000000000000000000000000000000..01180dc6b592fc9cac290cf89ba226544c515858 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/functorchdim/namedtensor_from_functorchdim.py @@ -0,0 +1,141 @@ +import einx._src.namedtensor.stage3 as stage3 +import einx._src.tracer as tracer +import functools +import einx._src.util.pytree as pytree +from einx._src.namedtensor import NamedTensor +from einx._src.util.functools import use_name_of +from .._util import _to_tensor + + +def _to_ord_str(i): + if i == 0: + return "1st" + elif i == 1: + return "2nd" + elif i == 2: + return "3rd" + else: + return f"{i + 1}th" + + +def expr_to_ftdims(expr, axisname_to_ftdim, runtime_axisname_to_ftdims=None): + if isinstance(expr, stage3.List): + return tuple(ftdim for child in expr.children for ftdim in expr_to_ftdims(child, axisname_to_ftdim, runtime_axisname_to_ftdims)) + elif isinstance(expr, stage3.Axis): + if expr.name in axisname_to_ftdim: + return (axisname_to_ftdim[expr.name],) + else: + assert runtime_axisname_to_ftdims is not None + return (runtime_axisname_to_ftdims[expr.name],) + elif isinstance(expr, stage3.ConcatenatedAxis): + raise ValueError("functorchdim does not support axis concatenation.") + elif isinstance(expr, stage3.FlattenedAxis): + return (expr_to_ftdims(expr.inner, axisname_to_ftdim, runtime_axisname_to_ftdims),) + elif isinstance(expr, stage3.Brackets): + return expr_to_ftdims(expr.inner, axisname_to_ftdim, runtime_axisname_to_ftdims) + else: + raise ValueError(f"Unexpected expression type: {type(expr)}") + + +def op(op, torch, functorchdim, get_device): + @use_name_of(op) + def inner(*tensors, out, **kwargs): + if not isinstance(out, list | tuple): + out = [out] + + to_tensor = _to_tensor(lambda x: torch.asarray(x, device=get_device()), forward=[torch.Tensor], convert=["numpy", "scalar"]) + tensors = [NamedTensor(to_tensor(tensor.value), tensor.expr) for tensor in tensors] + + # Convert classical tensors to functorchdim tensors + axisname_to_value = {axis.name: axis.value for tensor in tensors for axis in tensor.expr.nodes() if isinstance(axis, stage3.Axis)} + axisname_to_ftdim = {name: functorchdim.Dim(name, value) for name, value in axisname_to_value.items()} + + fttensors = [] + for tensor in tensors: + axisnames = [axis.name for axis in tensor.expr.nodes() if isinstance(axis, stage3.Axis)] + ftdims = expr_to_ftdims(tensor.expr, axisname_to_ftdim) + shape = {axisname: axisname_to_value[axisname] for axisname in axisnames} + + fttensor = tracer.signature.python.getitem(tensor.value, ftdims) + fttensor = tracer.cast(fttensor, lambda origin: tracer.signature.functorchdim.Tensor(origin, shape=shape)) + fttensors.append(fttensor) + + # Call the operation with functorchdim tensors + axes = {axis.name for tensor in tensors for axis in tensor.expr.nodes() if isinstance(axis, stage3.Axis) if stage3.is_in_brackets(axis)} + axes = {name: axisname_to_ftdim[name] for name in axes} + axes = tuple( + tuple(axes[axis.name] for axis in tensor.expr.nodes() if isinstance(axis, stage3.Axis) if stage3.is_in_brackets(axis)) for tensor in tensors + ) + fttensors = op(*fttensors, axes=axes, **kwargs) + + # Cast return value back to classical tensors + if isinstance(fttensors, tracer.Tracer): + # Create list of tracers + if len(out) == 1: + fttensors = [fttensors] + else: + fttensors = tracer.signature.python.assert_( + fttensors, + tracer.signature.python.builtins.isinstance(fttensors, tracer.signature.python.builtins.tuple), + f"Expected the adapted function to return a tuple of length {len(out)}", + ) + fttensors = tracer.signature.python.assert_( + fttensors, + tracer.signature.python.equal(tracer.signature.python.builtins.len(fttensors), len(out)), + f"Expected the adapted function to return a tuple of length {len(out)}", + ) + fttensors = tracer.cast(fttensors, lambda origin: [tracer.signature.python.Value(origin) for _ in range(len(out))]) + elif isinstance(fttensors, tuple) and all(isinstance(t, tracer.signature.Tracer) for t in fttensors): + # Return value already is a tuple of tracers + if len(fttensors) != len(out): + raise ValueError(f"Expected the adapted function to return a tuple of length {len(out)}, but got length {len(fttensors)}") + else: + raise ValueError(f"Expected the adapted function to return a tracer or a tuple of tracers, but got {pytree.map(type, fttensors)}") + + tensors = [] + for i, (fttensor, expr) in enumerate(zip(fttensors, out, strict=False)): + axisnames = [axis.name for axis in expr.nodes() if isinstance(axis, stage3.Axis)] + expected_shape = {axisname: axisname_to_value[axisname] for axisname in axisnames} + + if isinstance(fttensor, tracer.signature.functorchdim.Tensor): + # Return type is a tensor -> ensure that the static shape is correct + if t(fttensor.shape) != t(expected_shape): + raise ValueError( + f"Expected {_to_ord_str(i)} return value of the adapted function to be a tensor with shape {expected_shape}, " + f"but got shape {fttensor.shape}" + ) + else: + # Return type is a general tracer object -> ensure that it has the correct type and that the shape is correct at runtime. + # Then cast to expected shape + fttensor = tracer.signature.python.assert_( + fttensor, + tracer.signature.python.builtins.isinstance(fttensor, functorchdim.Tensor), + f"Expected {_to_ord_str(i)} return value of the adapted function to be a tensor", + ) + runtime_shape = tracer.signature.python.builtins.dict( + tracer.signature.python.builtins.map( + tracer.signature.python.function(lambda dim: (tracer.signature.python.builtins.repr(dim), dim.size)), fttensor.dims + ) + ) + fttensor = tracer.signature.python.assert_( + fttensor, + tracer.signature.python.equal(runtime_shape, expected_shape), + f"Expected {_to_ord_str(i)} return value of the adapted function to be a tensor with shape {expected_shape}", + ) + fttensor = tracer.cast(fttensor, lambda origin: tracer.signature.functorchdim.Tensor(origin, shape=expected_shape)) + + runtime_axisname_to_ftdims = tracer.signature.python.builtins.dict( + tracer.signature.python.builtins.map(tracer.signature.python.function(lambda dim: (tracer.signature.python.builtins.repr, dim)), fttensor.dims) + ) + ftdims = expr_to_ftdims(expr, axisname_to_ftdim, runtime_axisname_to_ftdims) # Prefer statically available ftdims + + tensor = fttensor.order(*ftdims) + tensor = tracer.cast(tensor, lambda origin: tracer.signature.classical.Tensor(origin, shape=expr.shape)) + tensors.append(NamedTensor(tensor, expr)) + + if len(tensors) == 1: + return tensors[0] + else: + return tuple(tensors) + + return inner diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/__pycache__/classical_from_jax.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/__pycache__/classical_from_jax.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9395e2d2501d1be70c0908347a9d5589d56752f5 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/__pycache__/classical_from_jax.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/__pycache__/einsum_from_jax.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/__pycache__/einsum_from_jax.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dd4cc5ed2b9418f37727339bd3910a35f323d30 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/__pycache__/einsum_from_jax.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/__pycache__/vmap_from_jax.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/__pycache__/vmap_from_jax.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..659590b2e2030102b6b187d4ca7d99a87ea66014 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/__pycache__/vmap_from_jax.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/classical_from_jax.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/classical_from_jax.py new file mode 100644 index 0000000000000000000000000000000000000000..a3406b2c4ecc4646b06d03bec0d3a0aad85da6a5 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/classical_from_jax.py @@ -0,0 +1,85 @@ +import einx._src.adapter as adapter +import numpy as np +from einx._src.util.functools import use_name_of +from .._util import _associative_binary_to_nary, _to_tensor + + +class ops: + def __init__(self, jax): + jnp = jax.numpy + + def to_tensor_all(*args): + to_tensor_one = _to_tensor(jnp.asarray, forward=[jnp.ndarray, "numpy", "scalar"], convert=[]) + return [to_tensor_one(arg) for arg in args] + + self.reshape = adapter.classical_from_numpy.reshape(jnp.reshape, to_tensor=to_tensor_all) + self.transpose = adapter.classical_from_numpy.transpose(jnp.transpose, to_tensor=to_tensor_all) + self.broadcast_to = adapter.classical_from_numpy.broadcast_to(jnp.broadcast_to, to_tensor=to_tensor_all) + self.diagonal = adapter.classical_from_numpy.diagonal(jnp.diagonal, self.transpose, to_tensor=to_tensor_all) + self.stop_gradient = jax.lax.stop_gradient + + self.add = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(jnp.add), to_tensor=to_tensor_all) + self.subtract = adapter.classical_from_numpy.elementwise(jnp.subtract, to_tensor=to_tensor_all) + self.multiply = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(jnp.multiply), to_tensor=to_tensor_all) + self.true_divide = adapter.classical_from_numpy.elementwise(jnp.true_divide, to_tensor=to_tensor_all) + self.floor_divide = adapter.classical_from_numpy.elementwise(jnp.floor_divide, to_tensor=to_tensor_all) + self.divide = adapter.classical_from_numpy.elementwise(jnp.divide, to_tensor=to_tensor_all) + self.logaddexp = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(jnp.logaddexp), to_tensor=to_tensor_all) + self.logical_and = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(jnp.logical_and), to_tensor=to_tensor_all) + self.logical_or = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(jnp.logical_or), to_tensor=to_tensor_all) + self.where = adapter.classical_from_numpy.elementwise(jnp.where, to_tensor=to_tensor_all) + self.maximum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(jnp.maximum), to_tensor=to_tensor_all) + self.minimum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(jnp.minimum), to_tensor=to_tensor_all) + self.less = adapter.classical_from_numpy.elementwise(jnp.less, to_tensor=to_tensor_all) + self.less_equal = adapter.classical_from_numpy.elementwise(jnp.less_equal, to_tensor=to_tensor_all) + self.greater = adapter.classical_from_numpy.elementwise(jnp.greater, to_tensor=to_tensor_all) + self.greater_equal = adapter.classical_from_numpy.elementwise(jnp.greater_equal, to_tensor=to_tensor_all) + self.equal = adapter.classical_from_numpy.elementwise(jnp.equal, to_tensor=to_tensor_all) + self.not_equal = adapter.classical_from_numpy.elementwise(jnp.not_equal, to_tensor=to_tensor_all) + self.exp = adapter.classical_from_numpy.elementwise(jnp.exp, to_tensor=to_tensor_all) + self.log = adapter.classical_from_numpy.elementwise(jnp.log, to_tensor=to_tensor_all) + self.negative = adapter.classical_from_numpy.elementwise(jnp.negative, to_tensor=to_tensor_all) + self.divmod = adapter.classical_from_numpy.elementwise(jnp.divmod, to_tensor=to_tensor_all) + + self.sum = adapter.classical_from_numpy.reduce(jnp.sum, to_tensor=to_tensor_all) + self.mean = adapter.classical_from_numpy.reduce(jnp.mean, to_tensor=to_tensor_all) + self.var = adapter.classical_from_numpy.reduce(jnp.var, to_tensor=to_tensor_all) + self.std = adapter.classical_from_numpy.reduce(jnp.std, to_tensor=to_tensor_all) + self.prod = adapter.classical_from_numpy.reduce(jnp.prod, to_tensor=to_tensor_all) + self.count_nonzero = adapter.classical_from_numpy.reduce(jnp.count_nonzero, to_tensor=to_tensor_all) + self.any = adapter.classical_from_numpy.reduce(jnp.any, to_tensor=to_tensor_all) + self.all = adapter.classical_from_numpy.reduce(jnp.all, to_tensor=to_tensor_all) + self.max = adapter.classical_from_numpy.reduce(jnp.max, to_tensor=to_tensor_all) + self.min = adapter.classical_from_numpy.reduce(jnp.min, to_tensor=to_tensor_all) + self.logsumexp = adapter.classical_from_numpy.reduce(jax.nn.logsumexp, to_tensor=to_tensor_all) + self.argmax = adapter.classical_from_numpy.reduce(jnp.argmax, to_tensor=to_tensor_all) + self.argmin = adapter.classical_from_numpy.reduce(jnp.argmin, to_tensor=to_tensor_all) + + self.sort = adapter.classical_from_numpy.sort(jnp.sort, to_tensor=to_tensor_all) + self.argsort = adapter.classical_from_numpy.sort(jnp.argsort, to_tensor=to_tensor_all) + self.roll = adapter.classical_from_numpy.roll(jnp.roll, to_tensor=to_tensor_all) + self.flip = adapter.classical_from_numpy.preserve_shape(jnp.flip, to_tensor=to_tensor_all) + self.softmax = adapter.classical_from_numpy.preserve_shape(jax.nn.softmax, to_tensor=to_tensor_all) + self.log_softmax = adapter.classical_from_numpy.preserve_shape(jax.nn.log_softmax, to_tensor=to_tensor_all) + + def to_tensor_index(x, *args): + x = _to_tensor(jnp.asarray, forward=[jnp.ndarray], convert=["numpy", "scalar"])(x) + args = [_to_tensor(jnp.asarray, forward=[jnp.ndarray, "numpy", "scalar"], convert=[])(a) for a in args] + return x, *args + + self.get_at = adapter.classical_from_numpy.get_at(jnp.ndarray.__getitem__, jnp.take, to_tensor=to_tensor_index) + self.set_at = adapter.classical_from_numpy.update_at( + lambda x, indices, updates: jnp.ndarray.at(x, indices).set(updates), to_tensor=to_tensor_index, broadcast=self.broadcast_to + ) + self.add_at = adapter.classical_from_numpy.update_at( + lambda x, indices, updates: jnp.ndarray.at(x, indices).add(updates), to_tensor=to_tensor_index, broadcast=self.broadcast_to + ) + self.subtract_at = adapter.classical_from_numpy.update_at( + lambda x, indices, updates: jnp.ndarray.at(x, indices).subtract(updates), to_tensor=to_tensor_index, broadcast=self.broadcast_to + ) + + self.arange = adapter.classical_from_numpy.arange(jnp.arange) + self.split = adapter.classical_from_numpy.split(jnp.split, to_tensor=to_tensor_all) + self.concatenate = adapter.classical_from_numpy.concatenate(jnp.concatenate, to_tensor=to_tensor_all) + self.dot = adapter.classical_from_numpy.dot(jnp.dot, to_tensor=to_tensor_all) + self.matmul = adapter.classical_from_numpy.matmul(jnp.matmul, to_tensor=to_tensor_all) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/einsum_from_jax.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/einsum_from_jax.py new file mode 100644 index 0000000000000000000000000000000000000000..5ac9a3bdd25ecd54dde0305568f4e90d2242ed0a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/einsum_from_jax.py @@ -0,0 +1,10 @@ +import einx._src.adapter as adapter +from .._util import _to_tensor + + +def einsum_from_jax(jax): + def to_tensor(*args): + to_tensor_one = _to_tensor(jax.numpy.asarray, forward=[jax.numpy.ndarray, "numpy", "scalar"], convert=[]) + return [to_tensor_one(arg) for arg in args] + + return adapter.einsum_from_numpy(jax.numpy.einsum, to_tensor=to_tensor) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/vmap_from_jax.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/vmap_from_jax.py new file mode 100644 index 0000000000000000000000000000000000000000..c77b3c896cbc4c01f09511c332bfeec340717789 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/jax/vmap_from_jax.py @@ -0,0 +1,24 @@ +from .._util import _to_tensor +from einx._src.util.functools import use_name_of + + +def vmap_from_jax(op=None, to_tensor=None): + if to_tensor is None: + jax = op + op = jax.vmap + + def to_tensor(*args): + to_tensor_one = _to_tensor(jax.numpy.asarray, forward=[jax.numpy.ndarray, "scalar"], convert=["numpy"]) + return [to_tensor_one(arg) for arg in args] + + def vmap(func, in_axes=0, out_axes=0): + func = op(func, in_axes=in_axes, out_axes=out_axes) + + @use_name_of(func) + def wrapped_func(*args): + args = to_tensor(*args) + return func(*args) + + return wrapped_func + + return vmap diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/__pycache__/classical_from_mlx.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/__pycache__/classical_from_mlx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69e68dbcb14ac4ddfbc736938de77c175656706d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/__pycache__/classical_from_mlx.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/__pycache__/einsum_from_mlx.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/__pycache__/einsum_from_mlx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7bc98ae96a49d2a614e2115b2665264deed86d5 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/__pycache__/einsum_from_mlx.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/__pycache__/vmap_from_mlx.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/__pycache__/vmap_from_mlx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d34010d18a25a0f449fbb5d143c3d5aef6e47c62 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/__pycache__/vmap_from_mlx.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/classical_from_mlx.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/classical_from_mlx.py new file mode 100644 index 0000000000000000000000000000000000000000..61fe3f47bb0c2ae89ba2418bea2be578f501601c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/classical_from_mlx.py @@ -0,0 +1,89 @@ +import einx._src.adapter as adapter +import numpy as np +from functools import partial +from einx._src.util.functools import use_name_of +from .._util import _associative_binary_to_nary, _to_tensor + + +def dot(tensordot, to_tensor): + return adapter.classical_from_numpy.dot(lambda *args: tensordot(*args, axes=1), to_tensor=to_tensor) + + +class ops: + def __init__(self, mlx): + mx = mlx.core + + def to_tensor_all(*args): + to_tensor_one = _to_tensor(mx.array, forward=[mx.array], convert=["scalar", "numpy"]) + return [to_tensor_one(arg) for arg in args] + + def _to_dtype(x): + if isinstance(x, str): + return getattr(mx, x) + else: + return x + + self.reshape = adapter.classical_from_numpy.reshape(mx.reshape, to_tensor=to_tensor_all) + self.transpose = adapter.classical_from_numpy.transpose(mx.transpose, to_tensor=to_tensor_all) + self.broadcast_to = adapter.classical_from_numpy.broadcast_to(mx.broadcast_to, to_tensor=to_tensor_all) + self.diagonal = adapter.classical_from_numpy.diagonal(mx.diagonal, self.transpose, to_tensor=to_tensor_all) + self.stop_gradient = mx.stop_gradient + + self.add = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(mx.add), to_tensor=to_tensor_all) + self.subtract = adapter.classical_from_numpy.elementwise(mx.subtract, to_tensor=to_tensor_all) + self.multiply = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(mx.multiply), to_tensor=to_tensor_all) + self.true_divide = adapter.classical_from_numpy.elementwise(mx.divide, to_tensor=to_tensor_all) + self.floor_divide = adapter.classical_from_numpy.elementwise(mx.floor_divide, to_tensor=to_tensor_all) + self.divide = adapter.classical_from_numpy.elementwise(mx.divide, to_tensor=to_tensor_all) + self.logaddexp = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(mx.logaddexp), to_tensor=to_tensor_all) + self.logical_and = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(mx.logical_and), to_tensor=to_tensor_all) + self.logical_or = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(mx.logical_or), to_tensor=to_tensor_all) + self.where = adapter.classical_from_numpy.elementwise(mx.where, to_tensor=to_tensor_all) + self.maximum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(mx.maximum), to_tensor=to_tensor_all) + self.minimum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(mx.minimum), to_tensor=to_tensor_all) + self.less = adapter.classical_from_numpy.elementwise(mx.less, to_tensor=to_tensor_all) + self.less_equal = adapter.classical_from_numpy.elementwise(mx.less_equal, to_tensor=to_tensor_all) + self.greater = adapter.classical_from_numpy.elementwise(mx.greater, to_tensor=to_tensor_all) + self.greater_equal = adapter.classical_from_numpy.elementwise(mx.greater_equal, to_tensor=to_tensor_all) + self.equal = adapter.classical_from_numpy.elementwise(mx.equal, to_tensor=to_tensor_all) + self.not_equal = adapter.classical_from_numpy.elementwise(mx.not_equal, to_tensor=to_tensor_all) + self.exp = adapter.classical_from_numpy.elementwise(mx.exp, to_tensor=to_tensor_all) + self.log = adapter.classical_from_numpy.elementwise(mx.log, to_tensor=to_tensor_all) + self.negative = adapter.classical_from_numpy.elementwise(mx.negative, to_tensor=to_tensor_all) + self.divmod = adapter.classical_from_numpy.elementwise(mx.divmod, to_tensor=to_tensor_all) + + self.sum = adapter.classical_from_numpy.reduce(mx.sum, to_tensor=to_tensor_all) + self.mean = adapter.classical_from_numpy.reduce(mx.mean, to_tensor=to_tensor_all) + self.var = adapter.classical_from_numpy.reduce(mx.var, to_tensor=to_tensor_all) + self.std = adapter.classical_from_numpy.reduce(mx.std, to_tensor=to_tensor_all) + self.prod = adapter.classical_from_numpy.reduce(mx.prod, to_tensor=to_tensor_all) + self.count_nonzero = adapter.classical_from_classical.count_nonzero(self) + self.any = adapter.classical_from_numpy.reduce(mx.any, to_tensor=to_tensor_all) + self.all = adapter.classical_from_numpy.reduce(mx.all, to_tensor=to_tensor_all) + self.max = adapter.classical_from_numpy.reduce(mx.max, to_tensor=to_tensor_all) + self.min = adapter.classical_from_numpy.reduce(mx.min, to_tensor=to_tensor_all) + self.logsumexp = adapter.classical_from_numpy.reduce(mx.logsumexp, to_tensor=to_tensor_all) + self.argmax = adapter.classical_from_numpy.reduce(mx.argmax, to_tensor=to_tensor_all) + self.argmin = adapter.classical_from_numpy.reduce(mx.argmin, to_tensor=to_tensor_all) + + self.sort = adapter.classical_from_numpy.sort(mx.sort, to_tensor=to_tensor_all) + self.argsort = adapter.classical_from_numpy.sort(mx.argsort, to_tensor=to_tensor_all) + self.roll = adapter.classical_from_numpy.roll(mx.roll, to_tensor=to_tensor_all) + self.flip = adapter.classical_from_classical.flip(self, mx.array.__getitem__) + self.softmax = adapter.classical_from_numpy.preserve_shape(mlx.nn.softmax, to_tensor=to_tensor_all) + self.log_softmax = adapter.classical_from_numpy.preserve_shape(mlx.nn.log_softmax, to_tensor=to_tensor_all) + + self.get_at = adapter.classical_from_numpy.get_at(mx.array.__getitem__, mx.take, to_tensor=to_tensor_all) + self.set_at = adapter.classical_from_numpy.update_at(mx.array.__setitem__, to_tensor=to_tensor_all) + self.add_at = adapter.classical_from_numpy.update_at( + lambda x, indices, updates: mx.array.at(x, indices).add(updates), to_tensor=to_tensor_all, broadcast=self.broadcast_to + ) + self.subtract_at = adapter.classical_from_numpy.update_at( + lambda x, indices, updates: mx.array.at(x, indices).subtract(updates), to_tensor=to_tensor_all, broadcast=self.broadcast_to + ) + + self.arange = adapter.classical_from_numpy.arange(mx.arange, to_dtype=_to_dtype) + self.split = adapter.classical_from_numpy.split(mx.split, to_tensor=to_tensor_all) + self.concatenate = adapter.classical_from_numpy.concatenate(mx.concatenate, to_tensor=to_tensor_all) + self.dot = adapter.classical_from_mlx.dot(mx.tensordot, to_tensor=to_tensor_all) + self.matmul = adapter.classical_from_numpy.matmul(mx.matmul, to_tensor=to_tensor_all) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/einsum_from_mlx.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/einsum_from_mlx.py new file mode 100644 index 0000000000000000000000000000000000000000..6e25d29bc2bb8653a2c6cd08d671698e0402d96a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/einsum_from_mlx.py @@ -0,0 +1,10 @@ +import einx._src.adapter as adapter +from .._util import _to_tensor + + +def einsum_from_mlx(mlx): + def to_tensor(*args): + to_tensor_one = _to_tensor(mlx.core.array, forward=[mlx.core.array], convert=["numpy", "scalar"]) + return [to_tensor_one(arg) for arg in args] + + return adapter.einsum_from_numpy(mlx.core.einsum, to_tensor=to_tensor, multiply=adapter.classical_from_mlx.ops(mlx).multiply) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/vmap_from_mlx.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/vmap_from_mlx.py new file mode 100644 index 0000000000000000000000000000000000000000..a248ae9e60a1d369c3d85f5658fb7214b67c8a7c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/mlx/vmap_from_mlx.py @@ -0,0 +1,11 @@ +from .._util import _to_tensor +from einx._src.util.functools import use_name_of +import einx._src.adapter as adapter + + +def vmap_from_mlx(mlx): + def to_tensor(*args): + to_tensor_one = _to_tensor(mlx.core.array, forward=[mlx.core.array], convert=["numpy", "scalar"]) + return [to_tensor_one(arg) for arg in args] + + return adapter.vmap_from_jax(mlx.core.vmap, to_tensor=to_tensor) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/namedtensor_calltensorfactory.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/namedtensor_calltensorfactory.py new file mode 100644 index 0000000000000000000000000000000000000000..0977144ea8c1dfe3780863161b2c68dd09c9a7bd --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/namedtensor_calltensorfactory.py @@ -0,0 +1,85 @@ +from einx._src.namedtensor import NamedTensor +import einx._src.tracer as tracer +from collections.abc import Callable +import functools +import inspect +import types +from einx._src.util.functools import use_name_of +import contextlib + + +def _call_tensorfactory(tensor, kwargs): + expr = tensor.expr + tensor = tensor.value + called = False + + if isinstance(tensor, tracer.signature.classical.ConvertibleTensor) and issubclass(tensor.concrete.type, Callable): + # Determine arguments that are passed to the tensor factory + shape = tuple(tensor.shape) + if kwargs is None: + kwargs = {} + has_var_kwargs = any(param.kind in [inspect.Parameter.VAR_KEYWORD] for param in tensor.concrete.parameters.values()) + + def use_parameter(name): + return has_var_kwargs or ( + name in tensor.concrete.parameters + and tensor.concrete.parameters[name].kind in [inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY] + ) + + kwargs = {name: value for name, value in kwargs.items() if use_parameter(name)} + + # Call the factory + tensor = tracer.signature.python.call(tensor, args=[shape], kwargs=kwargs) + called = True + + return tensor, expr, called + + +def _assert_output(tensor, expr, called, expected_type): + if called: + if callable(expected_type) and not isinstance(expected_type, type) and not isinstance(expected_type, tracer.Tracer): + expected_type = expected_type() + + tensor = tracer.signature.python.assert_( + tensor, + tracer.signature.python.builtins.isinstance(tensor, expected_type), + "Invalid type as output of tensor factory", # TODO: + ) + tensor = tracer.signature.python.assert_( + tensor, + tracer.signature.python.equal(tracer.signature.python.builtins.tuple(tensor.shape), expr.shape), + f"Expected shape {expr.shape} as output of tensor factory", # TODO: + ) + tensor = tracer.cast(tensor, lambda origin: tracer.signature.classical.Tensor(origin, shape=expr.shape)) + + return NamedTensor(tensor, expr) + + +class namedtensor_calltensorfactory: + @staticmethod + def op(op, expected_type, context=None, kwargs=None): + if context is None: + context = lambda *args: contextlib.nullcontext() + factory_kwargs = kwargs if kwargs is not None else {} + + @use_name_of(op) + def inner(*tensors, out, **kwargs): + signature = types.SimpleNamespace(exprs_in=tuple(t.expr for t in tensors), exprs_out=tuple(out) if isinstance(out, tuple | list) else (out,)) + signature = tracer.signature.python.constant(signature) + xs = [ + _call_tensorfactory(tensor, kwargs={"signature": signature, "arg_index": arg_index} | factory_kwargs) + for arg_index, tensor in enumerate(tensors) + ] + + with context([tensor for tensor, expr, called in xs]): + tensors = [_assert_output(tensor, expr, called, expected_type) for tensor, expr, called in xs] + + return op(*tensors, out=out, **kwargs) + + return inner + + @staticmethod + def ops(ops, expected_type, context=None, kwargs=None): + if kwargs is None: + kwargs = {} + return {name: namedtensor_calltensorfactory.op(op, expected_type, kwargs={"name": name} | kwargs, context=context) for name, op in ops.items()} diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/namedtensor_from_decomposednamedtensor.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/namedtensor_from_decomposednamedtensor.py new file mode 100644 index 0000000000000000000000000000000000000000..e6e02ea583f134b225a181f64d1beae795cb5244 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/namedtensor_from_decomposednamedtensor.py @@ -0,0 +1,271 @@ +import numpy as np +import einx._src.namedtensor.stage3 as stage3 +from einx._src.namedtensor import NamedTensor +import functools +from einx._src.adapter._util import _squeeze_transpose_broadcast +from einx._src.util.functools import use_name_of +from einx._src.frontend.errors import SemanticError + +py_id = id + + +class Decomposer: + def __init__(self, classical): + self.classical = classical + + def __call__(self, func): + @use_name_of(func) + def inner(tensors, exprs_out): + exprs_in = [tensors.expr for tensors in tensors] + tensors = [tensors.value for tensors in tensors] + + # Decompose + exprs_in, tensors = self._decompose(exprs_in, tensors) + exprs_out_flat, _ = self._decompose(exprs_out, None) + + # Remove unitary vectorized axes from input + exprs_in2 = [] + tensors2 = [] + + def is_squeezable_axis(expr): + return isinstance(expr, stage3.Axis) and not stage3.is_in_brackets(expr) and expr.value == 1 + + for expr_in, tensor in zip(exprs_in, tensors, strict=False): + expr_in = stage3.remove(expr_in, is_squeezable_axis, keep_children=False) + tensor = self.classical.reshape(tensor, expr_in.shape) + exprs_in2.append(expr_in) + tensors2.append(tensor) + exprs_in = exprs_in2 + tensors = tensors2 + + # Remove broadcast axes from output + in_axis_names = {axis.name for expr in exprs_in for axis in expr if isinstance(axis, stage3.Axis)} + + def is_broadcast_axis(expr): + return isinstance(expr, stage3.Axis) and expr.name not in in_axis_names and not stage3.is_in_brackets(expr) + + exprs_out_flat_without_broadcast = [stage3.remove(expr, is_broadcast_axis, keep_children=False) for expr in exprs_out_flat] + + # Call inner function + tensors = [NamedTensor(tensor, expr) for tensor, expr in zip(tensors, exprs_in, strict=False)] + tensors = func(tensors, exprs_out_flat_without_broadcast) + exprs_in = [t.expr for t in tensors] + tensors = [t.value for t in tensors] + + # Transpose and broadcast to output shape + x = [ + _squeeze_transpose_broadcast(self.classical, expr_in, tensor, expr_out_flat) + for expr_in, tensor, expr_out_flat in zip(exprs_in, tensors, exprs_out_flat, strict=False) + ] + tensors = [x[1] for x in x] + exprs_in = [x[0] for x in x] + + # Compose + tensors = self._compose(exprs_in, tensors, exprs_out) + + return [NamedTensor(tensor, expr) for tensor, expr in zip(tensors, exprs_out, strict=False)] + + return inner + + def _decompose_single(self, expr, tensor=None): + def readd_brackets(a): + if stage3.is_in_brackets(a): + return stage3.Brackets.create(a.__deepcopy__()) + else: + return a.__deepcopy__() + + # Decompose flattened axes + if any(isinstance(e, stage3.FlattenedAxis) for e in expr): + + def unflatten(e): + if isinstance(e, stage3.FlattenedAxis): + return readd_brackets(e.inner) + else: + return readd_brackets(e) + + expr = stage3.List.create([unflatten(e) for e in expr]) + + if tensor is not None: + tensor = self.classical.reshape(tensor, expr.shape) + + return self._decompose_single(expr, tensor) + + # Decompose repeated axes (not in brackets) + axis_counts = {} + for axis in expr: + if isinstance(axis, stage3.Axis) and not stage3.is_in_brackets(axis): + axis_counts[axis.name] = axis_counts.get(axis.name, 0) + 1 + if any(count > 1 for count in axis_counts.values()): + for axis_name, count in axis_counts.items(): + if count > 1: + indices_in = [i for i, a in enumerate(expr) if isinstance(a, stage3.Axis) and a.name == axis_name] + index_out = indices_in[0] + + expr = stage3.List.create([ + readd_brackets(a) for i, a in enumerate(expr) if not (isinstance(a, stage3.Axis) and a.name == axis_name and i != indices_in[0]) + ]) + if tensor is not None: + tensor = self.classical.diagonal(tensor, axes_in=indices_in, axis_out=index_out) + + return self._decompose_single(expr, tensor) + + # Decompose concatenated axes + if any(isinstance(e, stage3.ConcatenatedAxis) for e in expr): + concat_index, concat_expr = [(i, e) for i, e in enumerate(expr) if isinstance(e, stage3.ConcatenatedAxis)][0] + splits = np.cumsum([c.shape[0] for c in concat_expr.children])[:-1] + splits = splits.tolist() + + if tensor is not None: + subtensors = self.classical.split(tensor, splits, axis=concat_index) + else: + subtensors = [None for _ in concat_expr.children] + + subexprs = [] + for i in range(len(concat_expr.children)): + subexpr = stage3.map(expr, lambda expr: expr.children[i].__deepcopy__() if py_id(expr) == py_id(concat_expr) else None, include_children=False) + subexprs.append(subexpr) + + return self._decompose(subexprs, subtensors) + + # No more decomposition possible + return [expr], [tensor] + + def _decompose(self, exprs, tensors=None): + if tensors is None: + tensors = [None for _ in exprs] + + tensors_out = [] + exprs_out = [] + for expr, tensor in zip(exprs, tensors, strict=False): + subexprs, subtensors = self._decompose_single(expr, tensor) + exprs_out.extend(subexprs) + tensors_out.extend(subtensors) + + return exprs_out, tensors_out + + def _compose_next(self, exprs_in, tensors_in, expr_out): + def unflatten(e): + if isinstance(e, stage3.FlattenedAxis): + return e.inner.__deepcopy__() + else: + return e.__deepcopy__() + + expr_out_flat = stage3.List.create([unflatten(e) for e in expr_out]) + + if any(isinstance(e, stage3.ConcatenatedAxis) for e in expr_out_flat): + concat_index, concat_expr = [(i, e) for i, e in enumerate(expr_out_flat) if isinstance(e, stage3.ConcatenatedAxis)][0] + + tensors_out = [] + for i in range(len(concat_expr.children)): + # Extract subexpression of i-th child in concatenation + subexpr = stage3.map( + expr_out_flat, lambda expr: expr.children[i].__deepcopy__() if py_id(expr) == py_id(concat_expr) else None, include_children=False + ) + + # Get subtensor + subtensor = self._compose_next(exprs_in, tensors_in, subexpr) + + tensors_out.append(subtensor) + + tensor_out = self.classical.concatenate(tensors_out, axis=concat_index) + else: + _ = next(exprs_in) # next_expr_in + tensor_out = next(tensors_in) + + tensor_out = self.classical.reshape(tensor_out, expr_out.shape) + + return tensor_out + + def _compose(self, exprs_in, tensors_in, exprs_out): + iter_exprs_in = iter(exprs_in) + iter_tensors_in = iter(tensors_in) + tensors_out = [] + for expr_out in exprs_out: + t = self._compose_next(iter_exprs_in, iter_tensors_in, expr_out) + tensors_out.append(t) + + return tensors_out + + +def op(op, classical): + decomposer = Decomposer(classical) + + @use_name_of(op) + def inner(*tensors, out, **kwargs): + if not isinstance(out, list | tuple): + out = [out] + + @decomposer + def inner(tensors, out): + if not isinstance(out, list | tuple): + out = [out] + result = op(*tensors, out=out if len(out) > 1 else out[0], **kwargs) + if len(out) == 1: + result = [result] # Must return a list + return result + + tensors = inner(tensors, out) + if len(out) == 1: + return tensors[0] + else: + return tensors + + return inner + + +def _matchable(expr_in, expr_out): + axes_in = {axis.name for axis in expr_in if isinstance(axis, stage3.Axis) and axis.value != 1} + axes_out = {axis.name for axis in expr_out if isinstance(axis, stage3.Axis) and axis.value != 1} + return axes_in.issubset(axes_out) + + +def _to_ord_str(idx): + if idx == 0: + return "1st" + elif idx == 1: + return "2nd" + elif idx == 2: + return "3rd" + else: + return f"{idx + 1}th" + + +def id(id, classical): + if id is None: + + def id_inner(*xs, out): + return xs if len(xs) > 1 else xs[0] + + else: + id_inner = id + + def id(*tensors, out): + exprs_in = [t.expr for t in tensors] + exprs_out = out if isinstance(out, list | tuple) else [out] + if len(exprs_in) != len(exprs_out): + inputs = "input" if len(exprs_in) == 1 else "inputs" + outputs = "output" if len(exprs_out) == 1 else "outputs" + raise SemanticError( + message=( + f"The number of input and output expressions (after decomposition of axis concatenations) must be the same, " + f"but got {len(exprs_in)} {inputs} and {len(exprs_out)} {outputs}.\n%EXPR%" + ), + ) + for i, (expr_in, expr_out) in enumerate(zip(exprs_in, exprs_out, strict=False)): + if not _matchable(expr_in, expr_out): + raise SemanticError( + message=( + f'The {_to_ord_str(i)} input expression "{expr_in}" is not compatible with the {_to_ord_str(i)} output ' + f'expression "{expr_out}" (after decomposition of axis concatenations).\n%EXPR%' + ), + ) + return id_inner(*tensors, out=out) + + return op(id, classical) + + +def ops(decomposednamedtensor_ops, classical): + ops = {name: (id if name == "id" else globals()["op"])(op, classical) for name, op in decomposednamedtensor_ops.items()} + if "id" not in ops: + ops["id"] = id(None, classical) + return ops diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/__pycache__/classical_from_numpy.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/__pycache__/classical_from_numpy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4d19db036a2f86e63f030150fd9f8ac13a9e288 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/__pycache__/classical_from_numpy.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/__pycache__/einsum_from_numpy.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/__pycache__/einsum_from_numpy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eda138f2dfd80ba0d440ca68394a3ac6e4bac190 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/__pycache__/einsum_from_numpy.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/classical_from_numpy.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/classical_from_numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..d76af0f5d449938d816bef16388b24880692f7b6 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/classical_from_numpy.py @@ -0,0 +1,395 @@ +import numpy as _np +import einx._src.tracer as tracer +import einx._src.adapter as adapter +from einx._src.util.functools import use_name_of +from .._util import _associative_binary_to_nary, _axis_to_axisint, _axis_to_axistuple, _to_tensor +from einx._src.frontend.errors import OperationNotSupportedError + + +def reshape(op, to_tensor=None): + def reshape(x, shape): + shape = tuple(shape) + if tuple(x.shape) == shape: + return x + else: + (x,) = to_tensor(x) + return op(x, shape) + + return reshape + + +def transpose(op, to_tensor): + def transpose(x, perm): + perm = tuple(perm) + if perm == tuple(range(len(perm))): + return x + else: + (x,) = to_tensor(x) + return op(x, perm) + + return transpose + + +def broadcast_to(op, to_tensor): + def broadcast_to(x, shape): + shape = tuple(shape) + if tuple(x.shape) == shape: + return x + else: + (x,) = to_tensor(x) + return op(x, shape) + + return broadcast_to + + +def diagonal(diagonal, transpose, to_tensor, argname_axis1="axis1", argname_axis2="axis2", axis_always_last=False): + if axis_always_last: + diagonal0 = diagonal + + def diagonal(x, axis1, axis2): + # Transpose axis1 and axis2 to the last two axes + axis1, axis2 = sorted([axis1, axis2]) + perm = [i for i in range(x.ndim) if i != axis1 and i != axis2] + [axis1, axis2] + x = transpose(x, perm) + + # Call diagonal (always on the last two axes) + x = diagonal0(x) + + return x + + def inner(x, axes_in, axis_out): + (x,) = to_tensor(x) + + def canon_axis(axis): + if axis < 0: + axis += x.ndim + if axis < 0 or axis >= x.ndim: + raise ValueError(f"Invalid axis {axis} for array of dimension {x.ndim}") + return axis + + axes_in = sorted([canon_axis(axis) for axis in axes_in]) + axis_out = canon_axis(axis_out) + + # Call diagonal for every pair of in-axes, start from highest axes to keep axis indices valid. + while len(axes_in) > 1: + axes_in_now = axes_in[-2:] + kwargs = {argname_axis1: axes_in_now[0], argname_axis2: axes_in_now[1]} + x = diagonal(x, **kwargs) + axes_in = tuple(axes_in[:-2]) + (x.ndim - 1,) + axis_in = axes_in[0] + + # Only one in-axis remains. Move it to the out-axis. + perm = [] + for i in range(x.ndim): + if i == axis_out: + perm.append(axis_in) + elif i == axis_in: + perm.append(axis_out) + else: + perm.append(i) + x = transpose(x, perm) + + return x + + inner.__name__ = "diagonal" + return inner + + +def elementwise(op, to_tensor=None): + @use_name_of(op) + def inner(*xs): + xs = to_tensor(*xs) + return op(*xs) + + return inner + + +def reduce(op, to_tensor, no_none_axis=False, no_axis_tuple=False, scalar_op=None, argname_axis="axis", argname_keepdims="keepdims"): + @use_name_of(op) + def inner(x, *, axis=None, keepdims=None): + (x,) = to_tensor(x) + + kwargs = {} + + if axis is not None: + if isinstance(axis, list | _np.ndarray): + axis = tuple(axis) + if isinstance(axis, tuple) and len(axis) == 1: + axis = axis[0] + kwargs["axis"] = axis + elif no_none_axis: + kwargs["axis"] = tuple(range(x.ndim)) + + if keepdims is not None: + kwargs["keepdims"] = keepdims + + if scalar_op is not None and (x.ndim == 0 or ("axis" in kwargs and kwargs["axis"] == ())): + return scalar_op(x) + + if no_axis_tuple and "axis" in kwargs and isinstance(kwargs["axis"], tuple): + if len(kwargs["axis"]) == 1: + kwargs["axis"] = kwargs["axis"][0] + elif set(kwargs["axis"]) == set(range(x.ndim)): + kwargs["axis"] = None + else: + raise ValueError(f"This backend uses {op.__name__} which allows reduction only over (1) all axes or (2) a single axis.") + + if "axis" in kwargs: + kwargs[argname_axis] = kwargs.pop("axis") + if "keepdims" in kwargs: + kwargs[argname_keepdims] = kwargs.pop("keepdims") + + return op(x, **kwargs) + + return inner + + +def sort(op, to_tensor, argname_axis="axis"): + @use_name_of(op) + def inner(x, axis=None, **kwargs): + (x,) = to_tensor(x) + if axis is None: + if x.ndim == 1: + axis = 0 + else: + raise ValueError("When 'axis' is not specified, 'x' must be a 1D array.") + kwargs = {**kwargs} + kwargs[argname_axis] = _axis_to_axisint(axis) + return op(x, **kwargs) + + return inner + + +def roll(op, to_tensor, argname_axis="axis", argname_shift="shift"): + def roll(x, *, shift, axis=None): + (x,) = to_tensor(x) + if axis is None: + axis = tuple(range(x.ndim)) + axis = _axis_to_axistuple(axis) + shift = _axis_to_axistuple(shift) + if len(shift) != len(axis): + if len(shift) == 1: + shift = shift * len(axis) + else: + raise ValueError(f"When 'shift' has length != 1, it must have the same length as 'axis'. Got lengths {len(shift)} and {len(axis)}.") + + kwargs = {} + kwargs[argname_axis] = axis + kwargs[argname_shift] = shift + return op(x, **kwargs) + + return roll + + +def preserve_shape(op, to_tensor, no_none_axis=False): + @use_name_of(op) + def inner(x, **kwargs): + (x,) = to_tensor(x) + if "axis" in kwargs and isinstance(kwargs["axis"], list | _np.ndarray): + kwargs["axis"] = tuple(kwargs["axis"]) + if no_none_axis and "axis" not in kwargs: + kwargs["axis"] = tuple(range(x.ndim)) + return op(x, **kwargs) + + return inner + + +def matmul(op, to_tensor): + def matmul(x, y): + x, y = to_tensor(x, y) + return op(x, y) + + return matmul + + +def get_at(getitem, take, to_tensor, reshape=None): + def get_at(x, indices, *, axis=None): + if axis is None: + # Multi-dimensional indexing + if not isinstance(indices, tuple): + raise ValueError(f"Expected indices to be a tuple, but got {type(indices)}") + if len(indices) != x.ndim: + raise ValueError(f"Expected indices to have the same number of elements as x.ndim, but got {len(indices)} and {x.ndim}") + x, *indices = to_tensor(x, *indices) + indices = tuple(indices) + indices_shapes = {i.shape for i in indices} + if len(indices_shapes) != 1: + raise ValueError(f"Expected all indices to have the same shape, but got {indices_shapes}") + return getitem(x, indices) + else: + # Single-dimensional indexing + x, indices = to_tensor(x, indices) + if not hasattr(indices, "shape") or indices.ndim == 0: + if axis < 0: + axis += x.ndim + if axis < 0 or axis >= x.ndim: + raise ValueError(f"Invalid axis {axis} for array of dimension {x.ndim}") + return getitem(x, (slice(None),) * axis + (indices,) + (slice(None),) * (x.ndim - axis - 1)) + elif x.ndim == 1 and axis == 0: + if reshape is not None: + shape = indices.shape + indices = reshape(indices, (int(_np.prod(shape)),)) + x = take(x, indices) + if reshape is not None: + x = reshape(x, shape) + return x + else: + raise NotImplementedError("Don't know how to express this operation") + + return get_at + + +def update_at(op, to_tensor, broadcast=None, reshape=None): + @use_name_of(op) + def inner(x, indices, updates): + x, indices, updates = to_tensor(x, indices, updates) + if x.ndim != 1: + raise ValueError(f"Expected 1D array, but got {x.ndim}D") + if indices.ndim != updates.ndim: + raise ValueError(f"Expected indices and updates to have the same number of dimensions, but got {indices.ndim}D and {updates.ndim}D") + + if broadcast is not None: + shape = tuple(int(i) for i in _np.maximum(_np.asarray(indices.shape), _np.asarray(updates.shape))) + indices = broadcast(indices, shape) + updates = broadcast(updates, shape) + + if reshape is not None: + l = int(_np.prod(indices.shape)) + indices = reshape(indices, (l, 1)) + updates = reshape(updates, (l,)) + + return op(x, indices, updates) + + return inner + + +def arange(op, to_dtype=lambda x: x): + def arange(n, dtype="int32"): + if not isinstance(n, int | _np.integer): + raise ValueError(f"Expected an integer for n, but got {type(n)}") + return op(n, dtype=to_dtype(dtype)) + + return arange + + +def split(op, to_tensor, cumulative=True, argname_axis="axis"): + def split(x, indices, axis=0): + (x,) = to_tensor(x) + + if axis < 0: + axis += x.ndim + if axis < 0 or axis >= x.ndim: + raise ValueError(f"Invalid axis {axis} for array of dimension {x.ndim}") + + if not cumulative: + indices = (0,) + tuple(indices) + (x.shape[axis],) + indices = _np.diff(indices) + indices = [int(s) for s in indices] + + kwargs = {} + kwargs[argname_axis] = axis + return op(x, indices, **kwargs) + + return split + + +def concatenate(op, to_tensor, argname_axis="axis"): + def concatenate(xs, axis=0): + xs = to_tensor(*xs) + if axis < 0: + axis += xs[0].ndim + if axis < 0 or axis >= xs[0].ndim: + raise ValueError(f"Invalid axis {axis} for arrays of dimension {xs[0].ndim}") + kwargs = {} + kwargs[argname_axis] = axis + return op(xs, **kwargs) + + return concatenate + + +def dot(dot, to_tensor): + def inner(*tensors): + if len(tensors) != 2: + raise OperationNotSupportedError("dot operation with this backend does not support more than two argument tensors.") + x, y = to_tensor(*tensors) + if x.ndim != 1 or y.ndim != 1: + raise OperationNotSupportedError(f"dot operation with this backend only supports a single contraction axis, but found {x.ndim} contraction axes") + if x.shape != y.shape: + raise ValueError(f"Expected x and y to have the same shape, but got {x.shape} and {y.shape}") + return dot(x, y) + + inner.__name__ = "dot" + return inner + + +class ops: + def __init__(self, np): + def to_tensor_forward_all(*args): + to_tensor_one = _to_tensor(np.asarray, forward=["numpy", "scalar"], convert=[]) + return [to_tensor_one(arg) for arg in args] + + self.reshape = adapter.classical_from_numpy.reshape(np.reshape, to_tensor=to_tensor_forward_all) + self.transpose = adapter.classical_from_numpy.transpose(np.transpose, to_tensor=to_tensor_forward_all) + self.broadcast_to = adapter.classical_from_numpy.broadcast_to(np.broadcast_to, to_tensor=to_tensor_forward_all) + self.diagonal = adapter.classical_from_numpy.diagonal(np.diagonal, self.transpose, to_tensor=to_tensor_forward_all) + self.stop_gradient = lambda x: x + + self.add = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(np.add), to_tensor=to_tensor_forward_all) + self.subtract = adapter.classical_from_numpy.elementwise(np.subtract, to_tensor=to_tensor_forward_all) + self.multiply = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(np.multiply), to_tensor=to_tensor_forward_all) + self.true_divide = adapter.classical_from_numpy.elementwise(np.true_divide, to_tensor=to_tensor_forward_all) + self.floor_divide = adapter.classical_from_numpy.elementwise(np.floor_divide, to_tensor=to_tensor_forward_all) + self.divide = adapter.classical_from_numpy.elementwise(np.divide, to_tensor=to_tensor_forward_all) + self.logaddexp = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(np.logaddexp), to_tensor=to_tensor_forward_all) + self.logical_and = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(np.logical_and), to_tensor=to_tensor_forward_all) + self.logical_or = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(np.logical_or), to_tensor=to_tensor_forward_all) + self.where = adapter.classical_from_numpy.elementwise(np.where, to_tensor=to_tensor_forward_all) + self.maximum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(np.maximum), to_tensor=to_tensor_forward_all) + self.minimum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(np.minimum), to_tensor=to_tensor_forward_all) + self.less = adapter.classical_from_numpy.elementwise(np.less, to_tensor=to_tensor_forward_all) + self.less_equal = adapter.classical_from_numpy.elementwise(np.less_equal, to_tensor=to_tensor_forward_all) + self.greater = adapter.classical_from_numpy.elementwise(np.greater, to_tensor=to_tensor_forward_all) + self.greater_equal = adapter.classical_from_numpy.elementwise(np.greater_equal, to_tensor=to_tensor_forward_all) + self.equal = adapter.classical_from_numpy.elementwise(np.equal, to_tensor=to_tensor_forward_all) + self.not_equal = adapter.classical_from_numpy.elementwise(np.not_equal, to_tensor=to_tensor_forward_all) + self.exp = adapter.classical_from_numpy.elementwise(np.exp, to_tensor=to_tensor_forward_all) + self.log = adapter.classical_from_numpy.elementwise(np.log, to_tensor=to_tensor_forward_all) + self.negative = adapter.classical_from_numpy.elementwise(np.negative, to_tensor=to_tensor_forward_all) + self.divmod = adapter.classical_from_numpy.elementwise(np.divmod, to_tensor=to_tensor_forward_all) + + self.sum = adapter.classical_from_numpy.reduce(np.sum, to_tensor=to_tensor_forward_all) + self.mean = adapter.classical_from_numpy.reduce(np.mean, to_tensor=to_tensor_forward_all) + self.var = adapter.classical_from_numpy.reduce(np.var, to_tensor=to_tensor_forward_all) + self.std = adapter.classical_from_numpy.reduce(np.std, to_tensor=to_tensor_forward_all) + self.prod = adapter.classical_from_numpy.reduce(np.prod, to_tensor=to_tensor_forward_all) + self.count_nonzero = adapter.classical_from_numpy.reduce(np.count_nonzero, to_tensor=to_tensor_forward_all) + self.any = adapter.classical_from_numpy.reduce(np.any, to_tensor=to_tensor_forward_all) + self.all = adapter.classical_from_numpy.reduce(np.all, to_tensor=to_tensor_forward_all) + self.max = adapter.classical_from_numpy.reduce(np.max, to_tensor=to_tensor_forward_all) + self.min = adapter.classical_from_numpy.reduce(np.min, to_tensor=to_tensor_forward_all) + self.logsumexp = adapter.classical_from_classical.logsumexp(self) + self.argmax = adapter.classical_from_numpy.reduce(np.argmax, to_tensor=to_tensor_forward_all) + self.argmin = adapter.classical_from_numpy.reduce(np.argmin, to_tensor=to_tensor_forward_all) + + self.sort = adapter.classical_from_numpy.sort(np.sort, to_tensor=to_tensor_forward_all) + self.argsort = adapter.classical_from_numpy.sort(np.argsort, to_tensor=to_tensor_forward_all) + self.roll = adapter.classical_from_numpy.roll(np.roll, to_tensor=to_tensor_forward_all) + self.flip = adapter.classical_from_numpy.preserve_shape(np.flip, to_tensor=to_tensor_forward_all) + self.softmax = adapter.classical_from_classical.softmax(self) + self.log_softmax = adapter.classical_from_classical.log_softmax(self) + + def to_tensor_index(x, *args): + x = _to_tensor(np.asarray, forward=["numpy"], convert=["scalar"])(x) + args = [_to_tensor(np.asarray, forward=["numpy", "scalar"], convert=[])(a) for a in args] + return x, *args + + self.get_at = adapter.classical_from_numpy.get_at(np.ndarray.__getitem__, np.take, to_tensor=to_tensor_index) + self.set_at = adapter.classical_from_numpy.update_at(np.put, to_tensor=to_tensor_index) + self.add_at = adapter.classical_from_numpy.update_at(np.add.at, to_tensor=to_tensor_index, broadcast=self.broadcast_to) + self.subtract_at = adapter.classical_from_numpy.update_at(np.subtract.at, to_tensor=to_tensor_index, broadcast=self.broadcast_to) + + self.arange = adapter.classical_from_numpy.arange(np.arange) + self.split = adapter.classical_from_numpy.split(np.split, to_tensor=to_tensor_forward_all) + self.concatenate = adapter.classical_from_numpy.concatenate(np.concatenate, to_tensor=to_tensor_forward_all) + self.dot = adapter.classical_from_numpy.dot(np.dot, to_tensor=to_tensor_forward_all) + self.matmul = adapter.classical_from_numpy.matmul(np.matmul, to_tensor=to_tensor_forward_all) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/einsum_from_numpy.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/einsum_from_numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..1f8afee0bdf59c466fd7825f4c2945870b38f20c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/numpy/einsum_from_numpy.py @@ -0,0 +1,64 @@ +from .._util import _to_tensor + + +class _detachscalars: + def __init__(self, einsum, multiply): + self._einsum = einsum + self._multiply = multiply + + def __call__(self, equation, *operands): + exprs = equation.split("->") + if len(exprs) != 2: + raise ValueError("Invalid einsum equation") + in_exprs = exprs[0].split(",") + out_expr = exprs[1] + + # Remove scalars + scalars = [] + for in_expr, operand in zip(in_exprs, operands, strict=False): + if (len(in_expr) == 0) != (operand.shape == ()): + raise ValueError(f"Tensor and einsum expression do not match: {in_expr} and {operand.shape}") + if operand.shape == (): + scalars.append(operand) + operands = [operand for operand in operands if operand.shape != ()] + in_exprs = [in_expr for in_expr in in_exprs if len(in_expr) > 0] + assert len(in_exprs) == len(operands) + equation = ",".join(in_exprs) + "->" + out_expr + + # Call without scalars + if len(operands) == 1: + if in_exprs[0] != out_expr: + output = self._einsum(equation, *operands) + else: + output = operands[0] + elif len(operands) > 1: + output = self._einsum(equation, *operands) + else: + output = None + + # Multiply scalars + if len(scalars) > 0: + if output is None: + output = self._multiply(*scalars) + else: + output = self._multiply(output, *scalars) + + return output + + +def einsum_from_numpy(op=None, to_tensor=None, multiply=None): + if to_tensor is None: + np = op + op = np.einsum + + def to_tensor(*args): + to_tensor_one = _to_tensor(np.asarray, forward=["numpy", "scalar"], convert=[]) + return [to_tensor_one(arg) for arg in args] + + def einsum(subscripts, *operands): + operands = to_tensor(*operands) + return op(subscripts, *operands) + + if multiply is not None: + einsum = _detachscalars(einsum, multiply) + return einsum diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/ops.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..b40669a07a230b8246289808690ec0050b8a4caa --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/ops.py @@ -0,0 +1,33 @@ +elementwise = [ + "add", + "subtract", + "multiply", + "true_divide", + "floor_divide", + "divide", + "logical_and", + "logical_or", + "where", + "maximum", + "minimum", + "less", + "less_equal", + "greater", + "greater_equal", + "equal", + "not_equal", + "logaddexp", + "exp", + "log", + "negative", +] + +reduce = ["sum", "mean", "var", "std", "prod", "count_nonzero", "all", "any", "min", "max", "logsumexp"] + +update_at = ["set_at", "add_at", "subtract_at"] + +preserve_shape = ["flip", "roll", "sort", "argsort", "softmax", "log_softmax"] + +argfind = ["argmax", "argmin"] + +all = ["id", "dot", "get_at"] + elementwise + reduce + update_at + preserve_shape + argfind diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/__pycache__/classical_from_tensorflow.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/__pycache__/classical_from_tensorflow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..897e9ee47deab89645b05f9337e643ee4fde623a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/__pycache__/classical_from_tensorflow.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/__pycache__/einsum_from_tensorflow.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/__pycache__/einsum_from_tensorflow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56848a0273f20d74eca526d78819ff4b51e3b5c9 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/__pycache__/einsum_from_tensorflow.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/classical_from_tensorflow.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/classical_from_tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..3e4648fdceb5c23cb95eb980a7d0f5a10fc6e740 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/classical_from_tensorflow.py @@ -0,0 +1,111 @@ +import einx._src.adapter as adapter +import numpy as np +from functools import partial +from einx._src.util.functools import use_name_of +from .._util import _associative_binary_to_nary, _to_tensor +import einx._src.tracer as tracer + + +class ops: + def __init__(self, tf): + def to_tensor_all(*args): + to_tensor_one = _to_tensor(tf.convert_to_tensor, forward=[tf.Tensor], convert=["scalar", "numpy"]) + return [to_tensor_one(arg) for arg in args] + + def dtype(x): + if isinstance(x, tracer.signature.classical.Tensor): + return tracer.signature.python.getattr(x, "dtype") + elif isinstance(tf.Tensor, type) and isinstance(x, tf.Tensor): + return x.dtype + elif isinstance(x, int | float | bool | np.integer | np.floating | np.bool_): + return tf.as_dtype(type(x)) + elif isinstance(x, tracer.signature.classical.ConvertibleTensor) and issubclass( + x.concrete.type, int | float | bool | np.integer | np.floating | np.bool_ + ): + return tf.as_dtype(x.concrete.type) + elif isinstance(x, np.ndarray): + return tf.as_dtype(x.dtype) + elif isinstance(x, tracer.signature.classical.ConvertibleTensor) and issubclass(x.concrete.type, np.ndarray): + return tf.as_dtype(x.concrete.type.dtype) + else: + raise ValueError(f"Cannot determine dtype of {type(x)}.") + + self.dtype = dtype + self.tensor = tf.Tensor + + self.reshape = adapter.classical_from_numpy.reshape(tf.reshape, to_tensor=to_tensor_all) + self.transpose = adapter.classical_from_numpy.transpose(tf.transpose, to_tensor=to_tensor_all) + self.broadcast_to = adapter.classical_from_numpy.broadcast_to(tf.broadcast_to, to_tensor=to_tensor_all) + self.diagonal = adapter.classical_from_numpy.diagonal(tf.linalg.diag_part, self.transpose, to_tensor=to_tensor_all, axis_always_last=True) + self.stop_gradient = tf.stop_gradient + + def to_tensor_elementwise(*args): + to_tensor_one = _to_tensor(tf.convert_to_tensor, forward=[tf.Tensor, "scalar"], convert=["numpy"]) + return [to_tensor_one(arg) for arg in args] + + self.add = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tf.math.add), to_tensor=to_tensor_elementwise) + self.subtract = adapter.classical_from_numpy.elementwise(tf.math.subtract, to_tensor=to_tensor_elementwise) + self.multiply = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tf.math.multiply), to_tensor=to_tensor_elementwise) + self.true_divide = adapter.classical_from_numpy.elementwise(tf.math.truediv, to_tensor=to_tensor_elementwise) + self.floor_divide = adapter.classical_from_numpy.elementwise(tf.math.floordiv, to_tensor=to_tensor_elementwise) + self.divide = adapter.classical_from_numpy.elementwise(tf.math.divide, to_tensor=to_tensor_elementwise) + self.logaddexp = adapter.classical_from_classical.logaddexp(self) + self.logical_and = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tf.math.logical_and), to_tensor=to_tensor_elementwise) + self.logical_or = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tf.math.logical_or), to_tensor=to_tensor_elementwise) + self.where = adapter.classical_from_numpy.elementwise(tf.where, to_tensor=to_tensor_elementwise) + self.maximum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tf.math.maximum), to_tensor=to_tensor_elementwise) + self.minimum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tf.math.minimum), to_tensor=to_tensor_elementwise) + self.less = adapter.classical_from_numpy.elementwise(tf.math.less, to_tensor=to_tensor_elementwise) + self.less_equal = adapter.classical_from_numpy.elementwise(tf.math.less_equal, to_tensor=to_tensor_elementwise) + self.greater = adapter.classical_from_numpy.elementwise(tf.math.greater, to_tensor=to_tensor_elementwise) + self.greater_equal = adapter.classical_from_numpy.elementwise(tf.math.greater_equal, to_tensor=to_tensor_elementwise) + self.equal = adapter.classical_from_numpy.elementwise(tf.math.equal, to_tensor=to_tensor_elementwise) + self.not_equal = adapter.classical_from_numpy.elementwise(tf.math.not_equal, to_tensor=to_tensor_elementwise) + self.exp = adapter.classical_from_numpy.elementwise(tf.math.exp, to_tensor=to_tensor_elementwise) + self.log = adapter.classical_from_numpy.elementwise(tf.math.log, to_tensor=to_tensor_elementwise) + self.negative = adapter.classical_from_numpy.elementwise(tf.math.negative, to_tensor=to_tensor_elementwise) + self.divmod = adapter.classical_from_numpy.elementwise(lambda x, y: (tf.math.floordiv(x, y), tf.math.floormod(x, y)), to_tensor=to_tensor_elementwise) + + self.sum = adapter.classical_from_numpy.reduce(tf.math.reduce_sum, to_tensor=to_tensor_all) + self.mean = adapter.classical_from_numpy.reduce(tf.math.reduce_mean, to_tensor=to_tensor_all) + self.var = adapter.classical_from_numpy.reduce(tf.math.reduce_variance, to_tensor=to_tensor_all) + self.std = adapter.classical_from_numpy.reduce(tf.math.reduce_std, to_tensor=to_tensor_all) + self.prod = adapter.classical_from_numpy.reduce(tf.math.reduce_prod, to_tensor=to_tensor_all) + self.count_nonzero = adapter.classical_from_numpy.reduce(tf.math.count_nonzero, to_tensor=to_tensor_all) + self.any = adapter.classical_from_numpy.reduce(tf.math.reduce_any, to_tensor=to_tensor_all) + self.all = adapter.classical_from_numpy.reduce(tf.math.reduce_all, to_tensor=to_tensor_all) + self.max = adapter.classical_from_numpy.reduce(tf.math.reduce_max, to_tensor=to_tensor_all) + self.min = adapter.classical_from_numpy.reduce(tf.math.reduce_min, to_tensor=to_tensor_all) + self.logsumexp = adapter.classical_from_numpy.reduce(tf.math.reduce_logsumexp, to_tensor=to_tensor_all) + self.argmax = adapter.classical_from_numpy.reduce(tf.math.argmax, to_tensor=to_tensor_all) + self.argmin = adapter.classical_from_numpy.reduce(tf.math.argmin, to_tensor=to_tensor_all) + + self.sort = adapter.classical_from_numpy.sort(tf.sort, to_tensor=to_tensor_all) + self.argsort = adapter.classical_from_numpy.sort(tf.argsort, to_tensor=to_tensor_all) + self.roll = adapter.classical_from_numpy.roll(tf.roll, to_tensor=to_tensor_all) + self.flip = adapter.classical_from_numpy.preserve_shape(tf.reverse, to_tensor=to_tensor_all) + self.softmax = adapter.classical_from_classical.softmax(self) + self.log_softmax = adapter.classical_from_classical.log_softmax(self) + + def to_tensor_index(x, y, *args): + x = _to_tensor(tf.convert_to_tensor, forward=[], convert=["numpy", "scalar"])(x) + y = _to_tensor(tf.convert_to_tensor, forward=["scalar"], convert=["numpy"])(y) + args = [_to_tensor(tf.convert_to_tensor, forward=[], convert=["numpy", "scalar"])(a) for a in args] + return x, y, *args + + self.get_at = adapter.classical_from_numpy.get_at(tf.Tensor.__getitem__, tf.gather, to_tensor=to_tensor_index) + self.set_at = adapter.classical_from_numpy.update_at( + tf.tensor_scatter_nd_update, to_tensor=to_tensor_all, broadcast=self.broadcast_to, reshape=self.reshape + ) + self.add_at = adapter.classical_from_numpy.update_at( + tf.tensor_scatter_nd_add, to_tensor=to_tensor_all, broadcast=self.broadcast_to, reshape=self.reshape + ) + self.subtract_at = adapter.classical_from_numpy.update_at( + tf.tensor_scatter_nd_sub, to_tensor=to_tensor_all, broadcast=self.broadcast_to, reshape=self.reshape + ) + + self.arange = adapter.classical_from_numpy.arange(tf.range) + self.split = adapter.classical_from_numpy.split(tf.split, to_tensor=to_tensor_all, cumulative=False) + self.concatenate = adapter.classical_from_numpy.concatenate(tf.concat, to_tensor=to_tensor_all) + self.dot = adapter.classical_from_mlx.dot(tf.tensordot, to_tensor=to_tensor_all) + self.matmul = adapter.classical_from_numpy.matmul(tf.matmul, to_tensor=to_tensor_all) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/einsum_from_tensorflow.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/einsum_from_tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..22f33e6c8c61009da1146cd5aabed6e656235746 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tensorflow/einsum_from_tensorflow.py @@ -0,0 +1,10 @@ +import einx._src.adapter as adapter +from .._util import _to_tensor + + +def einsum_from_tensorflow(tf): + def to_tensor(*args): + to_tensor_one = _to_tensor(tf.convert_to_tensor, forward=[tf.Tensor], convert=["numpy", "scalar"]) + return [to_tensor_one(arg) for arg in args] + + return adapter.einsum_from_numpy(tf.einsum, to_tensor=to_tensor) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/__pycache__/classical_from_tinygrad.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/__pycache__/classical_from_tinygrad.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cf4735a05ccd90aed4545af43b2c78381f97ee6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/__pycache__/classical_from_tinygrad.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/__pycache__/einsum_from_tinygrad.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/__pycache__/einsum_from_tinygrad.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15969eb8fadb479ad66dd1903cb80ed3d4316e90 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/__pycache__/einsum_from_tinygrad.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/classical_from_tinygrad.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/classical_from_tinygrad.py new file mode 100644 index 0000000000000000000000000000000000000000..360f2bb1e514497a5894b39882e9daa56b6c414d --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/classical_from_tinygrad.py @@ -0,0 +1,149 @@ +import einx._src.adapter as adapter +import einx._src.tracer as tracer +import numpy as np +from functools import partial +from einx._src.util.functools import use_name_of +from .._util import _associative_binary_to_nary, _to_tensor, _unsupported_op + + +class ops: + def __init__(self, tinygrad): + def to_tensor_all(*args): + to_tensor_one = _to_tensor(tinygrad.Tensor, forward=[tinygrad.Tensor], convert=["numpy", "scalar"]) + return [to_tensor_one(arg) for arg in args] + + self.reshape = adapter.classical_from_numpy.reshape(tinygrad.Tensor.reshape, to_tensor=to_tensor_all) + self.transpose = adapter.classical_from_numpy.transpose(tinygrad.Tensor.permute, to_tensor=to_tensor_all) + self.broadcast_to = adapter.classical_from_numpy.broadcast_to(tinygrad.Tensor.expand, to_tensor=to_tensor_all) + self.diagonal = _unsupported_op("diagonal", "tinygrad") + self.stop_gradient = tinygrad.Tensor.detach + + self.add = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tinygrad.Tensor.add), to_tensor=to_tensor_all) + self.subtract = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.sub, to_tensor=to_tensor_all) + self.multiply = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tinygrad.Tensor.mul), to_tensor=to_tensor_all) + self.true_divide = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.div, to_tensor=to_tensor_all) + self.floor_divide = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.idiv, to_tensor=to_tensor_all) + self.divide = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.div, to_tensor=to_tensor_all) + self.logaddexp = adapter.classical_from_classical.logaddexp( + self + ) # adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tinygrad.Tensor.logaddexp), to_tensor=to_tensor_all) + self.logical_and = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tinygrad.Tensor.mul), to_tensor=to_tensor_all) + self.logical_or = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tinygrad.Tensor.add), to_tensor=to_tensor_all) + self.where = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.where, to_tensor=to_tensor_all) + self.maximum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tinygrad.Tensor.maximum), to_tensor=to_tensor_all) + self.minimum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(tinygrad.Tensor.minimum), to_tensor=to_tensor_all) + self.less = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.__lt__, to_tensor=to_tensor_all) + self.less_equal = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.__le__, to_tensor=to_tensor_all) + self.greater = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.__gt__, to_tensor=to_tensor_all) + self.greater_equal = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.__ge__, to_tensor=to_tensor_all) + self.equal = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.__eq__, to_tensor=to_tensor_all) + self.not_equal = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.__ne__, to_tensor=to_tensor_all) + self.exp = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.exp, to_tensor=to_tensor_all) + self.log = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.log, to_tensor=to_tensor_all) + self.negative = adapter.classical_from_numpy.elementwise(tinygrad.Tensor.neg, to_tensor=to_tensor_all) + + def divmod(x, y): + q = tinygrad.Tensor.idiv(x, y) + r = tinygrad.Tensor.sub(x, tinygrad.Tensor.mul(q, y)) + return q, r + + self.divmod = adapter.classical_from_numpy.elementwise(divmod, to_tensor=to_tensor_all) + + self.sum = adapter.classical_from_numpy.reduce(tinygrad.Tensor.sum, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.mean = adapter.classical_from_numpy.reduce(tinygrad.Tensor.mean, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.var = adapter.classical_from_numpy.reduce(tinygrad.Tensor.var, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.std = adapter.classical_from_numpy.reduce(tinygrad.Tensor.std, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.prod = adapter.classical_from_numpy.reduce(tinygrad.Tensor.prod, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.count_nonzero = adapter.classical_from_numpy.reduce(tinygrad.Tensor.sum, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.any = adapter.classical_from_numpy.reduce(tinygrad.Tensor.any, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.all = adapter.classical_from_numpy.reduce(tinygrad.Tensor.all, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.max = adapter.classical_from_numpy.reduce(tinygrad.Tensor.max, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.min = adapter.classical_from_numpy.reduce(tinygrad.Tensor.min, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.logsumexp = adapter.classical_from_classical.logsumexp( + self + ) # adapter.classical_from_numpy.reduce(tinygrad.Tensor.logsumexp, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.argmax = adapter.classical_from_numpy.reduce(tinygrad.Tensor.argmax, to_tensor=to_tensor_all, argname_keepdims="keepdim") + self.argmin = adapter.classical_from_numpy.reduce(tinygrad.Tensor.argmin, to_tensor=to_tensor_all, argname_keepdims="keepdim") + + self.sort = adapter.classical_from_numpy.sort(lambda x, **kwargs: tinygrad.Tensor.sort(x, **kwargs)[0], to_tensor=to_tensor_all, argname_axis="dim") + self.argsort = adapter.classical_from_numpy.sort(lambda x, **kwargs: tinygrad.Tensor.sort(x, **kwargs)[1], to_tensor=to_tensor_all, argname_axis="dim") + self.roll = adapter.classical_from_numpy.roll(tinygrad.Tensor.roll, to_tensor=to_tensor_all, argname_axis="dims", argname_shift="shifts") + self.flip = adapter.classical_from_numpy.preserve_shape(tinygrad.Tensor.flip, to_tensor=to_tensor_all) + self.softmax = adapter.classical_from_numpy.preserve_shape(tinygrad.Tensor.softmax, to_tensor=to_tensor_all) + self.log_softmax = adapter.classical_from_numpy.preserve_shape(tinygrad.Tensor.log_softmax, to_tensor=to_tensor_all) + + def to_tensor_index(x, *args): + x = _to_tensor(tinygrad.Tensor, forward=[tinygrad.Tensor], convert=["numpy", "scalar"])(x) + args = [_to_tensor(tinygrad.Tensor, forward=[tinygrad.Tensor, "scalar"], convert=["numpy"])(a) for a in args] + return x, *args + + self.get_at = adapter.classical_from_numpy.get_at(tinygrad.Tensor.__getitem__, tinygrad.Tensor.gather, to_tensor=to_tensor_index, reshape=self.reshape) + + def update_at(x, indices, updates, op): + if op == "set": + op = tinygrad.Tensor.scatter + elif op == "add": + op = partial(tinygrad.Tensor.scatter_reduce, reduce="sum") + elif op == "subtract": + op = partial(tinygrad.Tensor.scatter_reduce, reduce="sum") + updates = self.negative(updates) + else: + raise ValueError(f"Unsupported op: {op}") + assert x.ndim == 1 + assert indices.ndim == 2 + assert indices.shape[1] == 1 + assert updates.ndim == 1 + indices = self.reshape(indices, (indices.shape[0],)) + x = op(x, 0, indices, updates) + return x + + self.set_at = adapter.classical_from_numpy.update_at( + partial(update_at, op="set"), to_tensor=to_tensor_index, broadcast=self.broadcast_to, reshape=self.reshape + ) + self.add_at = adapter.classical_from_numpy.update_at( + partial(update_at, op="add"), to_tensor=to_tensor_index, broadcast=self.broadcast_to, reshape=self.reshape + ) + self.subtract_at = adapter.classical_from_numpy.update_at( + partial(update_at, op="subtract"), to_tensor=to_tensor_index, broadcast=self.broadcast_to, reshape=self.reshape + ) + + self.arange = adapter.classical_from_numpy.arange(tinygrad.Tensor.arange) + self.split = adapter.classical_from_numpy.split(tinygrad.Tensor.split, to_tensor=to_tensor_all, cumulative=False, argname_axis="dim") + self.concatenate = adapter.classical_from_numpy.concatenate(tinygrad.Tensor.cat, to_tensor=to_tensor_all, argname_axis="dim") + self.dot = adapter.classical_from_numpy.dot(tinygrad.Tensor.dot, to_tensor=to_tensor_all) + + def matmul(x, y): + # 1. Shapes here: + # x: (..., i, j) + # y: (..., j, k) + + # Swap contracted axis in y to last axis + perm = list(range(y.ndim)) + perm[-2], perm[-1] = perm[-1], perm[-2] + y = self.transpose(y, perm) + + # 2. Shapes here: + # x: (..., i, j) + # y: (..., k, j) + + # Insert unitary dimensions + x = self.reshape(x, x.shape[:-2] + (x.shape[-2], 1, x.shape[-1])) + y = self.reshape(y, y.shape[:-2] + (1, y.shape[-2], y.shape[-1])) + + # 3. Shapes here: + # x: (..., i, 1, j) + # y: (..., 1, k, j) + + z = self.multiply(x, y) + + # 4. Shapes here: + # z: (..., i, k, j) + + z = self.sum(z, axis=-1) + + # 5. Shapes here: + # z: (..., i, k) + + return z + + self.matmul = adapter.classical_from_numpy.matmul(matmul, to_tensor=to_tensor_all) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/einsum_from_tinygrad.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/einsum_from_tinygrad.py new file mode 100644 index 0000000000000000000000000000000000000000..a20f7dfbe07a58dfb9a8857a94ec0e42357aec8f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/tinygrad/einsum_from_tinygrad.py @@ -0,0 +1,10 @@ +import einx._src.adapter as adapter +from .._util import _to_tensor + + +def einsum_from_tinygrad(tinygrad): + def to_tensor(*args): + to_tensor_one = _to_tensor(tinygrad.Tensor, forward=[tinygrad.Tensor], convert=["numpy", "scalar"]) + return [to_tensor_one(arg) for arg in args] + + return adapter.einsum_from_numpy(tinygrad.Tensor.einsum, to_tensor=to_tensor, multiply=adapter.classical_from_tinygrad.ops(tinygrad).multiply) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/classical_from_torch.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/classical_from_torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9960e989ce6501b96838b4897d25e2b25d64bf1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/classical_from_torch.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/devicestack.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/devicestack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7927b7fc813b06d96750a1b1f399c4ab3406b598 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/devicestack.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/einsum_from_torch.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/einsum_from_torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..310015636b3114ec352e52c4e96c8a6e3c5ce289 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/einsum_from_torch.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/vmap_from_torch.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/vmap_from_torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22a7f57df54aa0210cb9183a4806df47a055a942 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/__pycache__/vmap_from_torch.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/classical_from_torch.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/classical_from_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..8304f55eb920aa46c2cc1842ed41a22f2cb049f1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/classical_from_torch.py @@ -0,0 +1,165 @@ +import numpy as np +from .._util import _associative_binary_to_nary +from .._util import _axis_to_axistuple +from .._util import _to_tensor, _has_type +from einx._src.util.functools import use_name_of +import einx._src.adapter as adapter +import einx._src.tracer as tracer + + +def reduce(op, to_tensor, no_none_axis=False, no_axis_tuple=False, scalar_op=None): + @use_name_of(op) + def inner(x, **kwargs): + if "axis" in kwargs: + kwargs["dim"] = kwargs.pop("axis") + if "keepdims" in kwargs: + kwargs["keepdim"] = kwargs.pop("keepdims") + return op(x, **kwargs) + + return adapter.classical_from_numpy.reduce(inner, to_tensor=to_tensor, no_none_axis=no_none_axis, no_axis_tuple=no_axis_tuple, scalar_op=scalar_op) + + +def sort(op, to_tensor): + return adapter.classical_from_numpy.sort(lambda x, *, axis=None, **kwargs: op(x, dim=axis, **kwargs), to_tensor=to_tensor) + + +def softmax(torch_op, my_op, to_tensor): + @use_name_of(torch_op) + def inner(x, *, axis=None): + (x,) = to_tensor(x) + if axis is None: + axis = tuple(range(x.ndim)) + axis = _axis_to_axistuple(axis) + if len(axis) == 0: + return x + elif len(axis) == 1: + # Use torch's softmax directly for single axis + return torch_op(x, dim=axis[0]) + else: + # Use custom implementation for multiple axes + return my_op(x, axis=axis) + + return inner + + +class ops: + def __init__(self, torch, get_device): + asarray_with_device = lambda x: torch.asarray(x, device=get_device()) + + def to_tensor_all(*args): + to_tensor_one = _to_tensor(asarray_with_device, forward=[torch.Tensor], convert=["numpy", "scalar"]) + return [to_tensor_one(arg) for arg in args] + + def to_tensor_all_notallscalar(*args): + if all(_has_type(arg, ["scalar"]) for arg in args): + args = list(args) + args[0] = _to_tensor(asarray_with_device, forward=[torch.Tensor], convert=["scalar"])(args[0]) + else: + args = [_to_tensor(asarray_with_device, forward=[torch.Tensor, "scalar"], convert=["numpy"])(arg) for arg in args] + + return tuple(args) + + def _to_dtype(x): + if isinstance(x, str): + return getattr(torch, x) + else: + return x + + self.reshape = adapter.classical_from_numpy.reshape(torch.reshape, to_tensor=to_tensor_all) + self.transpose = adapter.classical_from_numpy.transpose(torch.permute, to_tensor=to_tensor_all) + self.broadcast_to = adapter.classical_from_numpy.broadcast_to(torch.broadcast_to, to_tensor=to_tensor_all) + self.diagonal = adapter.classical_from_numpy.diagonal( + torch.diagonal, self.transpose, to_tensor=to_tensor_all, argname_axis1="dim1", argname_axis2="dim2" + ) + self.stop_gradient = torch.Tensor.detach + + self.add = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(torch.add), to_tensor=to_tensor_all_notallscalar) + self.subtract = adapter.classical_from_numpy.elementwise(torch.subtract, to_tensor=to_tensor_all_notallscalar) + self.multiply = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(torch.multiply), to_tensor=to_tensor_all_notallscalar) + self.true_divide = adapter.classical_from_numpy.elementwise(torch.true_divide, to_tensor=to_tensor_all_notallscalar) + self.floor_divide = adapter.classical_from_numpy.elementwise(torch.floor_divide, to_tensor=to_tensor_all_notallscalar) + self.divide = adapter.classical_from_numpy.elementwise(torch.divide, to_tensor=to_tensor_all_notallscalar) + + self.logaddexp = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(torch.logaddexp), to_tensor=to_tensor_all) + self.logical_and = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(torch.logical_and), to_tensor=to_tensor_all) + self.logical_or = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(torch.logical_or), to_tensor=to_tensor_all) + + def to_tensor_where(x, *args): + x = _to_tensor(asarray_with_device, forward=[torch.Tensor], convert=["numpy", "scalar"])(x) + args = [_to_tensor(asarray_with_device, forward=[torch.Tensor, "scalar"], convert=["numpy"])(a) for a in args] + return (x, *args) + + self.where = adapter.classical_from_numpy.elementwise(torch.where, to_tensor=to_tensor_where) + + self.maximum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(torch.maximum), to_tensor=to_tensor_all) + self.minimum = adapter.classical_from_numpy.elementwise(_associative_binary_to_nary(torch.minimum), to_tensor=to_tensor_all) + + def to_tensor_compare(x, y): + x = _to_tensor(asarray_with_device, forward=[torch.Tensor], convert=["numpy", "scalar"])(x) + y = _to_tensor(asarray_with_device, forward=[torch.Tensor, "scalar"], convert=["numpy"])(y) + return (x, y) + + self.less = adapter.classical_from_numpy.elementwise(torch.less, to_tensor=to_tensor_compare) + self.less_equal = adapter.classical_from_numpy.elementwise(torch.less_equal, to_tensor=to_tensor_compare) + self.greater = adapter.classical_from_numpy.elementwise(torch.greater, to_tensor=to_tensor_compare) + self.greater_equal = adapter.classical_from_numpy.elementwise(torch.greater_equal, to_tensor=to_tensor_compare) + self.equal = adapter.classical_from_numpy.elementwise(torch.eq, to_tensor=to_tensor_compare) + self.not_equal = adapter.classical_from_numpy.elementwise(torch.ne, to_tensor=to_tensor_compare) + + self.exp = adapter.classical_from_numpy.elementwise(torch.exp, to_tensor=to_tensor_all) + self.log = adapter.classical_from_numpy.elementwise(torch.log, to_tensor=to_tensor_all) + self.negative = adapter.classical_from_numpy.elementwise(torch.neg, to_tensor=to_tensor_all) + + self.divmod = adapter.classical_from_numpy.elementwise( + lambda x, y: (torch.floor_divide(x, y), torch.remainder(x, y)), to_tensor=to_tensor_all_notallscalar + ) + + self.sum = adapter.classical_from_torch.reduce(torch.sum, to_tensor=to_tensor_all, scalar_op=lambda x: x) + self.mean = adapter.classical_from_torch.reduce(torch.mean, to_tensor=to_tensor_all, scalar_op=lambda x: x) + self.var = adapter.classical_from_torch.reduce(torch.var, to_tensor=to_tensor_all, scalar_op=lambda x: x) + self.std = adapter.classical_from_torch.reduce(torch.std, to_tensor=to_tensor_all, scalar_op=lambda x: x) + self.prod = adapter.classical_from_torch.reduce(torch.prod, to_tensor=to_tensor_all, no_axis_tuple=True, scalar_op=lambda x: x) + self.count_nonzero = adapter.classical_from_torch.reduce(torch.count_nonzero, to_tensor=to_tensor_all) + self.any = adapter.classical_from_torch.reduce(torch.any, to_tensor=to_tensor_all, scalar_op=lambda x: x) + self.all = adapter.classical_from_torch.reduce(torch.all, to_tensor=to_tensor_all, scalar_op=lambda x: x) + self.max = adapter.classical_from_torch.reduce(torch.amax, to_tensor=to_tensor_all, scalar_op=lambda x: x) + self.min = adapter.classical_from_torch.reduce(torch.amin, to_tensor=to_tensor_all, scalar_op=lambda x: x) + self.logsumexp = adapter.classical_from_torch.reduce(torch.logsumexp, to_tensor=to_tensor_all, no_none_axis=True) + self.argmax = adapter.classical_from_torch.reduce(torch.argmax, to_tensor=to_tensor_all) + self.argmin = adapter.classical_from_torch.reduce(torch.argmin, to_tensor=to_tensor_all) + + self.sort = adapter.classical_from_torch.sort(torch.sort, to_tensor=to_tensor_all) + self.argsort = adapter.classical_from_torch.sort(torch.argsort, to_tensor=to_tensor_all) + self.roll = adapter.classical_from_numpy.roll(lambda x, *, shift, axis: torch.roll(x, shifts=shift, dims=axis), to_tensor=to_tensor_all) + self.flip = adapter.classical_from_numpy.preserve_shape(lambda x, *, axis: torch.flip(x, dims=axis), to_tensor=to_tensor_all, no_none_axis=True) + self.softmax = adapter.classical_from_torch.softmax( + torch.nn.functional.softmax, adapter.classical_from_classical.softmax(self), to_tensor=to_tensor_all + ) + self.log_softmax = adapter.classical_from_torch.softmax( + torch.nn.functional.log_softmax, adapter.classical_from_classical.log_softmax(self), to_tensor=to_tensor_all + ) + + def to_tensor_get_at(x, y): + x = _to_tensor(asarray_with_device, forward=[torch.Tensor], convert=["numpy", "scalar"])(x) + y = _to_tensor(asarray_with_device, forward=[torch.Tensor, "scalar"], convert=["numpy"])(y) + return x, y + + def take(x, y): + return tracer.signature.classical.getitem()(x, y) + + self.get_at = adapter.classical_from_numpy.get_at(torch.Tensor.__getitem__, take, reshape=self.reshape, to_tensor=to_tensor_get_at) + self.set_at = adapter.classical_from_numpy.update_at( + lambda x, indices, updates: torch.index_put_(x, indices, updates, accumulate=False), to_tensor=to_tensor_all, broadcast=self.broadcast_to + ) + self.add_at = adapter.classical_from_numpy.update_at( + lambda x, indices, updates: torch.index_put_(x, indices, updates, accumulate=True), to_tensor=to_tensor_all, broadcast=self.broadcast_to + ) + self.subtract_at = adapter.classical_from_numpy.update_at( + lambda x, indices, updates: torch.index_put_(x, indices, torch.neg(updates), accumulate=True), to_tensor=to_tensor_all, broadcast=self.broadcast_to + ) + + self.arange = adapter.classical_from_numpy.arange(lambda x, dtype: torch.arange(x, dtype=dtype, device=get_device()), to_dtype=_to_dtype) + self.split = adapter.classical_from_numpy.split(torch.split, to_tensor=to_tensor_all, argname_axis="dim", cumulative=False) + self.concatenate = adapter.classical_from_numpy.concatenate(lambda xs, *, axis=0: torch.cat(xs, dim=axis), to_tensor=to_tensor_all) + self.dot = adapter.classical_from_numpy.dot(torch.dot, to_tensor=to_tensor_all) + self.matmul = adapter.classical_from_numpy.matmul(torch.matmul, to_tensor=to_tensor_all) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/devicestack.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/devicestack.py new file mode 100644 index 0000000000000000000000000000000000000000..847bff310df149ba4b7262329dfad8f7af16326f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/devicestack.py @@ -0,0 +1,50 @@ +import einx._src.tracer as tracer +import threading +import types +from einx._src.util.functools import use_name_of + + +class TorchDeviceStack: + def __init__(self): + self._thread_local = threading.local() + self.namedtensor = types.SimpleNamespace(op=self._wrap_namedtensor_op, ops=self._wrap_namedtensor_ops) + + def get_device(self): + stack = self._get_stack() + assert len(stack) > 0 + return stack[-1] + + def _wrap_namedtensor_op(self, op): + @use_name_of(op) + def inner(*tensors, out, **kwargs): + self._enter([t.value for t in tensors]) + try: + return op(*tensors, out=out, **kwargs) + finally: + self._exit([t.value for t in tensors]) + + return inner + + def _wrap_namedtensor_ops(self, ops): + return {name: self._wrap_namedtensor_op(op) for name, op in ops.items()} + + def _get_stack(self): + if not hasattr(self._thread_local, "stack"): + self._thread_local.stack = [] + return self._thread_local.stack + + def _enter(self, tensors): + device = None + for tensor in tensors: + if isinstance(tensor, tracer.signature.classical.Tensor): + device = tracer.signature.python.getattr(tensor, "device") + break + # if device is None: + # raise ValueError("Failed to determine the PyTorch device placement of parameters. Maybe convert the given arguments to a tensor first.") + stack = self._get_stack() + stack.append(device) + + def _exit(self, tensors): + stack = self._get_stack() + assert len(stack) > 0 + stack.pop() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/einsum_from_torch.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/einsum_from_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..11fefe708ba8352b331dba09342b18285121ec18 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/einsum_from_torch.py @@ -0,0 +1,10 @@ +import einx._src.adapter as adapter +from .._util import _to_tensor + + +def einsum_from_torch(torch, get_device): + def to_tensor(*args): + to_tensor_one = _to_tensor(lambda x: torch.asarray(x, device=get_device()), forward=[torch.Tensor], convert=["numpy", "scalar"]) + return [to_tensor_one(arg) for arg in args] + + return adapter.einsum_from_numpy(torch.einsum, to_tensor=to_tensor) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/vmap_from_torch.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/vmap_from_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..8a34aee6acb304008a114a5713536af6931082eb --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/adapter/torch/vmap_from_torch.py @@ -0,0 +1,10 @@ +from .._util import _to_tensor +import einx._src.adapter as adapter + + +def vmap_from_torch(torch, get_device): + def to_tensor(*args): + to_tensor_one = _to_tensor(lambda x: torch.asarray(x, device=get_device()), forward=[torch.Tensor], convert=["scalar", "numpy"]) + return [to_tensor_one(arg) for arg in args] + + return adapter.vmap_from_jax(lambda op, in_axes, out_axes: torch.vmap(op, in_dims=in_axes, out_dims=out_axes), to_tensor=to_tensor) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/api.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e616116d83891e7dbdb0bba5fa67d95f73cfc771 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/api.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/backend.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/backend.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..726270ab7080fffce3f0fa84a343b8802c504587 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/backend.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/errors.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/errors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac679c79a7722c7ff22a99e3f803afd0a00c2f47 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/errors.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/ops.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01d10ee90556f99916e7ad85670ea2c1afabf19c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/ops.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/removed_ops.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/removed_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d512f4fb11efa93834576f9fd649eb97f70dcfe1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/removed_ops.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/types.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..494130deaa67f72638f01eff090e9456c984a148 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/types.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/util.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..562da87034c9960d948a6c10fc7fb9a1cd48c09c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/__pycache__/util.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/api.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/api.py new file mode 100644 index 0000000000000000000000000000000000000000..3fbe522c2e7a0f692fe47215b6f84cf088a5988a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/api.py @@ -0,0 +1,237 @@ +import functools +import inspect +import traceback +import types +from collections.abc import Callable +from functools import partial +from typing import Any, TypeVar, overload + +import numpy as np + +import einx._src.tracer as tracer +from einx._src.frontend.errors import CallOperationError +from einx._src.util.lru_cache import lru_cache + +from .backend import registry +from .types import Tensor + +_F = TypeVar("_F", bound=Callable[..., Any]) + + +class TensorArg: + def __init__(self, value): + self.value = value + + +def _split_tensors(signature, args, kwargs): + tensor_args = [] + + def replace_with_tensorarg(value): + tensor_args.append(value) + return TensorArg(value) + + try: + bound = signature.bind(*args, **kwargs) + bound_arguments_without_defaults = bound.arguments.copy() + bound.apply_defaults() + bound_arguments_with_defaults = bound.arguments.copy() + except TypeError as e: + raise TypeError(f"The einx operation received incorrect arguments. {e}\nThe function's signature is: {signature}") from e + + new_args = [] + new_kwargs = {} + + for name, param in signature.parameters.items(): + if name in bound_arguments_with_defaults: + val = bound_arguments_with_defaults[name] + + # Determine if the parameter is a tensor and will be traced + if param.annotation is Tensor or param.annotation == "Tensor": + # Parameter is marked as Tensor => is a tensor + is_tensor = True + else: + # Parameter is marked as non-Tensor or has no annotation => not a tensor + is_tensor = False + + if is_tensor: + # Tensors are traced and replaced with TensorArg + if param.kind == inspect.Parameter.VAR_POSITIONAL: + val = tuple(replace_with_tensorarg(v) for v in val) + else: + val = replace_with_tensorarg(val) + + if param.kind == inspect.Parameter.POSITIONAL_ONLY: + new_args.append(val) + elif param.kind == inspect.Parameter.VAR_POSITIONAL: + assert isinstance(val, tuple | list) + new_args.extend(val) + elif param.kind == inspect.Parameter.KEYWORD_ONLY: + new_kwargs[name] = val + elif param.kind == inspect.Parameter.VAR_KEYWORD: + assert isinstance(val, dict) + new_kwargs.update(val) + elif param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD: + # Positional-or-keyword arguments are ... + if name in kwargs: + # ... forwarded as keyword arguments if they are given as keyword arguments + new_kwargs[name] = val + elif name not in bound_arguments_without_defaults: + # ... forwarded as keyword arguments if they are given only as default parameters + new_kwargs[name] = val + else: + # ... forwarded as positional arguments if they are given as positional arguments + new_args.append(val) + else: + raise AssertionError(f"Unknown parameter kind: {param.kind}") + + return new_args, new_kwargs, tensor_args + + +def _is_scalar(x): + return isinstance(x, int | float | bool | np.integer | np.floating | np.bool_) + + +def _get_signature(func): + try: + signature = inspect.signature(func) + except ValueError: + signature = inspect.signature(lambda shape: None) + return {**signature.parameters} + + +def _to_tracer(x, backend, name): + if isinstance(x, TensorArg): + if backend.is_supported_tensor(x.value): + return tracer.signature.classical.Tensor(None, shape=backend.get_shape(x.value)) + elif isinstance(x.value, np.ndarray): + return tracer.signature.classical.ConvertibleTensor( + None, shape=tuple(int(x) for x in x.value.shape), concrete=types.SimpleNamespace(type=type(x.value)) + ) + elif _is_scalar(x.value): + return tracer.signature.classical.ConvertibleTensor(None, shape=(), concrete=types.SimpleNamespace(type=type(x.value))) + elif callable(x.value): + return tracer.signature.classical.ConvertibleTensor( + None, shape=None, concrete=types.SimpleNamespace(type=type(x.value), parameters=_get_signature(x.value)) + ) + else: + raise ValueError(f"The {name} to the einx function has an invalid type: {type(x.value)}") + else: + return x + + +def _construct_graph(args, kwargs, func, backend=None): + if backend is None: + backend = kwargs["backend"] + + # Trace function with the given tracer objects + input_tracers = [x for x in list(args) + list(kwargs.values()) if isinstance(x, tracer.Tracer)] + with tracer.depend_on( + *input_tracers + ): # Ensure that no constant tensors are allocated at graph construction time -> all functions must be invoked inside the compiled function + output_tracer = func(*args, **kwargs) + + # Create graph object + graph = tracer.Graph(inputs=input_tracers, output=output_tracer, name="op") + + # from einx._src.tracer.visualize import visualize # TODO: remove + # dot = visualize(graph) + # dot.render(filename="~/graph1", format="pdf", cleanup=True) + + # Optimize graph + graph = tracer.optimize(graph, optimizations=backend.optimizations) + + # from einx._src.tracer.visualize import visualize # TODO: remove + # dot = visualize(graph) + # dot.render(filename="~/graph2", format="pdf", cleanup=True) + + # Compile graph to callable function + function, code = backend.compiler.compile(graph, return_code=True) + + return function, code + + +def to_ord_str(x): + if x == 0: + return "1st" + elif x == 1: + return "2nd" + elif x == 2: + return "3rd" + else: + return f"{x + 1}th" + + +def _api_withoutbackend(func, signature): + if signature is None: + signature = inspect.signature(func) + + construct_graph_with_cache = lru_cache(partial(_construct_graph, func=func)) + + @functools.wraps(func) + def inner(*args, backend=None, graph=False, **kwargs): + # Find tensor arguments that will be traced + args, kwargs, tensor_args = _split_tensors(signature, args, kwargs) + del kwargs["backend"] + + # Find backend + backend = registry.get(backend, tensor_args) + backend.raise_on_import_failure() + + # Convert tensor arguments to Tracer + args = [_to_tracer(x, backend, name=f"{to_ord_str(i)} positional argument") for i, x in enumerate(args)] + kwargs = {k: _to_tracer(v, backend, name=f"keyword argument '{k}'") for k, v in kwargs.items()} + + # Construct function or retrieve from cache + function, code = construct_graph_with_cache(args=args, kwargs=kwargs | {"backend": backend}) + if graph: + return code + + # Call function + try: + return function(*tensor_args) + except Exception as e: + raise CallOperationError.create(e, code) from e + + return inner + + +def _api_withbackend(func, backend, signature): + if signature is None: + signature = inspect.signature(func) + + construct_graph_with_cache = lru_cache(partial(_construct_graph, func=func, backend=backend)) + + @functools.wraps(func) + def inner(*args, graph=False, **kwargs): + # Find tensor arguments that will be traced + args, kwargs, tensor_args = _split_tensors(signature, args, kwargs) + + # Convert tensor arguments to Tracer + args = [_to_tracer(x, backend, name=f"{to_ord_str(i)} positional argument") for i, x in enumerate(args)] + kwargs = {k: _to_tracer(v, backend, name=f"keyword argument '{k}'") for k, v in kwargs.items()} + + # Construct function or retrieve from cache + function, code = construct_graph_with_cache(args=args, kwargs=kwargs) + if graph: + return code + + # Call function + try: + return function(*tensor_args) + except Exception as e: + raise CallOperationError.create(e, code) from e + + return inner + + +@overload +def api(func: _F) -> _F: ... +@overload +def api(func: None = None, backend: Any = None, signature: Any = None) -> Callable[[_F], _F]: ... +def api(func=None, backend=None, signature=None): + if func is None: + return partial(api, backend=backend, signature=signature) + if backend is None: + return _api_withoutbackend(func, signature=signature) + else: + return _api_withbackend(func, backend, signature=signature) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/backend.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..7935f4a74998c10132b886fe7dbfcddb805e1a3e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/backend.py @@ -0,0 +1,336 @@ +import sys +import traceback +import types +import threading +from einx._src.frontend.errors import ImportBackendError +from einx._src.frontend.errors import OperationNotSupportedError +from einx._src.frontend.errors import BackendResolutionError +import functools +import numpy as np + + +class InvalidBackend: + def __init__(self, name, message, priority=0): + self.name = name + self.message = message + self.priority = priority + + def is_supported_tensor(self, tensor): + return False + + def __getattr__(self, name): + raise ImportBackendError(self.message) + + def raise_on_import_failure(self): + raise ImportBackendError(self.message) + + def __hash__(self): + return id(self) + + def __eq__(self, other): + return self is other + + def __enter__(self): + Use(self, registry).__enter__() + + def __exit__(self, *args): + Use(self, registry).__exit__(*args) + + +class Backend: + def __init__(self, ops, name, priority, optimizations, compiler, is_supported_tensor, get_shape): + self.ops = ops + self.name = name + self.priority = priority + self.optimizations = optimizations + self.compiler = compiler + self.is_supported_tensor = is_supported_tensor + self.get_shape = get_shape + + def __getattr__(self, name): + def op(*args, **kwargs): + if name not in self.ops: + raise OperationNotSupportedError(f"{name} operation is not supported by the {self.name} backend.") + return self.ops[name](*args, **kwargs) + + if name in self.ops: + op = functools.wraps(self.ops[name])(op) + else: + op.__name__ = name + + return op + + def raise_on_import_failure(self): + pass + + def __hash__(self): + return id(self) + + def __eq__(self, other): + return self is other + + def __enter__(self): + Use(self, registry).__enter__() + + def __exit__(self, *args): + Use(self, registry).__exit__(*args) + + +class Use: + def __init__(self, backend, registry): + self.backend = backend + self.registry = registry + + def __enter__(self): + self.registry.enter(self.backend) + + def __exit__(self, exc_type, exc_value, traceback): + self.registry.exit(self.backend) + + +class BackendRegistryState: + def __init__(self, state=None): + self.seen_module_names = set() + self.uninitialized_backends = {} # module name -> (backend factory, tensor-types) + self.backends = [] + self.tensortypes_to_backend = {} + self.name_to_backend = {} + self.use_stack = [] + if state is not None: + self.seen_module_names.update(state.seen_module_names) + self.uninitialized_backends.update(state.uninitialized_backends) + self.backends.extend(state.backends) + self.tensortypes_to_backend.update(state.tensortypes_to_backend) + self.name_to_backend.update(state.name_to_backend) + self.use_stack.extend(state.use_stack) + + def _invalid_backend_reasons(self): + invalid_backends = [backend for backend in self.backends if isinstance(backend, InvalidBackend)] + if len(invalid_backends) > 0: + message = "\n\nThe following backends could not be initialized:\n" + for backend in invalid_backends: + message += f"\n############################ {backend.name} ############################\n" + message += f"{backend.message}\n" + else: + message = "" + return message + + def _run_factory(self, module_name, backend_name, backend_factory): + try: + backend = backend_factory() + except Exception: + backend = InvalidBackend( + backend_name, f'Failed to import backend "{backend_name}" for module "{module_name}" due to the following error:\n{traceback.format_exc()}' + ) + self._register(backend) + + def _register(self, backend): + if not isinstance(backend, Backend | InvalidBackend): + raise ValueError("Backend must be an instance of Backend or InvalidBackend.") + + self.backends.append(backend) + self.name_to_backend[backend.name] = backend + + def _register_on_import(self, module_name, backend_name, backend_factory): + if module_name in sys.modules: + # Module is already imported -> register backend now + self._run_factory(module_name, backend_name, backend_factory) + else: + # Module is not yet imported -> register factory + if module_name not in self.uninitialized_backends: + self.uninitialized_backends[module_name] = [] + self.uninitialized_backends[module_name].append((backend_name, backend_factory)) + + def _check_new_imports(self, has_checked): + if has_checked[0]: + return False + has_checked[0] = True + + if any(module_name not in self.seen_module_names for module_name in sys.modules): + new_module_names = [module_name for module_name in sys.modules if module_name not in self.seen_module_names] + + for new_module_name in new_module_names: + self.seen_module_names.add(new_module_name) + if new_module_name in self.uninitialized_backends: + for backend_name, backend_factory in self.uninitialized_backends[new_module_name]: + self._run_factory(new_module_name, backend_name, backend_factory) + del self.uninitialized_backends[new_module_name] + + return True + else: + return False + + def _get_by_tensors(self, tensors, has_checked_new_imports=None): + tensortypes = tuple(type(tensor) for tensor in tensors) + if tensortypes in self.tensortypes_to_backend: + return [self.tensortypes_to_backend[tensortypes]] + + if has_checked_new_imports is None: + has_checked_new_imports = [False] + + def _get_by_tensor(tensor): + # Find backends that support this tensor type + backends = [backend for backend in self.backends if backend.is_supported_tensor(tensor)] + + if len(backends) > 0: + return backends + else: + # If no backend was found and we haven't already checked for new imports, check and try again + changed = self._check_new_imports(has_checked_new_imports) + if changed: + return _get_by_tensor(tensor) + return [] + + backends = set() + for tensor in tensors: + backends.update(_get_by_tensor(tensor)) + backends = list(backends) + + if all(isinstance(tensor, float | int | bool | np.floating | np.integer | np.bool_) for tensor in tensors): + backends = [self._get_by_name("numpy")] + + # Keep only backends with highest priority + if len(backends) > 1: + max_priority = max(backend.priority for backend in backends) + backends = [backend for backend in backends if backend.priority == max_priority] + + # If exactly one backend was found, cache it for these tensor types + if len(backends) == 1: + self.tensortypes_to_backend[tensortypes] = backends[0] + + return backends + + def _get_by_name(self, name, has_checked_new_imports=None): + if name not in self.name_to_backend: + if has_checked_new_imports is None: + has_checked_new_imports = [False] + changed = self._check_new_imports(has_checked_new_imports) + if not changed or name not in self.name_to_backend: + raise ValueError( + f"Backend with name {name} not found. Currently registered backends are: " + f"{list(self.name_to_backend.keys())}{self._invalid_backend_reasons()}" + ) + return self.name_to_backend.get(name) + + def _get(self, backend=None, tensors=None, has_checked_new_imports=None): + if tensors is None: + tensors = [] + + # If backend object is given + if isinstance(backend, Backend | InvalidBackend): + return backend + + if has_checked_new_imports is None: + has_checked_new_imports = [False] + + # If backend name is given + if isinstance(backend, str): + return self._get_by_name(backend, has_checked_new_imports) + + # If global default backend is specified + if len(self.use_stack) > 0: + return self.use_stack[-1] + + # Other backend parameters are invalid + if backend is not None: + raise ValueError("Backend must be either a Backend instance, a string, or None.") + + # If no backend is specified, determine backend from tensors + backends = self._get_by_tensors(tensors, has_checked_new_imports) + if len(backends) == 1: + return backends[0] + elif len(backends) > 1: + raise BackendResolutionError( + "Failed to determine which backend to use for this operation:\n" + " - The 'backend' parameter is not specified.\n" + " - No global default backend is specified using 'with backend:'.\n" + " - Multiple registered backends with same priority match the tensor types of the arguments: " + f"{', '.join([backend.name for backend in backends])}" + ) + else: + message = ( + "Failed to determine which backend to use for this operation:\n" + " - The 'backend' parameter is not specified.\n" + " - No global default backend is specified using 'with backend:'.\n" + f" - No registered backends match the tensor types of the arguments: {', '.join([str(type(t)) for t in tensors])}" + ) + message += self._invalid_backend_reasons() + + raise BackendResolutionError(message) + + def _enter(self, backend): + self.use_stack.append(backend) + + def _exit(self, backend): + assert id(self.use_stack[-1]) == id(backend) + self.use_stack.pop() + + def register(self, backend): + new_state = BackendRegistryState(self) + new_state._register(backend) + return new_state + + def register_on_import(self, module_name, backend_name, backend_factory): + new_state = BackendRegistryState(self) + new_state._register_on_import(module_name, backend_name, backend_factory) + return new_state + + def get_by_tensors(self, tensors): + new_state = BackendRegistryState(self) + backends = new_state._get_by_tensors(tensors) + return new_state, backends + + def get_by_name(self, name): + new_state = BackendRegistryState(self) + backend = new_state._get_by_name(name) + return new_state, backend + + def get(self, backend=None, tensors=None): + new_state = BackendRegistryState(self) + backend = new_state._get(backend, tensors) + return new_state, backend + + def enter(self, backend): + new_state = BackendRegistryState(self) + new_state._enter(backend) + return new_state + + def exit(self, backend): + new_state = BackendRegistryState(self) + new_state._exit(backend) + return new_state + + +class BackendRegistry: + def __init__(self): + self.state = BackendRegistryState() + self.use_lock = threading.Lock() + + def register(self, backend): + self.state = self.state.register(backend) + + def register_on_import(self, module_name, backend_name, backend_factory): + self.state = self.state.register_on_import(module_name, backend_name, backend_factory) + + def get_by_tensors(self, tensor): + self.state, backends = self.state.get_by_tensors(tensor) + return backends + + def get_by_name(self, name): + self.state, backend = self.state.get_by_name(name) + return backend + + def get(self, backend=None, tensors=None): + self.state, backend = self.state.get(backend, tensors) + return backend + + def enter(self, backend): + with self.use_lock: + self.state = self.state.enter(backend) + + def exit(self, backend): + with self.use_lock: + self.state = self.state.exit(backend) + + +registry = BackendRegistry() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/errors.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..29d1381d98546eab2cb51929ab8e58701e55e3f6 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/errors.py @@ -0,0 +1,265 @@ +import traceback + + +def export(obj): + obj.__module__ = "einx.errors" + return obj + + +@export +class EinxError(Exception): + pass + + +@export +class SyntaxError(EinxError): + """ + This error occurs if einx operations encounter invalid syntax in an expression. + + Example: + >>> x = np.random.rand(3, 4) + >>> einx.id("a (b -> b a", x) + einx.errors.SyntaxError: Found an opening parenthesis that is not closed: + Expression: "a (b" + ^ + """ + + def __init__(self, expression, message, pos=None): + if not isinstance(expression, str): + raise ValueError("expression must be a string") + + from einx._src.namedtensor import ExpressionIndicator + + indicator = ExpressionIndicator(expression) + + if isinstance(pos, int): + self.pos = [pos] + elif pos is None: + self.pos = [] + else: + self.pos = list(pos) + assert all(p >= 0 and p < len(expression) for p in self.pos) + + if "%EXPR%" in message: + message = message.replace("%EXPR%", indicator.create(self.pos)) + + EinxError.__init__(self, message) + + +@export +class RankError(EinxError): + """ + This error occurs if the ranks (i.e. number of dimensions) of all expressions cannot + be determined under the given input tensor shapes and additional constraints. + + Example: + >>> x = np.random.rand(3, 4) + >>> einx.id("a b c -> a c b", x) + einx.errors.RankError: The number of tensor dimensions and axes in the expression does not match. + The operation was called with the following arguments: + - Positional argument #1: Tensor with shape (3, 4) + """ + + def __init__(self, invocation, message, pos=None, constraints=None): + if constraints is None: + constraints = [] + + if isinstance(pos, int): + self.pos = [pos] + elif pos is None: + self.pos = [] + else: + self.pos = list(pos) + assert all(p >= 0 and p < len(invocation.expression) for p in self.pos) + + constraints2 = [] + for constraint in constraints: + if isinstance(constraint, str): + constraints2.append(constraint) + else: + assert len(constraint) == 2 + if constraint[0] is not None and constraint[1] is not None: + constraints2.append(f"{constraint[0]} = {constraint[1]}") + + if "%EXPR%" in message: + message = message.replace("%EXPR%", invocation.indicator.create(self.pos)) + if len(constraints2) > 0: + message += "\nThe following equation(s) were determined for the expression:" + for constraint in constraints2: + message += f"\n {constraint}" + message += "\n" + invocation.to_call_signature_string() + + EinxError.__init__(self, message) + + +@export +class AxisSizeError(EinxError): + """ + This error occurs if the size of all axes in an einx expression cannot be determined + under the given input tensor shapes and additional constraints. + + Example: + >>> x = np.random.rand(3, 4) + >>> y = np.random.rand(4, 4) + >>> einx.add("a b, a c -> a b c", x, y) + einx.errors.AxisSizeError: Failed to determine the size of all axes in the expression under the given constraints. + Expression: "a b, a c -> a b c" + + The operation was called with the following arguments: + - Positional argument #1: Tensor with shape (3, 4) + - Positional argument #2: Tensor with shape (4, 4) + """ + + def __init__(self, invocation, message, pos=None, constraints=None): + if constraints is None: + constraints = [] + + if isinstance(pos, int): + self.pos = [pos] + elif pos is None: + self.pos = [] + else: + self.pos = list(pos) + assert all(p >= 0 and p < len(invocation.expression) for p in self.pos) + + constraints2 = [] + for constraint in constraints: + if isinstance(constraint, str): + constraints2.append(constraint) + else: + assert len(constraint) == 2 + if constraint[0] is not None and constraint[1] is not None: + constraints2.append(f"{constraint[0]} = {constraint[1]}") + + if "%EXPR%" in message: + message = message.replace("%EXPR%", invocation.indicator.create(self.pos)) + if len(constraints2) > 0: + message += "\nThe expression, tensor shapes and contraints resulted in the following equation(s):" + for constraint in constraints2: + message += f"\n {constraint}" + message += "\n" + invocation.to_call_signature_string() + + EinxError.__init__(self, message) + + +@export +class SemanticError(EinxError): + """ + This error occurs if the expression requirements of a particular einx operation are not met. + + Example: + >>> x = np.random.rand(3, 4) + >>> y = np.random.rand(4, 5) + >>> einx.dot("a [b], [c] d -> a d", x, y) + einx.errors.SemanticError: All contracted axes must appear in exactly two input expressions. + Expression: "a [b], [c] d -> a d" + ^ ^ + The operation was called with the following arguments: + - Positional argument #1: Tensor with shape (3, 4) + - Positional argument #2: Tensor with shape (4, 5) + """ + + def __init__(self, message, invocation=None, pos=None): + assert isinstance(message, str) + if invocation is not None: + if isinstance(pos, int): + self.pos = [pos] + elif pos is None: + self.pos = [] + else: + self.pos = list(pos) + assert all(p >= 0 and p < len(invocation.expression) for p in self.pos) + + if "%EXPR%" in message: + message = message.replace("%EXPR%", invocation.indicator.create(self.pos)) + message += "\n" + invocation.to_call_signature_string() + + else: + self.pos = None + + EinxError.__init__(self, message) + + +@export +class OperationNotSupportedError(EinxError): + """ + This error occurs if an einx operation is not supported by the selected backend. + + Example: + >>> x = np.random.rand(3, 4) + >>> einx.min("a [b]", x, backend="numpy.einsum") + einx.errors.OperationNotSupportedError: min operation is not supported by the numpy.einsum backend. + """ + + def __init__(self, message=None): + if message is None: + message = "This operation is not supported by this backend." + EinxError.__init__(self, message) + + +@export +class ImportBackendError(EinxError): + """ + This error occurs if a requested backend failed to be imported or initialized. + + Example: + >>> sys.modules["jax"] = types.SimpleNamespace() # Create some invalid jax module + >>> x = np.random.rand(3, 4) + >>> einx.min("a [b]", x, backend="jax") + einx.errors.ImportBackendError: Failed to import backend "jax" for module "jax" due to the following error: ... + """ + + pass + + +@export +class BackendResolutionError(EinxError): + """ + This error occurs if the backend with which to execute an einx operation could not be determined. + + Example: + >>> x = jnp.zeros((10, 11)) + >>> y = torch.zeros(10, 11) + >>> einx.add("a b, a b", x, y) + einx.errors.BackendResolutionError: Failed to determine which backend to use for this operation: ... + """ + + pass + + +@export +class CallOperationError(EinxError): + """ + This error occurs if the Python function that einx compiles for an einx operation fails to execute. + + Example: + >>> op = lambda x: None # Create some invalid operation + >>> einop = einx.jax.adapt_with_vmap(op) + >>> x = np.random.rand(3, 4) + >>> einop("a [b] -> a", x) + einx.errors.CallOperationError: The function that was compiled for this operation failed to execute. + ... + The error was: AssertionError: Expected 1st return value of the adapted function to be a tensor + """ + + @staticmethod + def create(e, code): + message = "The function that was compiled for this operation failed to execute." + if code is not None: + message += " The following code was generated:\n" + for i, line in enumerate(code.splitlines(), 1): + message += f"{i:4}: {line}\n" + + if e.__traceback__ is not None: + tb = traceback.extract_tb(e.__traceback__) + if tb: + linenos = [frame.lineno for frame in tb if frame.filename == ""] + if len(linenos) == 1: + message += f"The error occurred at line {linenos[0]}.\n" + + message += "\nThe error was: " + if hasattr(type(e), "__name__"): + message += f"{type(e).__name__}" + if len(str(e)) > 0: + message += f": {e}" + return CallOperationError(message) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/_docs.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/_docs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38929c8457e2f29d867b41d5cbb63ca5e637736e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/_docs.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/_util.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67f6acdcc5badb03b31731276f738cbcd7564466 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/_util.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/arrayapi.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/arrayapi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b12990c69017a4db67ebcc2ff01cdbb2406a775 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/arrayapi.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/functorchdim.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/functorchdim.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cf1c9adc3d9a2d0c5b62423502c3072c00ee3cf Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/functorchdim.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/jax.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/jax.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38ba9e1a0a3d59b155450fc1c340b6662d25957e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/jax.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/mlx.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/mlx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6410ea41cc0262445de3158f1d5ede730d4535d7 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/mlx.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/numpy.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/numpy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24fe2bef099ae024e128a48e20b84160ff52b583 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/numpy.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/tensorflow.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/tensorflow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1af012359d6eaa46d71dc21c21d6a048bf4fa564 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/tensorflow.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/tinygrad.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/tinygrad.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73efcf75c29720516ce671a376ea7c303375a674 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/tinygrad.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/torch.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..488375a1119a37572454c3df26ed0fc4b5d289e8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/__pycache__/torch.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/_docs.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..c185254f73fb3453737419056658a6dcd3bafdaf --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/_docs.py @@ -0,0 +1,76 @@ +def _make_doc_adapt_numpylike_reduce(): + return """Adapts an operation with a Numpy-like reduce signature to einx notation. + +The operation is expected to have the following Numpy-like signature: + +.. code-block:: python + + def op(tensor: Tensor, axis: Tuple[int]) -> Tensor: + ... + +It should return a tensor with the same shape as the input tensor, but with axes at positions specified in `axis` removed. + +Args: + op: The operation that will be adapted to einx notation. + +Returns: + A new operation that follows einx notation and internally invokes the original operation. +""" + + +def _make_doc_adapt_numpylike_elementwise(): + return """Adapts an operation with a Numpy-like element-wise signature to einx notation. + +The operation is expected to have the following Numpy-like signature: + +.. code-block:: python + + def op(*tensors: Tensor) -> Tensor: + ... + +All input tensors are guaranteed to be broadcastable according to Numpy's `broadcasting rules +`__. They are +additionally guaranteed to have the same number of dimensions. The function should return a tensor +with the broadcasted shape of the input tensors. + +Args: + op: The operation that will be adapted to einx notation. + +Returns: + A new operation that follows einx notation and internally invokes the original operation. +""" + + +def _make_doc_adapt_with_vmap(framework, vmap): + return f"""Adapts an operation to einx notation using {vmap}. + +The operation is expected to have one of the following signatures: + +.. code-block:: python + + def op(*tensors: Tensor) -> Tensor: + ... + + def op(*tensors: Tensor) -> Tuple[Tensor]: + ... + +The number and shapes of input and output tensors match the signature of the elementary operation specified +in the einx expression (i.e. containing all non-vectorized axes). For example: + +.. code-block:: python + + @einx.{framework}.adapt_with_vmap + def einop(x, y): + # shape of x is (b, c) + # shape of y is (c) + ... + return ... # shape of result must be (c, b) + + z = einop("a [b c] x, d [c] -> a d x [c b]", x, y) + +Args: + op: The operation that will be adapted to einx notation. + +Returns: + A new operation that follows einx notation and internally invokes the original operation. +""" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/_util.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e54ee7cc396db1978f1bd112df5ea4f74241dcb5 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/_util.py @@ -0,0 +1,29 @@ +import inspect +from einx._src.frontend.errors import OperationNotSupportedError + + +def _make_iskwarg(op): + if not callable(op): + raise ValueError(f"The given operation must be callable, but found type {type(op)}.") + + signature = inspect.signature(op) + parameters = {**signature.parameters} + + kwargnames = [] + for name, param in parameters.items(): + if param.kind is inspect.Parameter.KEYWORD_ONLY: + kwargnames.append(name) + elif param.kind is inspect.Parameter.VAR_KEYWORD: + raise ValueError(f"The given operation must not have a var-keyword parameter, but found '**{name}'.") + return lambda name: name in kwargnames + + +def _unsupported_op(name, backend, message=None): + def op(*args, **kwargs): + message2 = f"{name} operation is not supported by the {backend} backend." + if message is not None: + message2 += " " + message + raise OperationNotSupportedError(message2) + + op.__name__ = name + return op diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/arrayapi.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/arrayapi.py new file mode 100644 index 0000000000000000000000000000000000000000..72eb6888aa382f50ceedef0bf772a4b4058d9ec8 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/arrayapi.py @@ -0,0 +1,148 @@ +from ..backend import registry +from ..backend import Backend +import einx._src.adapter as adapter +import einx._src.tracer as tracer +from ._util import _make_iskwarg +from ..api import api +import types +from functools import partial +from ._docs import _make_doc_adapt_numpylike_reduce +from ._docs import _make_doc_adapt_numpylike_elementwise + + +def _get_backend_kwargs(): + np = tracer.signature.python.import_("numpy", as_="np") + optimizations = [ + tracer.optimizer.classical.SkipReshape(np.reshape), + tracer.optimizer.classical.SkipTranspose(np.transpose), + tracer.optimizer.classical.SkipBroadcastTo(np.broadcast_to), + tracer.optimizer.classical.SkipConcatenate(np.concatenate), + tracer.optimizer.InlineGraph(), + tracer.optimizer.SkipCast(), + ] + + import array_api_compat + import numpy as np + + def is_supported_tensor(tensor): + try: + array_api_compat.array_namespace(tensor) + return True + except: + return False + + def get_shape(x): + if isinstance(x, int | float | bool | np.integer | np.floating | np.bool_): + return () + elif hasattr(x, "shape"): + return tuple(int(x) for x in x.shape) + else: + raise TypeError(f"Cannot get shape of object of type {type(x)}") + + return {"optimizations": optimizations, "compiler": tracer.compiler.python, "is_supported_tensor": is_supported_tensor, "get_shape": get_shape} + + +def adapt_numpylike_reduce(op): + iskwarg = lambda name, iskwarg=_make_iskwarg(op): name != "axis" and iskwarg(name) + xp_stack = adapter.ArrayApiNamespaceStack() + xp = tracer.signature.arrayapi(xp_stack.get_xp) + + classical = adapter.classical_from_arrayapi.ops(xp) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.reduce(op, expected_type=partial(adapter.tensortype_from_arrayapi, xp)) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, context=xp_stack, expected_type=partial(adapter.tensortype_from_arrayapi, xp)) + op = adapter.einx_from_namedtensor.reduce(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_reduce.__doc__ = _make_doc_adapt_numpylike_reduce() + + +def adapt_numpylike_elementwise(op): + iskwarg = _make_iskwarg(op) + xp_stack = adapter.ArrayApiNamespaceStack() + xp = tracer.signature.arrayapi(xp_stack.get_xp) + + classical = adapter.classical_from_arrayapi.ops(xp) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.elementwise(op, classical, expected_type=partial(adapter.tensortype_from_arrayapi, xp)) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, context=xp_stack, expected_type=partial(adapter.tensortype_from_arrayapi, xp)) + op = adapter.einx_from_namedtensor.elementwise(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_elementwise.__doc__ = _make_doc_adapt_numpylike_elementwise() + + +def _backend_creator(create): + def new_create(): + xp_stack = adapter.ArrayApiNamespaceStack() + + xp = tracer.signature.arrayapi(xp_stack.get_xp) + + classical = adapter.classical_from_arrayapi.ops(xp) + + decomposednamedtensor_ops, name = create(xp, classical) + + namedtensor_ops = adapter.namedtensor_from_decomposednamedtensor.ops(decomposednamedtensor_ops, classical) + namedtensor_ops = adapter.namedtensor_calltensorfactory.ops( + namedtensor_ops, context=xp_stack, expected_type=partial(adapter.tensortype_from_arrayapi, xp) + ) + einx_ops = adapter.einx_from_namedtensor.ops(namedtensor_ops) + + return Backend(ops=einx_ops, name=name, priority=-15, **_get_backend_kwargs()) + + return new_create + + +@_backend_creator +def create_backend_numpylike(xp, classical): + einsum = adapter.einsum_from_arrayapi(xp) + + decomposednamedtensor_ops = ( + {name: adapter.decomposednamedtensor_from_classical.elementwise(getattr(classical, name), classical) for name in adapter.ops.elementwise} + | {name: adapter.decomposednamedtensor_from_classical.reduce(getattr(classical, name)) for name in adapter.ops.reduce} + | {name: adapter.decomposednamedtensor_from_classical.preserve_shape(getattr(classical, name)) for name in adapter.ops.preserve_shape} + | {name: adapter.decomposednamedtensor_from_classical.argfind(getattr(classical, name), classical) for name in adapter.ops.argfind} + | {name: adapter.decomposednamedtensor_from_classical.update_at_ravelled(getattr(classical, name), classical) for name in adapter.ops.update_at} + | {"get_at": adapter.decomposednamedtensor_from_classical.get_at_ravelled(classical), "dot": adapter.decomposednamedtensor_from_einsum.dot(einsum)} + ) + + return decomposednamedtensor_ops, "arrayapi.numpylike" + + +registry.register_on_import("array_api_compat", "arrayapi.numpylike", create_backend_numpylike) + + +@_backend_creator +def create_backend_einsum(xp, classical): + einsum = adapter.einsum_from_arrayapi(xp) + + decomposednamedtensor_ops = { + "id": adapter.decomposednamedtensor_from_einsum.id(einsum), + "sum": adapter.decomposednamedtensor_from_einsum.sum(einsum), + "multiply": adapter.decomposednamedtensor_from_einsum.multiply(einsum), + "dot": adapter.decomposednamedtensor_from_einsum.dot(einsum), + } + + return decomposednamedtensor_ops, "arrayapi.einsum" + + +registry.register_on_import("array_api_compat", "arrayapi.einsum", create_backend_einsum) + + +def create_backend(): + einx_ops_numpylike = create_backend_numpylike().ops + einx_ops_einsum = create_backend_einsum().ops + einx_ops = einx_ops_numpylike | {"dot": einx_ops_einsum["dot"]} + + return Backend(ops=einx_ops, name="arrayapi", priority=-2, **_get_backend_kwargs()) + + +registry.register_on_import("array_api_compat", "arrayapi", create_backend) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/functorchdim.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/functorchdim.py new file mode 100644 index 0000000000000000000000000000000000000000..af9d8aa005572a4a83d75ad3f935724b88d3e645 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/functorchdim.py @@ -0,0 +1,49 @@ +import einx._src.tracer as tracer +import einx._src.adapter as adapter +from ..api import api +import types +import inspect +from ..backend import registry +from ..backend import Backend +import threading +from ._util import _make_iskwarg + +from .torch import _raise_on_invalid_version +from .torch import _allow_ops_in_graph + + +def _get_backend_kwargs(): + optimizations = [tracer.optimizer.InlineGraph(), tracer.optimizer.SkipCast()] + + import torch + + def is_supported_tensor(tensor): + return isinstance(tensor, torch.Tensor) + + def get_shape(tensor): + return tuple(int(x) for x in tensor.shape) + + return {"optimizations": optimizations, "compiler": tracer.compiler.python, "is_supported_tensor": is_supported_tensor, "get_shape": get_shape} + + +def adapt(op): + _raise_on_invalid_version() + iskwarg = lambda name, iskwarg=_make_iskwarg(op): name != "axis" and iskwarg(name) + + device_stack = adapter.TorchDeviceStack() + + torch = tracer.signature.torch() + functorchdim = tracer.signature.python.import_("functorch.dim", as_="ftdim") + + op = tracer.signature.python.constant(op) + op = adapter.namedtensor_from_functorchdim.op(op, torch, functorchdim, get_device=device_stack.get_device) + op = device_stack.namedtensor.op(op) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=torch.Tensor) + op = adapter.einx_from_namedtensor.op(op, iskwarg=iskwarg, allow_concat=False) + + func = api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + import torch + + torch.compiler.allow_in_graph(func) + return func diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/jax.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/jax.py new file mode 100644 index 0000000000000000000000000000000000000000..8a73aee6099dd24acd666f8d447f8105a296d56f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/jax.py @@ -0,0 +1,179 @@ +import einx._src.tracer as tracer +import einx._src.adapter as adapter +from ..api import api +from ..types import Tensor +import types +import inspect +import functools +from functools import partial +from ..backend import registry +from ..backend import Backend +from ._util import _make_iskwarg, _unsupported_op +from ._docs import _make_doc_adapt_numpylike_reduce +from ._docs import _make_doc_adapt_numpylike_elementwise +from ._docs import _make_doc_adapt_with_vmap + + +def _get_backend_kwargs(): + jnp = tracer.signature.python.import_("jax.numpy", as_="jnp") + optimizations = [ + tracer.optimizer.classical.SkipReshape(jnp.reshape), + tracer.optimizer.classical.SkipTranspose(jnp.transpose), + tracer.optimizer.classical.SkipBroadcastTo(jnp.broadcast_to), + tracer.optimizer.classical.SkipConcatenate(jnp.concatenate), + tracer.optimizer.InlineGraph(), + tracer.optimizer.SkipCast(), + ] + + import jax + import jax.numpy as jnp + + try: + tensor_types = (jax.Array, jax.core.Tracer) + except: + tensor_types = jnp.ndarray + + def is_supported_tensor(tensor): + return isinstance(tensor, tensor_types) + + def get_shape(tensor): + return tuple(int(x) for x in tensor.shape) + + return {"optimizations": optimizations, "compiler": tracer.compiler.python, "is_supported_tensor": is_supported_tensor, "get_shape": get_shape} + + +def adapt_with_vmap(op, signature=None): + iskwarg = _make_iskwarg(op) + jax = tracer.signature.jax() + + classical = adapter.classical_from_jax.ops(jax) + vmap = adapter.vmap_from_jax(jax) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_vmap.op(op, vmap, expected_type=jax.numpy.ndarray) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=jax.numpy.ndarray) + op = adapter.einx_from_namedtensor.op(op, iskwarg=iskwarg, el_op=signature, implicit_output="bijective") + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_with_vmap.__doc__ = _make_doc_adapt_with_vmap("jax", "``jax.vmap``") + + +def adapt_numpylike_reduce(op): + iskwarg = lambda name, iskwarg=_make_iskwarg(op): name != "axis" and iskwarg(name) + jax = tracer.signature.jax() + + classical = adapter.classical_from_jax.ops(jax) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.reduce(op, expected_type=jax.numpy.ndarray) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=jax.numpy.ndarray) + op = adapter.einx_from_namedtensor.reduce(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_reduce.__doc__ = _make_doc_adapt_numpylike_reduce() + + +def adapt_numpylike_elementwise(op): + iskwarg = _make_iskwarg(op) + jax = tracer.signature.jax() + + classical = adapter.classical_from_jax.ops(jax) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.elementwise(op, classical, expected_type=jax.numpy.ndarray) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=jax.numpy.ndarray) + op = adapter.einx_from_namedtensor.elementwise(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_elementwise.__doc__ = _make_doc_adapt_numpylike_elementwise() + + +def _backend_creator(create): + def new_create(): + jax = tracer.signature.jax() + classical = adapter.classical_from_jax.ops(jax) + + decomposednamedtensor_ops, name = create(jax, classical) + + namedtensor_ops = adapter.namedtensor_from_decomposednamedtensor.ops(decomposednamedtensor_ops, classical) + namedtensor_ops = adapter.namedtensor_calltensorfactory.ops(namedtensor_ops, expected_type=jax.numpy.ndarray) + einx_ops = adapter.einx_from_namedtensor.ops(namedtensor_ops) + + return Backend(ops=einx_ops, name=name, priority=-5, **_get_backend_kwargs()) + + return new_create + + +@_backend_creator +def create_backend_numpylike(jax, classical): + decomposednamedtensor_ops = ( + {name: adapter.decomposednamedtensor_from_classical.elementwise(getattr(classical, name), classical) for name in adapter.ops.elementwise} + | {name: adapter.decomposednamedtensor_from_classical.reduce(getattr(classical, name)) for name in adapter.ops.reduce} + | {name: adapter.decomposednamedtensor_from_classical.preserve_shape(getattr(classical, name)) for name in adapter.ops.preserve_shape} + | {name: adapter.decomposednamedtensor_from_classical.argfind(getattr(classical, name), classical) for name in adapter.ops.argfind} + | {name: adapter.decomposednamedtensor_from_classical.update_at_ravelled(getattr(classical, name), classical) for name in adapter.ops.update_at} + | { + "get_at": adapter.decomposednamedtensor_from_classical.get_at_ravelled(classical), + "dot": adapter.decomposednamedtensor_from_classical.dot(classical), + } + ) + + return decomposednamedtensor_ops, "jax.numpylike" + + +registry.register_on_import("jax", "jax.numpylike", create_backend_numpylike) + + +@_backend_creator +def create_backend_einsum(jax, classical): + einsum = adapter.einsum_from_jax(jax) + + decomposednamedtensor_ops = { + "id": adapter.decomposednamedtensor_from_einsum.id(einsum), + "sum": adapter.decomposednamedtensor_from_einsum.sum(einsum), + "multiply": adapter.decomposednamedtensor_from_einsum.multiply(einsum), + "dot": adapter.decomposednamedtensor_from_einsum.dot(einsum), + } + + return decomposednamedtensor_ops, "jax.einsum" + + +registry.register_on_import("jax", "jax.einsum", create_backend_einsum) + + +@_backend_creator +def create_backend_vmap(jax, classical): + vmap = adapter.vmap_from_jax(jax) + elementary_ops = adapter.elementary_from_classical.ops(classical) + + decomposednamedtensor_ops = { + name: adapter.decomposednamedtensor_from_vmap.op( + elementary_ops[name], vmap, expected_type=jax.numpy.ndarray, allow_squeeze_unsqueeze=True, classical=classical + ) + for name in adapter.ops.all + } | {name: _unsupported_op(name, "jax.vmap") for name in adapter.ops.update_at} + + return decomposednamedtensor_ops, "jax.vmap" + + +registry.register_on_import("jax", "jax.vmap", create_backend_vmap) + + +def create_backend(): + einx_ops_numpylike = create_backend_numpylike().ops + einx_ops_einsum = create_backend_einsum().ops + einx_ops = einx_ops_numpylike | {"dot": einx_ops_einsum["dot"]} + + return Backend(ops=einx_ops, name="jax", priority=0, **_get_backend_kwargs()) + + +registry.register_on_import("jax", "jax", create_backend) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/mlx.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/mlx.py new file mode 100644 index 0000000000000000000000000000000000000000..46d4161eb0ecc087e70c1faaa04ac653cb4e9253 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/mlx.py @@ -0,0 +1,170 @@ +import einx._src.tracer as tracer +import einx._src.adapter as adapter +from ..types import Tensor +from ..backend import registry +from ..backend import Backend +from ._util import _make_iskwarg, _unsupported_op +from ..api import api +import types +from ._docs import _make_doc_adapt_numpylike_reduce +from ._docs import _make_doc_adapt_numpylike_elementwise +from ._docs import _make_doc_adapt_with_vmap + + +def _get_backend_kwargs(): + mx = tracer.signature.python.import_("mlx.core", as_="mx") + optimizations = [ + tracer.optimizer.classical.SkipReshape(mx.reshape), + tracer.optimizer.classical.SkipTranspose(mx.transpose), + tracer.optimizer.classical.SkipBroadcastTo(mx.broadcast_to), + tracer.optimizer.classical.SkipConcatenate(mx.concatenate), + tracer.optimizer.InlineGraph(), + tracer.optimizer.SkipCast(), + ] + + import mlx.core as mx + + def is_supported_tensor(tensor): + return isinstance(tensor, mx.array) + + def get_shape(tensor): + return tuple(int(x) for x in tensor.shape) + + return {"optimizations": optimizations, "compiler": tracer.compiler.python, "is_supported_tensor": is_supported_tensor, "get_shape": get_shape} + + +def adapt_with_vmap(op, signature=None): + iskwarg = _make_iskwarg(op) + mlx = tracer.signature.mlx() + + classical = adapter.classical_from_mlx.ops(mlx) + vmap = adapter.vmap_from_mlx(mlx) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_vmap.op(op, vmap, expected_type=mlx.core.array) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=mlx.core.array) + op = adapter.einx_from_namedtensor.op(op, iskwarg=iskwarg, el_op=signature, implicit_output="bijective") + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_with_vmap.__doc__ = _make_doc_adapt_with_vmap("mlx", "``mlx.core.vmap``") + + +def adapt_numpylike_reduce(op): + iskwarg = lambda name, iskwarg=_make_iskwarg(op): name != "axis" and iskwarg(name) + mlx = tracer.signature.mlx() + + classical = adapter.classical_from_mlx.ops(mlx) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.reduce(op, expected_type=mlx.core.array) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=mlx.core.array) + op = adapter.einx_from_namedtensor.reduce(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_reduce.__doc__ = _make_doc_adapt_numpylike_reduce() + + +def adapt_numpylike_elementwise(op): + iskwarg = _make_iskwarg(op) + mlx = tracer.signature.mlx() + + classical = adapter.classical_from_mlx.ops(mlx) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.elementwise(op, classical, expected_type=mlx.core.array) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=mlx.core.array) + op = adapter.einx_from_namedtensor.elementwise(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_elementwise.__doc__ = _make_doc_adapt_numpylike_elementwise() + + +def _backend_creator(create): + def new_create(): + mlx = tracer.signature.mlx() + + classical = adapter.classical_from_mlx.ops(mlx) + + decomposednamedtensor_ops, name = create(mlx, classical) + + namedtensor_ops = adapter.namedtensor_from_decomposednamedtensor.ops(decomposednamedtensor_ops, classical) + namedtensor_ops = adapter.namedtensor_calltensorfactory.ops(namedtensor_ops, expected_type=mlx.core.array) + einx_ops = adapter.einx_from_namedtensor.ops(namedtensor_ops) + + return Backend(ops=einx_ops, name=name, priority=-5, **_get_backend_kwargs()) + + return new_create + + +@_backend_creator +def create_backend_numpylike(mlx, classical): + einsum = adapter.einsum_from_mlx(mlx) + + decomposednamedtensor_ops = ( + {name: adapter.decomposednamedtensor_from_classical.elementwise(getattr(classical, name), classical) for name in adapter.ops.elementwise} + | {name: adapter.decomposednamedtensor_from_classical.reduce(getattr(classical, name)) for name in adapter.ops.reduce} + | {name: adapter.decomposednamedtensor_from_classical.preserve_shape(getattr(classical, name)) for name in adapter.ops.preserve_shape} + | {name: adapter.decomposednamedtensor_from_classical.argfind(getattr(classical, name), classical) for name in adapter.ops.argfind} + | {name: adapter.decomposednamedtensor_from_classical.update_at_ravelled(getattr(classical, name), classical) for name in adapter.ops.update_at} + | {"get_at": adapter.decomposednamedtensor_from_classical.get_at_ravelled(classical), "dot": adapter.decomposednamedtensor_from_einsum.dot(einsum)} + ) + + return decomposednamedtensor_ops, "mlx.numpylike" + + +registry.register_on_import("mlx", "mlx.numpylike", create_backend_numpylike) + + +@_backend_creator +def create_backend_einsum(mlx, classical): + einsum = adapter.einsum_from_mlx(mlx) + + decomposednamedtensor_ops = { + "id": adapter.decomposednamedtensor_from_einsum.id(einsum), + "sum": adapter.decomposednamedtensor_from_einsum.sum(einsum), + "multiply": adapter.decomposednamedtensor_from_einsum.multiply(einsum), + "dot": adapter.decomposednamedtensor_from_einsum.dot(einsum), + } + + return decomposednamedtensor_ops, "mlx.einsum" + + +registry.register_on_import("mlx", "mlx.einsum", create_backend_einsum) + + +@_backend_creator +def create_backend_vmap(mlx, classical): + vmap = adapter.vmap_from_mlx(mlx) + elementary_ops = adapter.elementary_from_classical.ops(classical) + + decomposednamedtensor_ops = { + name: adapter.decomposednamedtensor_from_vmap.op( + elementary_ops[name], vmap, expected_type=mlx.core.array, allow_squeeze_unsqueeze=True, classical=classical + ) + for name in adapter.ops.all + } | {name: _unsupported_op(name, "mlx.vmap") for name in adapter.ops.update_at} + + return decomposednamedtensor_ops, "mlx.vmap" + + +registry.register_on_import("mlx", "mlx.vmap", create_backend_vmap) + + +def create_backend(): + einx_ops_numpylike = create_backend_numpylike().ops + einx_ops_einsum = create_backend_einsum().ops + einx_ops = einx_ops_numpylike | {"dot": einx_ops_einsum["dot"]} + + return Backend(ops=einx_ops, name="mlx", priority=0, **_get_backend_kwargs()) + + +registry.register_on_import("mlx", "mlx", create_backend) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/numpy.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..91450e01874b44459fc8cb1dd34bde5a9073d49f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/numpy.py @@ -0,0 +1,132 @@ +from ..backend import registry +from ..backend import Backend +import einx._src.adapter as adapter +import einx._src.tracer as tracer +from ._util import _make_iskwarg +from ._util import _unsupported_op +from ..api import api +import types +from ._docs import _make_doc_adapt_numpylike_reduce +from ._docs import _make_doc_adapt_numpylike_elementwise + + +def _get_backend_kwargs(): + np = tracer.signature.python.import_("numpy", as_="np") + optimizations = [ + tracer.optimizer.classical.SkipReshape(np.reshape), + tracer.optimizer.classical.SkipTranspose(np.transpose), + tracer.optimizer.classical.SkipBroadcastTo(np.broadcast_to), + tracer.optimizer.classical.SkipConcatenate(np.concatenate), + tracer.optimizer.InlineGraph(), + tracer.optimizer.SkipCast(), + ] + + import numpy as np + + def is_supported_tensor(tensor): + return isinstance(tensor, np.ndarray) + + def get_shape(tensor): + return tuple(int(x) for x in tensor.shape) + + return {"optimizations": optimizations, "compiler": tracer.compiler.python, "is_supported_tensor": is_supported_tensor, "get_shape": get_shape} + + +def adapt_numpylike_reduce(op): + iskwarg = lambda name, iskwarg=_make_iskwarg(op): name != "axis" and iskwarg(name) + np = tracer.signature.numpy() + + classical = adapter.classical_from_numpy.ops(np) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.reduce(op, expected_type=np.ndarray) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=np.ndarray) + op = adapter.einx_from_namedtensor.reduce(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_reduce.__doc__ = _make_doc_adapt_numpylike_reduce() + + +def adapt_numpylike_elementwise(op): + iskwarg = _make_iskwarg(op) + np = tracer.signature.numpy() + + classical = adapter.classical_from_numpy.ops(np) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.elementwise(op, classical, expected_type=np.ndarray) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=np.ndarray) + op = adapter.einx_from_namedtensor.elementwise(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_elementwise.__doc__ = _make_doc_adapt_numpylike_elementwise() + + +def _backend_creator(create): + def new_create(): + numpy = tracer.signature.numpy() + classical = adapter.classical_from_numpy.ops(numpy) + + decomposednamedtensor_ops, name = create(numpy, classical) + + namedtensor_ops = adapter.namedtensor_from_decomposednamedtensor.ops(decomposednamedtensor_ops, classical) + namedtensor_ops = adapter.namedtensor_calltensorfactory.ops(namedtensor_ops, expected_type=numpy.ndarray) + einx_ops = adapter.einx_from_namedtensor.ops(namedtensor_ops) + + return Backend(ops=einx_ops, name=name, priority=-5, **_get_backend_kwargs()) + + return new_create + + +@_backend_creator +def create_backend_numpylike(numpy, classical): + decomposednamedtensor_ops = ( + {name: adapter.decomposednamedtensor_from_classical.elementwise(getattr(classical, name), classical) for name in adapter.ops.elementwise} + | {name: adapter.decomposednamedtensor_from_classical.reduce(getattr(classical, name)) for name in adapter.ops.reduce} + | {name: adapter.decomposednamedtensor_from_classical.preserve_shape(getattr(classical, name)) for name in adapter.ops.preserve_shape} + | {name: adapter.decomposednamedtensor_from_classical.argfind(getattr(classical, name), classical) for name in adapter.ops.argfind} + | {name: adapter.decomposednamedtensor_from_classical.update_at_ravelled(getattr(classical, name), classical) for name in adapter.ops.update_at} + | { + "get_at": adapter.decomposednamedtensor_from_classical.get_at_ravelled(classical), + "dot": adapter.decomposednamedtensor_from_classical.dot(classical), + } + ) + + return decomposednamedtensor_ops, "numpy.numpylike" + + +registry.register_on_import("numpy", "numpy.numpylike", create_backend_numpylike) + + +@_backend_creator +def create_backend_einsum(numpy, classical): + einsum = adapter.einsum_from_numpy(numpy) + + decomposednamedtensor_ops = { + "id": adapter.decomposednamedtensor_from_einsum.id(einsum), + "sum": adapter.decomposednamedtensor_from_einsum.sum(einsum), + "multiply": adapter.decomposednamedtensor_from_einsum.multiply(einsum), + "dot": adapter.decomposednamedtensor_from_einsum.dot(einsum), + } + + return decomposednamedtensor_ops, "numpy.einsum" + + +registry.register_on_import("numpy", "numpy.einsum", create_backend_einsum) + + +def create_backend(): + einx_ops_numpylike = create_backend_numpylike().ops + einx_ops_einsum = create_backend_einsum().ops + einx_ops = einx_ops_numpylike | {"dot": einx_ops_einsum["dot"]} + + return Backend(ops=einx_ops, name="numpy", priority=-1, **_get_backend_kwargs()) + + +registry.register_on_import("numpy", "numpy", create_backend) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/tensorflow.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..2a9a44a9d8ba3ae80ac040502b7bebb8e9831efb --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/tensorflow.py @@ -0,0 +1,136 @@ +import einx._src.tracer as tracer +import einx._src.adapter as adapter +from ..api import api +from ..types import Tensor +import types +import inspect +import functools +from functools import partial +from ..backend import registry +from ..backend import Backend +from ._util import _make_iskwarg +from ._docs import _make_doc_adapt_numpylike_reduce +from ._docs import _make_doc_adapt_numpylike_elementwise + + +def _get_backend_kwargs(): + tf = tracer.signature.python.import_("tensorflow", as_="tf") + optimizations = [ + tracer.optimizer.classical.SkipReshape(tf.reshape), + tracer.optimizer.classical.SkipTranspose(tf.transpose), + tracer.optimizer.classical.SkipBroadcastTo(tf.broadcast_to), + tracer.optimizer.classical.SkipConcatenate(tf.concat), + tracer.optimizer.InlineGraph(), + tracer.optimizer.SkipCast(), + ] + + import tensorflow as tf + + def is_supported_tensor(tensor): + return isinstance(tensor, tf.Tensor) + + def get_shape(tensor): + return tuple(int(x) for x in tensor.shape) + + return {"optimizations": optimizations, "compiler": tracer.compiler.python, "is_supported_tensor": is_supported_tensor, "get_shape": get_shape} + + +def adapt_numpylike_reduce(op): + iskwarg = lambda name, iskwarg=_make_iskwarg(op): name != "axis" and iskwarg(name) + tf = tracer.signature.tensorflow() + + classical = adapter.classical_from_tensorflow.ops(tf) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.reduce(op, expected_type=tf.Tensor) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=tf.Tensor) + op = adapter.einx_from_namedtensor.reduce(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_reduce.__doc__ = _make_doc_adapt_numpylike_reduce() + + +def adapt_numpylike_elementwise(op): + iskwarg = lambda name, iskwarg=_make_iskwarg(op): name != "axis" and iskwarg(name) + tf = tracer.signature.tensorflow() + + classical = adapter.classical_from_tensorflow.ops(tf) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.elementwise(op, classical, expected_type=tf.Tensor) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=tf.Tensor) + op = adapter.einx_from_namedtensor.elementwise(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_elementwise.__doc__ = _make_doc_adapt_numpylike_elementwise() + + +def _backend_creator(create): + def new_create(): + tf = tracer.signature.tensorflow() + + classical = adapter.classical_from_tensorflow.ops(tf) + + decomposednamedtensor_ops, name = create(tf, classical) + + namedtensor_ops = adapter.namedtensor_from_decomposednamedtensor.ops(decomposednamedtensor_ops, classical) + namedtensor_ops = adapter.namedtensor_calltensorfactory.ops(namedtensor_ops, expected_type=tf.Tensor) + einx_ops = adapter.einx_from_namedtensor.ops(namedtensor_ops) + + return Backend(ops=einx_ops, name=name, priority=-5, **_get_backend_kwargs()) + + return new_create + + +@_backend_creator +def create_backend_numpylike(tf, classical): + decomposednamedtensor_ops = ( + {name: adapter.decomposednamedtensor_from_classical.elementwise(getattr(classical, name), classical) for name in adapter.ops.elementwise} + | {name: adapter.decomposednamedtensor_from_classical.reduce(getattr(classical, name)) for name in adapter.ops.reduce} + | {name: adapter.decomposednamedtensor_from_classical.preserve_shape(getattr(classical, name)) for name in adapter.ops.preserve_shape} + | {name: adapter.decomposednamedtensor_from_classical.argfind(getattr(classical, name), classical) for name in adapter.ops.argfind} + | {name: adapter.decomposednamedtensor_from_classical.update_at_ravelled(getattr(classical, name), classical) for name in adapter.ops.update_at} + | { + "get_at": adapter.decomposednamedtensor_from_classical.get_at_ravelled(classical), + "dot": adapter.decomposednamedtensor_from_classical.dot(classical), + } + ) + + return decomposednamedtensor_ops, "tensorflow.numpylike" + + +registry.register_on_import("tensorflow", "tensorflow.numpylike", create_backend_numpylike) + + +@_backend_creator +def create_backend_einsum(tf, classical): + einsum = adapter.einsum_from_tensorflow(tf) + + decomposednamedtensor_ops = { + "id": adapter.decomposednamedtensor_from_einsum.id(einsum), + "sum": adapter.decomposednamedtensor_from_einsum.sum(einsum), + "multiply": adapter.decomposednamedtensor_from_einsum.multiply(einsum), + "dot": adapter.decomposednamedtensor_from_einsum.dot(einsum), + } + + return decomposednamedtensor_ops, "tensorflow.einsum" + + +registry.register_on_import("tensorflow", "tensorflow.einsum", create_backend_einsum) + + +def create_backend(): + einx_ops_numpylike = create_backend_numpylike().ops + einx_ops_einsum = create_backend_einsum().ops + einx_ops = einx_ops_numpylike | {"dot": einx_ops_einsum["dot"]} + + return Backend(ops=einx_ops, name="tensorflow", priority=0, **_get_backend_kwargs()) + + +registry.register_on_import("tensorflow", "tensorflow", create_backend) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/tinygrad.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/tinygrad.py new file mode 100644 index 0000000000000000000000000000000000000000..ab93324f48b8d57ecb2ee09dc016cb199610d9f9 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/tinygrad.py @@ -0,0 +1,136 @@ +import einx._src.tracer as tracer +import einx._src.adapter as adapter +from ..api import api +from ..types import Tensor +import types +import inspect +import functools +from functools import partial +from ..backend import registry +from ..backend import Backend +from ._util import _make_iskwarg +from ._docs import _make_doc_adapt_numpylike_reduce +from ._docs import _make_doc_adapt_numpylike_elementwise + + +def _get_backend_kwargs(): + tinygrad = tracer.signature.python.import_("tinygrad") + optimizations = [ + tracer.optimizer.classical.SkipReshape(tinygrad.reshape), + tracer.optimizer.classical.SkipTranspose(tinygrad.permute), + tracer.optimizer.classical.SkipBroadcastTo(tinygrad.expand), + tracer.optimizer.classical.SkipConcatenate(tinygrad.cat), + tracer.optimizer.InlineGraph(), + tracer.optimizer.SkipCast(), + ] + + import tinygrad + + def is_supported_tensor(tensor): + return isinstance(tensor, tinygrad.Tensor) + + def get_shape(tensor): + return tuple(int(x) for x in tensor.shape) + + return {"optimizations": optimizations, "compiler": tracer.compiler.python, "is_supported_tensor": is_supported_tensor, "get_shape": get_shape} + + +def adapt_numpylike_reduce(op): + iskwarg = lambda name, iskwarg=_make_iskwarg(op): name != "axis" and iskwarg(name) + tinygrad = tracer.signature.tinygrad() + + classical = adapter.classical_from_tinygrad.ops(tinygrad) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.reduce(op, expected_type=tinygrad.Tensor) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=tinygrad.Tensor) + op = adapter.einx_from_namedtensor.reduce(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_reduce.__doc__ = _make_doc_adapt_numpylike_reduce() + + +def adapt_numpylike_elementwise(op): + iskwarg = lambda name, iskwarg=_make_iskwarg(op): name != "axis" and iskwarg(name) + tinygrad = tracer.signature.tinygrad() + + classical = adapter.classical_from_tinygrad.ops(tinygrad) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.elementwise(op, classical, expected_type=tinygrad.Tensor) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=tinygrad.Tensor) + op = adapter.einx_from_namedtensor.elementwise(op, iskwarg=iskwarg) + + return api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + + +adapt_numpylike_elementwise.__doc__ = _make_doc_adapt_numpylike_elementwise() + + +def _backend_creator(create): + def new_create(): + tinygrad = tracer.signature.tinygrad() + + classical = adapter.classical_from_tinygrad.ops(tinygrad) + + decomposednamedtensor_ops, name = create(tinygrad, classical) + + namedtensor_ops = adapter.namedtensor_from_decomposednamedtensor.ops(decomposednamedtensor_ops, classical) + namedtensor_ops = adapter.namedtensor_calltensorfactory.ops(namedtensor_ops, expected_type=tinygrad.Tensor) + einx_ops = adapter.einx_from_namedtensor.ops(namedtensor_ops) + + return Backend(ops=einx_ops, name=name, priority=-5, **_get_backend_kwargs()) + + return new_create + + +@_backend_creator +def create_backend_numpylike(tinygrad, classical): + decomposednamedtensor_ops = ( + {name: adapter.decomposednamedtensor_from_classical.elementwise(getattr(classical, name), classical) for name in adapter.ops.elementwise} + | {name: adapter.decomposednamedtensor_from_classical.reduce(getattr(classical, name)) for name in adapter.ops.reduce} + | {name: adapter.decomposednamedtensor_from_classical.preserve_shape(getattr(classical, name)) for name in adapter.ops.preserve_shape} + | {name: adapter.decomposednamedtensor_from_classical.argfind(getattr(classical, name), classical) for name in adapter.ops.argfind} + | {name: adapter.decomposednamedtensor_from_classical.update_at_ravelled(getattr(classical, name), classical) for name in adapter.ops.update_at} + | { + "get_at": adapter.decomposednamedtensor_from_classical.get_at_ravelled(classical), + "dot": adapter.decomposednamedtensor_from_classical.dot(classical), + } + ) + + return decomposednamedtensor_ops, "tinygrad.numpylike" + + +registry.register_on_import("tinygrad", "tinygrad.numpylike", create_backend_numpylike) + + +@_backend_creator +def create_backend_einsum(tinygrad, classical): + einsum = adapter.einsum_from_tinygrad(tinygrad) + + decomposednamedtensor_ops = { + "id": adapter.decomposednamedtensor_from_einsum.id(einsum), + "sum": adapter.decomposednamedtensor_from_einsum.sum(einsum), + "multiply": adapter.decomposednamedtensor_from_einsum.multiply(einsum), + "dot": adapter.decomposednamedtensor_from_einsum.dot(einsum), + } + + return decomposednamedtensor_ops, "tinygrad.einsum" + + +registry.register_on_import("tinygrad", "tinygrad.einsum", create_backend_einsum) + + +def create_backend(): + einx_ops_numpylike = create_backend_numpylike().ops + einx_ops_einsum = create_backend_einsum().ops + einx_ops = einx_ops_numpylike | {"dot": einx_ops_einsum["dot"]} + + return Backend(ops=einx_ops, name="tinygrad", priority=0, **_get_backend_kwargs()) + + +registry.register_on_import("tinygrad", "tinygrad", create_backend) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/torch.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/torch.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6e9e053e33d10eff31461bd934a6a7b5fe17e7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/impl/torch.py @@ -0,0 +1,249 @@ +import einx._src.tracer as tracer +import einx._src.adapter as adapter +from ..api import api +import types +import inspect +import functools +from functools import partial +from ..backend import registry +from ..backend import Backend +from einx._src.frontend.errors import ImportBackendError +import threading +from ._util import _make_iskwarg, _unsupported_op +from ._docs import _make_doc_adapt_numpylike_reduce +from ._docs import _make_doc_adapt_numpylike_elementwise +from ._docs import _make_doc_adapt_with_vmap + + +def _raise_on_invalid_version(): + import torch + + version = tuple(int(i) for i in torch.__version__.split(".")[:2]) + if version < (2, 2): + raise ImportBackendError(f"einx with PyTorch requires PyTorch version >= 2.2, but found {torch.__version__}. einx functions are disabled for PyTorch.") + + +_has_allowed_in_graph = False +_has_allowed_in_graph_lock = threading.Lock() + + +def _allow_ops_in_graph(): + global _has_allowed_in_graph + if not _has_allowed_in_graph: + with _has_allowed_in_graph_lock: + if not _has_allowed_in_graph: + import torch + from einx._src.frontend.ops import ops + + for op in ops: + torch.compiler.allow_in_graph(op) + _has_allowed_in_graph = True + + +def _get_backend_kwargs(): + torch = tracer.signature.python.import_("torch") + optimizations = [ + tracer.optimizer.classical.SkipReshape(torch.reshape), + tracer.optimizer.classical.SkipTranspose(torch.permute), + tracer.optimizer.classical.SkipBroadcastTo(torch.broadcast_to), + tracer.optimizer.classical.SkipConcatenate(torch.cat), + tracer.optimizer.InlineGraph(), + tracer.optimizer.SkipCast(), + ] + + import torch + + def is_supported_tensor(tensor): + return isinstance(tensor, torch.Tensor) + + def get_shape(tensor): + return tuple(int(x) for x in tensor.shape) + + return {"optimizations": optimizations, "compiler": tracer.compiler.python, "is_supported_tensor": is_supported_tensor, "get_shape": get_shape} + + +def adapt_with_vmap(op, signature=None): + _raise_on_invalid_version() + iskwarg = _make_iskwarg(op) + + device_stack = adapter.TorchDeviceStack() + + torch = tracer.signature.torch() + + classical = adapter.classical_from_torch.ops(torch, get_device=device_stack.get_device) + vmap = adapter.vmap_from_torch(torch, get_device=device_stack.get_device) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_vmap.op(op, vmap, expected_type=torch.Tensor) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = device_stack.namedtensor.op(op) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=torch.Tensor) + op = adapter.einx_from_namedtensor.op(op, iskwarg=iskwarg, el_op=signature, implicit_output="bijective") + + op = api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + import torch + + torch.compiler.allow_in_graph(op) + + return op + + +adapt_with_vmap.__doc__ = _make_doc_adapt_with_vmap("torch", "``torch.vmap``") + + +def adapt_numpylike_reduce(op): + _raise_on_invalid_version() + iskwarg = lambda name, iskwarg=_make_iskwarg(op): name != "axis" and iskwarg(name) + + device_stack = adapter.TorchDeviceStack() + + torch = tracer.signature.torch() + + classical = adapter.classical_from_torch.ops(torch, get_device=device_stack.get_device) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.reduce(op, expected_type=torch.Tensor) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = device_stack.namedtensor.op(op) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=torch.Tensor) + op = adapter.einx_from_namedtensor.reduce(op, iskwarg=iskwarg) + + op = api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + import torch + + torch.compiler.allow_in_graph(op) + + return op + + +adapt_numpylike_reduce.__doc__ = _make_doc_adapt_numpylike_reduce() + + +def adapt_numpylike_elementwise(op): + _raise_on_invalid_version() + iskwarg = _make_iskwarg(op) + + device_stack = adapter.TorchDeviceStack() + + torch = tracer.signature.torch() + + classical = adapter.classical_from_torch.ops(torch, get_device=device_stack.get_device) + + op = tracer.signature.python.constant(op) + op = adapter.decomposednamedtensor_from_classical.elementwise(op, classical, expected_type=torch.Tensor) + op = adapter.namedtensor_from_decomposednamedtensor.op(op, classical) + op = device_stack.namedtensor.op(op) + op = adapter.namedtensor_calltensorfactory.op(op, expected_type=torch.Tensor) + op = adapter.einx_from_namedtensor.elementwise(op, iskwarg=iskwarg) + + op = api(op, backend=types.SimpleNamespace(**_get_backend_kwargs())) + import torch + + torch.compiler.allow_in_graph(op) + + return op + + +adapt_numpylike_elementwise.__doc__ = _make_doc_adapt_numpylike_elementwise() + + +def _backend_creator(create): + def new_create(): + _raise_on_invalid_version() + _allow_ops_in_graph() + + device_stack = adapter.TorchDeviceStack() + + torch = tracer.signature.torch() + + classical = adapter.classical_from_torch.ops(torch, get_device=device_stack.get_device) + + decomposednamedtensor_ops, name = create(torch, classical, device_stack) + + namedtensor_ops = adapter.namedtensor_from_decomposednamedtensor.ops(decomposednamedtensor_ops, classical) + namedtensor_ops = device_stack.namedtensor.ops(namedtensor_ops) + namedtensor_ops = adapter.namedtensor_calltensorfactory.ops(namedtensor_ops, expected_type=torch.Tensor) + einx_ops = adapter.einx_from_namedtensor.ops(namedtensor_ops) + + return Backend(ops=einx_ops, name=name, priority=-5, **_get_backend_kwargs()) + + return new_create + + +@_backend_creator +def create_backend_numpylike(torch, classical, device_stack): + decomposednamedtensor_ops = ( + {name: adapter.decomposednamedtensor_from_classical.elementwise(getattr(classical, name), classical) for name in adapter.ops.elementwise} + | {name: adapter.decomposednamedtensor_from_classical.reduce(getattr(classical, name)) for name in adapter.ops.reduce} + | {name: adapter.decomposednamedtensor_from_classical.preserve_shape(getattr(classical, name)) for name in adapter.ops.preserve_shape} + | {name: adapter.decomposednamedtensor_from_classical.argfind(getattr(classical, name), classical) for name in adapter.ops.argfind} + | {name: adapter.decomposednamedtensor_from_classical.update_at_ravelled(getattr(classical, name), classical) for name in adapter.ops.update_at} + | { + "get_at": adapter.decomposednamedtensor_from_classical.get_at_ravelled(classical), + "dot": adapter.decomposednamedtensor_from_classical.dot(classical), + } + ) + + return decomposednamedtensor_ops, "torch.numpylike" + + +registry.register_on_import("torch", "torch.numpylike", create_backend_numpylike) + + +@_backend_creator +def create_backend_einsum(torch, classical, device_stack): + einsum = adapter.einsum_from_torch(torch, get_device=device_stack.get_device) + + decomposednamedtensor_ops = { + "id": adapter.decomposednamedtensor_from_einsum.id(einsum), + "sum": adapter.decomposednamedtensor_from_einsum.sum(einsum), + "multiply": adapter.decomposednamedtensor_from_einsum.multiply(einsum), + "dot": adapter.decomposednamedtensor_from_einsum.dot(einsum), + } + + return decomposednamedtensor_ops, "torch.einsum" + + +registry.register_on_import("torch", "torch.einsum", create_backend_einsum) + + +@_backend_creator +def create_backend_vmap(torch, classical, device_stack): + vmap = adapter.vmap_from_torch(torch, get_device=device_stack.get_device) + + elementary_ops = adapter.elementary_from_classical.ops(classical) + + get_at_error_message = ( + "get_at is not supported by the torch.vmap backend. As of testing this, " + "torch.vmap is not compatible with scalar indexing operations and raises the following error:\n\"vmap: It looks like you're calling " + ".item() on a Tensor. We don't support vmap over calling .item() on a Tensor, please try to rewrite what you're doing with other operations. " + 'If error is occurring somewhere inside PyTorch internals, please file a bug report."\n' + "Please use another PyTorch backend for this operation." + ) + + decomposednamedtensor_ops = ( + { + name: adapter.decomposednamedtensor_from_vmap.op( + elementary_ops[name], vmap, expected_type=torch.Tensor, allow_squeeze_unsqueeze=True, classical=classical + ) + for name in adapter.ops.all + } + | {"get_at": _unsupported_op("get_at", "torch.vmap", get_at_error_message)} + | {name: _unsupported_op(name, "torch.vmap") for name in adapter.ops.update_at} + ) + + return decomposednamedtensor_ops, "torch.vmap" + + +registry.register_on_import("torch", "torch.vmap", create_backend_vmap) + + +def create_backend(): + einx_ops_numpylike = create_backend_numpylike().ops + einx_ops_einsum = create_backend_einsum().ops + einx_ops = einx_ops_numpylike | {"dot": einx_ops_einsum["dot"]} + + return Backend(ops=einx_ops, name="torch", priority=0, **_get_backend_kwargs()) + + +registry.register_on_import("torch", "torch", create_backend) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/ops.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..bb8221dae524a6619fc734b03409caa94fada7f9 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/ops.py @@ -0,0 +1,721 @@ +from .api import api +from .types import Tensor +from .backend import Backend +import numpy.typing as npt +from typing import Any +import warnings + + +def _args_return(single, kwargs=""): + s = "" if single else "s" + ies = "y" if single else "ies" + return f"""Args: + description: Description string for the operation in einx notation. + {"tensor" if single else "*tensors"}: Input tensor{s} or tensor factor{ies} matching the description string. + backend: Backend to use for all operations. If None, uses the :doc:`default backend ` for the given setting. Defaults to None. + graph: Whether to return the compiled code representation of this operation instead of + computing the result. Defaults to False. + {kwargs} + **parameters: Additional parameters that specify dimension sizes, e.g. ``a=4``. + +Returns: + The result of the operation if ``graph=False``, otherwise the compiled code + representation of the operation. +""" + + +@api +def id(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Any: # Tensor | tuple[Tensor, ...]: + return backend.id(description, *tensors, **parameters) + + +id.__doc__ = f"""Compute the identity-map of values in the given tensor. + +In the simplest case, the elementary operation has the signature ``[] -> []`` and returns the input as-is. If there are more than one +input/ output or concatenated inputs/ outputs, the ordered tuple of inputs is returned as-is. + +{_args_return(False)} +""" + + +def _make_reduction_doc(op, line1, output): + return f"""{line1}. + +The elementary operation has the signature ``[...] -> []`` and {output}. + +If there is no output expression, it is determined implicitly by removing all bracketed expressions from the input expression. +For example, the following operations compute the same output: + +.. code-block:: python + + y = einx.{op}("a [b]", x) + y = einx.{op}("a [b] -> a", x) + +If there are no brackets in the expression, brackets are implicitly placed around all axes that do not appear in the output expression. +For example, the following operations compute the same output: + +.. code-block:: python + + y = einx.{op}("a b -> a", x) + y = einx.{op}("a [b] -> a", x) + +{_args_return(True)} +""" + + +def _keepdims_warning(keepdims): + if keepdims is not None: + warnings.warn( + "The 'keepdims' argument in einx reduction operations is deprecated and will be removed in a future version. " + "Please use a flattened axis instead.\nFor example, instead of\n\n" + ' einx.{op}("a [b]", x, keepdims=True)\n\nwrite\n\n einx.{op}("a ([b])", x).\n', + DeprecationWarning, + stacklevel=6, + ) + + +@api +def sum(description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + _keepdims_warning(keepdims) + return backend.sum(description, tensor, keepdims=keepdims, **parameters) + + +sum.__doc__ = _make_reduction_doc("sum", "Compute the sum of values in the given tensor", "computes the sum of all values of the input tensor") + + +@api +def mean(description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + _keepdims_warning(keepdims) + return backend.mean(description, tensor, keepdims=keepdims, **parameters) + + +mean.__doc__ = _make_reduction_doc("mean", "Compute the mean of values in the given tensor", "computes the mean of all values of the input tensor") + + +@api +def var(description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + _keepdims_warning(keepdims) + return backend.var(description, tensor, keepdims=keepdims, **parameters) + + +var.__doc__ = _make_reduction_doc("var", "Compute the variance of values in the given tensor", "computes the variance of all values of the input tensor") + + +@api +def std(description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + _keepdims_warning(keepdims) + return backend.std(description, tensor, keepdims=keepdims, **parameters) + + +std.__doc__ = _make_reduction_doc( + "std", "Compute the standard deviation of values in the given tensor", "computes the standard deviation of all values of the input tensor" +) + + +@api +def prod(description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + _keepdims_warning(keepdims) + return backend.prod(description, tensor, keepdims=keepdims, **parameters) + + +prod.__doc__ = _make_reduction_doc("prod", "Compute the product of values in the given tensor", "computes the product of all values of the input tensor") + + +@api +def count_nonzero( + description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike +) -> Tensor: + _keepdims_warning(keepdims) + return backend.count_nonzero(description, tensor, keepdims=keepdims, **parameters) + + +count_nonzero.__doc__ = _make_reduction_doc( + "count_nonzero", "Counts non-zero values in the given tensor", "counts the number of all non-zero values of the input tensor" +) + + +@api +def any(description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + _keepdims_warning(keepdims) + return backend.any(description, tensor, keepdims=keepdims, **parameters) + + +any.__doc__ = _make_reduction_doc( + "any", "Compute the logical disjunction (OR) of values in the given tensor", "computes the logical disjunction (OR) of all values of the input tensor" +) + + +@api +def all(description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + _keepdims_warning(keepdims) + return backend.all(description, tensor, keepdims=keepdims, **parameters) + + +all.__doc__ = _make_reduction_doc( + "all", "Compute the logical conjunction (AND) of values in the given tensor", "computes the logical conjunction (AND) of all values of the input tensor" +) + + +@api +def max(description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + _keepdims_warning(keepdims) + return backend.max(description, tensor, keepdims=keepdims, **parameters) + + +max.__doc__ = _make_reduction_doc("max", "Compute the maximum of values in the given tensor", "computes the maximum of all values of the input tensor") + + +@api +def min(description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + _keepdims_warning(keepdims) + return backend.min(description, tensor, keepdims=keepdims, **parameters) + + +min.__doc__ = _make_reduction_doc("min", "Compute the minimum of values in the given tensor", "computes the minimum of all values of the input tensor") + + +@api +def logsumexp(description: str, tensor: Tensor, *, keepdims: bool | None = None, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + _keepdims_warning(keepdims) + return backend.logsumexp(description, tensor, keepdims=keepdims, **parameters) + + +logsumexp.__doc__ = _make_reduction_doc( + "logsumexp", "Compute the log-sum-exp of values in the given tensor", "computes the log-sum-exp of all values of the input tensor" +) + + +@api +def dot(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.dot(description, *tensors, **parameters) + + +dot.__doc__ = f"""Compute the dot-product of values in the given tensors. + +In the simplest case, the elementary operation has the signature ``[a], [a] -> []`` and computes the dot-product over the two input vectors. +If more than two tensors or more than two axes are passed to the elementary operation, the dot-product is applied sequentially in an unspecified +order to all pairs of dimensions with the same name. + +If there are no brackets in the expression, brackets are placed implicitly around all axes that do not appear in the output expression. For example, +the following operations compute the same output: + +.. code-block:: python + + z = einx.dot("a b, b c -> a c", x, y) + z = einx.dot("a [b], [b] c -> a c", x, y) + +{_args_return(False)} + """ + + +def _make_elwise_doc(op, line1, output, nargs): + if nargs == 2: + code = f""" + z = einx.{op}("a b, a", x, y) + z = einx.{op}("a b, a -> a b", x, y) + + z = einx.{op}("a b, a b", x, y) + z = einx.{op}("a b, a b -> a b", x, y) + + z = einx.{op}("a b, b a", x, y) + # raises an exception due to ambiguous output expression +""" + elif nargs == 3: + code = f""" + w = einx.{op}("a b, a, b", x, y, z) + w = einx.{op}("a b, a, b -> a b", x, y, z) + + w = einx.{op}("a b, a b, a b", x, y, z) + w = einx.{op}("a b, a b, a b -> a b", x, y, z) + + w = einx.{op}("a b, b a, a b", x, y, z) + # raises an exception due to ambiguous output expression +""" + else: + raise ValueError("Invalid nargs") + + return f"""{line1}. + +The elementary operation {output}. + +If there is no output expression, one of the input expressions is implicitly used as output expression if it contains the axis names of all other +inputs and if this choice is unique. For example, the following pairs of operations compute the same output: + +.. code-block:: python + + {code} + +{_args_return(False)} +""" + + +@api +def add(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.add(description, *tensors, **parameters) + + +add.__doc__ = _make_elwise_doc("add", "Compute the sum of values of multiple given tensors", "takes any number of scalars as input and returns their sum", 2) + + +@api +def subtract(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.subtract(description, *tensors, **parameters) + + +subtract.__doc__ = _make_elwise_doc( + "subtract", "Computes the difference between values of two given tensors", "takes two scalars as input and subtracts the second from the first", 2 +) + + +@api +def multiply(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.multiply(description, *tensors, **parameters) + + +multiply.__doc__ = _make_elwise_doc( + "multiply", "Compute the product of values of multiple given tensors", "takes any number of scalars as input and returns their product", 2 +) + + +@api +def true_divide(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.true_divide(description, *tensors, **parameters) + + +true_divide.__doc__ = _make_elwise_doc( + "true_divide", "Computes the true division between values of two given tensors", "takes two scalars as input and divides the first by the second", 2 +) + + +@api +def floor_divide(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.floor_divide(description, *tensors, **parameters) + + +floor_divide.__doc__ = _make_elwise_doc( + "floor_divide", "Computes the floor division between values of two given tensors", "takes two scalars as input and divides the first by the second", 2 +) + + +@api +def divide(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.divide(description, *tensors, **parameters) + + +divide.__doc__ = _make_elwise_doc( + "divide", "Computes the division between values of two given tensors", "takes two scalars as input and divides the first by the second", 2 +) + + +@api +def logical_and(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.logical_and(description, *tensors, **parameters) + + +logical_and.__doc__ = _make_elwise_doc( + "logical_and", + "Compute the logical conjunction (AND) of values of multiple given tensors", + "takes any number of scalars as input and returns their logical conjunction (AND)", + 2, +) + + +@api +def logical_or(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.logical_or(description, *tensors, **parameters) + + +logical_or.__doc__ = _make_elwise_doc( + "logical_or", + "Compute the logical disjunction (OR) of values of multiple given tensors", + "takes any number of scalars as input and returns their logical disjunction (OR)", + 2, +) + + +@api +def where(description: str, mask: Tensor, x: Tensor, y: Tensor, *, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.where(description, mask, x, y, **parameters) + + +where.__doc__ = _make_elwise_doc( + "where", + "Conditionally select values from two tensors based on a boolean mask", + "takes three scalars as input (mask, true_val, false_val) and returns true_val if mask is true, otherwise false_val", + 3, +) + + +@api +def maximum(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.maximum(description, *tensors, **parameters) + + +maximum.__doc__ = _make_elwise_doc( + "maximum", "Compute the maximum of values of multiple given tensors", "takes any number of scalars as input and returns their maximum", 2 +) + + +@api +def minimum(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.minimum(description, *tensors, **parameters) + + +minimum.__doc__ = _make_elwise_doc( + "minimum", "Compute the minimum of values of multiple given tensors", "takes any number of scalars as input and returns their minimum", 2 +) + + +@api +def less(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.less(description, *tensors, **parameters) + + +less.__doc__ = _make_elwise_doc( + "less", + "Computes the less-than comparison between values of two given tensors", + "takes two scalars as input and returns true if the first is less than the second, otherwise false", + 2, +) + + +@api +def less_equal(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.less_equal(description, *tensors, **parameters) + + +less_equal.__doc__ = _make_elwise_doc( + "less_equal", + "Computes the less-than-or-equal comparison between values of two given tensors", + "takes two scalars as input and returns true if the first is less than or equal to the second, otherwise false", + 2, +) + + +@api +def greater(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.greater(description, *tensors, **parameters) + + +greater.__doc__ = _make_elwise_doc( + "greater", + "Computes the greater-than comparison between values of two given tensors", + "takes two scalars as input and returns true if the first is greater than the second, otherwise false", + 2, +) + + +@api +def greater_equal(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.greater_equal(description, *tensors, **parameters) + + +greater_equal.__doc__ = _make_elwise_doc( + "greater_equal", + "Computes the greater-than-or-equal comparison between values of two given tensors", + "takes two scalars as input and returns true if the first is greater than or equal to the second, otherwise false", + 2, +) + + +@api +def equal(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.equal(description, *tensors, **parameters) + + +equal.__doc__ = _make_elwise_doc( + "equal", + "Computes the equality comparison between values of two given tensors", + "takes two scalars as input and returns true if they are equal, otherwise false", + 2, +) + + +@api +def not_equal(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.not_equal(description, *tensors, **parameters) + + +not_equal.__doc__ = _make_elwise_doc( + "equal", + "Computes the non-equality comparison between values of two given tensors", + "takes two scalars as input and returns false if they are equal, otherwise true", + 2, +) + + +@api +def logaddexp(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.logaddexp(description, *tensors, **parameters) + + +logaddexp.__doc__ = _make_elwise_doc( + "logaddexp", "Compute the log-sum-exp of values of multiple given tensors", "takes any number of scalars as input and returns their log-sum-exp", 2 +) + + +@api +def get_at(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.get_at(description, *tensors, **parameters) + + +get_at.__doc__ = f"""Retrieves values from a tensor at the coordinates specified by another tensor. + +The elementary operation has the signature ``[...] , [n] -> []``. The first argument is the n-dimensional value tensor, the second argument +specifies a single n-dimensional coordinate, and the result is the value at that coordinate. + +For 1-dimensional value tensors, the elementary operation also accepts the signature ``[...] , [] -> []``. For example, the following two +operations compute the same output: + +.. code-block:: python + + y = einx.get_at("[h], p [1] -> p", x, idx) + y = einx.get_at("[h], p -> p", x, idx[:, 0]) + +The elementary operation also accepts multiple coordinate tensors as input, in which case they are concatenated first. The length of the resulting +coordinate vector must equal the number of dimensions of the value tensor. For example, the following two operations compute the same output: + +.. code-block:: python + + y = einx.get_at("[a b c d], p [n] -> p", x, idx) + y = einx.get_at("[a b c d], p, p [2], p [1] -> p", x, idx[:, 0], idx[:, 1:3], idx[:, 3:4]) + +{_args_return(False)} +""" + + +def _update_at_doc(op, line1, value1, value2): + return f"""{line1} at the coordinates specified by an indexing tensor. + +The elementary operation has the signature ``[...] , [n], [] -> [...]``. The first argument is the n-dimensional value tensor, the second argument +specifies a single n-dimensional coordinate, the third argument is the {value1} value, and the result is the value tensor with the value {value2} +at that coordinate. + +For 1-dimensional value tensors, the elementary operation also accepts the signature ``[...] , [], [] -> []``. For example, the following two +operations compute the same output: + +.. code-block:: python + + y = einx.{op}("p [h], p [1], p -> p [h]", x, idx, update) + y = einx.{op}("p [h], p, p -> p [h]", x, idx[:, 0], update) + +The elementary operation also accepts multiple coordinate tensors as input, in which case they are concatenated first. The length of the resulting +coordinate vector must equal the number of dimensions of the value tensor. The update tensor always is the last argument. +For example, the following two operations compute the same output: + +.. code-block:: python + + y = einx.{op}("p [a b c d], p [n], p -> p", x, idx, update) + y = einx.{op}("p [a b c d], p, p [2], p [1], p -> p", x, idx[:, 0], idx[:, 1:3], idx[:, 3:4], update) + +If no output expression is given, it is implicitly chosen to be the same as the input expression of the value tensor. For example, +the following two operations compute the same output: + +.. code-block:: python + + y = einx.{op}("b [h w] c, b p [2], b p c", x, idx, update) + y = einx.{op}("b [h w] c, b p [2], b p c -> b [h w] c", x, idx, update) + +The order in which the updates are applied depends on the chosen backend. The operation also may or may not update the target tensor inplace. +Please check by inspecting the code representation (by passing ``graph=True``). + +{_args_return(False)} + """ + + +@api +def set_at(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.set_at(description, *tensors, **parameters) + + +set_at.__doc__ = _update_at_doc("set_at", "Sets values in a target tensor from an update tensor", "new", "overwritten") + + +@api +def add_at(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.add_at(description, *tensors, **parameters) + + +add_at.__doc__ = _update_at_doc("add_at", "Adds values from an update tensor to a target tensor", "added", "added") + + +@api +def subtract_at(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.subtract_at(description, *tensors, **parameters) + + +subtract_at.__doc__ = _update_at_doc("subtract_at", "Subtracts values from a target tensor by an update tensor", "subtracted", "subtracted") + + +@api +def softmax(description: str, tensor: Tensor, *, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.softmax(description, tensor, **parameters) + + +softmax.__doc__ = f"""Compute the softmax of values in the given tensor. + +The elementary operation has the signature ``[...] -> [...]`` and computes the softmax over all input values. + +If there is no output expression, it is chosen to be the same as the input expression. For example, the following operations compute the same output: + +.. code-block:: python + + y = einx.softmax("a [b]", x) + y = einx.softmax("a [b] -> a [b]", x) + +{_args_return(True)} +""" + + +@api +def log_softmax(description: str, tensor: Tensor, *, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.log_softmax(description, tensor, **parameters) + + +log_softmax.__doc__ = f"""Compute the log-softmax of values in the given tensor. + +The elementary operation has the signature ``[...] -> [...]`` and computes the log-softmax over all input values. + +If there is no output expression, it is chosen to be the same as the input expression. For example, the following operations compute the same output: + +.. code-block:: python + + y = einx.log_softmax("a [b]", x) + y = einx.log_softmax("a [b] -> a [b]", x) + +{_args_return(True)} +""" + + +@api +def sort(description: str, tensor: Tensor, *, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.sort(description, tensor, **parameters) + + +sort.__doc__ = f"""Returns values in the given tensor sorted in ascending order. + +The elementary operation has the signature ``[a] -> [a]`` and returns the values sorted along the single axis in ascending order. + +If there is no output expression, it is chosen to be the same as the input expression. For example, the following operations compute the same output: + +.. code-block:: python + + y = einx.sort("a [b]", x) + y = einx.sort("a [b] -> a [b]", x) + +{_args_return(True)} +""" + + +@api +def argsort(description: str, tensor: Tensor, *, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.argsort(description, tensor, **parameters) + + +argsort.__doc__ = f"""Returns the indices that would sort values in the given tensor in ascending order. + +The elementary operation has the signature ``[a] -> [a]`` and returns the indices that would sort values along the single axis in ascending order. + +If there is no output expression, it is chosen to be the same as the input expression. For example, the following operations compute the same output: + +.. code-block:: python + + y = einx.argsort("a [b]", x) + y = einx.argsort("a [b] -> a [b]", x) + +{_args_return(True)} +""" + + +@api +def flip(description: str, tensor: Tensor, *, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.flip(description, tensor, **parameters) + + +flip.__doc__ = f"""Reverse the order of elements in the given tensor. + +The elementary operation has the signature ``[...] -> [...]`` and reverses the order of elements along all axes. + +If there is no output expression, it is chosen to be the same as the input expression. For example, the following operations compute the same output: + +.. code-block:: python + + y = einx.flip("a [b]", x) + y = einx.flip("a [b] -> a [b]", x) + +{_args_return(True)} +""" + + +@api +def roll(description: str, tensor: Tensor, *, shift: npt.ArrayLike, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.roll(description, tensor, shift=shift, **parameters) + + +roll.__doc__ = f"""Rolls the elements in the given tensor by the specified shift amounts. + +The elementary operation has the signature ``[...] -> [...]`` and rolls elements separately along all axes. Elements that are rolled beyond the last position +are re-introduced at the first position. + +If there is no output expression, it is chosen to be the same as the input expression. For example, the following operations compute the same output: + +.. code-block:: python + + y = einx.roll("a [b]", x, shift=4) + y = einx.roll("a [b] -> a [b]", x, shift=4) + +{ + _args_return( + True, + ( + "shift: Amounts by which elements are shifted along each axis. Can be a single integer or a list of integers matching " + "the number of axes in the tensor." + ), + ) +} +""" + + +def _make_argfind_doc(op, find): + return f"""Find the coordinates of the {find} values in the given tensor. + +The elementary operation has the signature ``[...] -> [n]``. It takes an n-dimensional tensor as input and returns the n-dimensional coordinate vector of +the {find} value. + +For 1-dimensional tensors, the elementary operation also accepts the signature ``[a] -> []``. For example, the following two operations compute +the same output: + +.. code-block:: python + + y = einx.argma{op}x("a [b] -> a [1]", x) + y = einx.{op}("a [b] -> a ", x) + +If no output is given, it is determined implicitly by replacing a single bracketed expression in the input with ``[n]``. For example, the +following two operations compute the same output: + +.. code-block:: python + + y = einx.{op}("a [b c]", x) + y = einx.{op}("a [b c] -> a [2]", x) + +{_args_return(True)} +""" + + +@api +def argmax(description: str, tensor: Tensor, *, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.argmax(description, tensor, **parameters) + + +argmax.__doc__ = _make_argfind_doc("argmax", "maximum") + + +@api +def argmin(description: str, tensor: Tensor, *, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor: + return backend.argmin(description, tensor, **parameters) + + +argmin.__doc__ = _make_argfind_doc("argmin", "minimum") + + +ops = [globals()[name] for name in dir() if name[0].islower() and name not in ["api", "npt"] and callable(globals()[name])] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/removed_ops.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/removed_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..b28c8d9a18c6fe94695deaa8f370ee8b7c0f88bf --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/removed_ops.py @@ -0,0 +1,43 @@ +import warnings +from typing import Union +import numpy.typing as npt +from .ops import id +from .backend import Backend +from .types import Tensor + + +class RemovedOperationError(Exception): + pass + + +def vmap(*args, **kwargs): + raise RemovedOperationError( + "einx.vmap has been removed since version 0.4.0. Please use 'einx.{framework}.adapt_with_vmap' instead. See https://einx.readthedocs.io/en/latest/api/adapters.html" + ) + + +def vmap_with_axis(*args, **kwargs): + raise RemovedOperationError( + "einx.vmap_with_axis has been removed since version 0.4.0. Please use one of the new adapters instead. See https://einx.readthedocs.io/en/latest/api/adapters.html" + ) + + +def reduce(*args, **kwargs): + raise RemovedOperationError( + "einx.reduce has been removed since version 0.4.0. Please use 'einx.{framework}.adapt_numpylike_reduce' instead. See https://einx.readthedocs.io/en/latest/api/adapters.html" + ) + + +def elementwise(*args, **kwargs): + raise RemovedOperationError( + "einx.elementwise has been removed since version 0.4.0. Please use 'einx.{framework}.adapt_numpylike_elementwise' instead. See https://einx.readthedocs.io/en/latest/api/adapters.html" + ) + + +def arange(*args, **kwargs): + raise RemovedOperationError("einx.arange has been removed since version 0.4.0. Please use einx.id with np.arange instead.") + + +def rearrange(description: str, *tensors: Tensor, backend: Backend | str | None = None, **parameters: npt.ArrayLike) -> Tensor | tuple[Tensor, ...]: + warnings.warn("einx.rearrange is deprecated and will be removed in a future release. Please use einx.id instead.", DeprecationWarning, stacklevel=2) + return id(description, *tensors, backend=backend, **parameters) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/types.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/types.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0bcc94b253bfac44a3f6c451b955587be0ca8b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/types.py @@ -0,0 +1,9 @@ +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + # Annotation for type checkers + Tensor = Any +else: + # Annotation that can be used at runtime to determine which arguments of a function are tensors + class Tensor: + pass diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/util.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/util.py new file mode 100644 index 0000000000000000000000000000000000000000..f0734ce90ee78440e55c4a0e3fdc21587c59dd45 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/frontend/util.py @@ -0,0 +1,159 @@ +from einx._src.adapter.einx_from_namedtensor import _parse_op +from einx._src.adapter.einx_from_namedtensor import Invocation +from einx._src.adapter.einx_from_namedtensor import solve as _solve2 +from einx._src.frontend.errors import SyntaxError +from einx._src.namedtensor import ExpressionIndicator +import einx._src.namedtensor.stage3 as stage3 +from collections import defaultdict +import numpy as np +import numpy.typing as npt +from collections.abc import Mapping +from .api import _is_scalar +from .types import Tensor +import einx._src.tracer as tracer +import types +import warnings + + +def _exprs_to_axes(exprs): + values = defaultdict(list) + for root in exprs: + for expr in root.nodes(): + if isinstance(expr, stage3.Axis): + tokens = expr.name.split(".") + values[tokens[0]].append((tuple(int(t) for t in tokens[1:]), expr.value)) + + values2 = {} + for name, xs in values.items(): + shape = np.amax([coord for coord, value in xs], axis=0) + 1 + value = np.zeros(shape, dtype="int32") + for coord, v in xs: + value[coord] = v + if value.shape == (): + value = int(value) + values2[name] = value + + return values2 + + +def _solve(description, tensor_shapes, parameters, reraise, cse): + invocation = Invocation( + description, + name="operation", + tensors=[ + tracer.signature.classical.Tensor(None, shape=shape) + if shape is not None + else tracer.signature.classical.ConvertibleTensor(None, shape=None, concrete=types.SimpleNamespace(type=None)) + for shape in tensor_shapes + ], + kwargs={}, + ) + if "->" in description: + indicator = ExpressionIndicator(description) + raise SyntaxError(description, pos=indicator.get_pos_for_literal("->"), message="The expression must not contain a '->' operator.\n%EXPR%") + try: + exprs_in, exprs_out = _parse_op(f"{description} ->", el_op=None, invocation=invocation, allow_concat=True) + exprs_in, exprs_out = _solve2(exprs_in, exprs_out, tensor_shapes, invocation, parameters, cse_concat=True, cse=cse) + except Exception: + if reraise: + raise + else: + return None + return exprs_in + + +def _get_shape(tensor): + if tensor is None: + return None + try: + return tuple(int(x) for x in tensor.shape) + except: + pass + if _is_scalar(tensor): + return () + elif callable(tensor): + return None + else: + raise ValueError(f"Found {type(tensor)} which is not a valid tensor argument.") + + +def solve_shapes(description: str, *tensors: Tensor, **parameters: npt.ArrayLike) -> tuple[tuple[int, ...], ...]: + """Solve for the shapes of the einx expressions under the given constraints. + + Args: + description: Comma-separated list of tensor expressions in einx notation. + *tensors: Tensors matching the description string. Accepts ``None`` for unknown + shapes. + **parameters: Additional parameters that specify dimension sizes, e.g. ``a=4``. + + Returns: + A tuple of shapes corresponding to the input tensors. + + Example: + >>> x = np.random.rand(3, 4) + >>> einx.solve_shapes("a b, c b a", x, None, c=3) + ((3, 4), (5, 4, 3)) + """ + exprs = _solve(description, [_get_shape(tensor) for tensor in tensors], parameters, reraise=True, cse=True) + return tuple(expr.shape for expr in exprs) + + +def solve_axes(description: str, *tensors: Tensor, **parameters: npt.ArrayLike) -> Mapping[str, npt.ArrayLike]: + """Solve for the length of all axes in an expression under the given constraints. + + Args: + description: Comma-separated list of tensor expressions in einx notation. + *tensors: Tensors matching the description string. Accepts ``None`` for unknown + shapes. + **parameters: Additional parameters that specify dimension sizes, e.g. ``a=4``. + + Returns: + A mapping from axis name to their lengths. If an axis is used with an ellipsis, + the lengths are given as a list of integers. + + Example: + >>> x = np.random.rand(3, 4) + >>> einx.solve_axes("a b, c b a", x, None, c=3) + {'a': 3, 'b': 4, 'c': 3} + >>> einx.solve_axes("a..., c a...", x, None, c=3) + {'a': array([3, 4], dtype=int32), 'c': 3} + """ + exprs = _solve(description, [_get_shape(tensor) for tensor in tensors], parameters, reraise=True, cse=False) + return _exprs_to_axes(exprs) + + +def solve(description: str, *tensors: Tensor, **parameters: npt.ArrayLike) -> Mapping[str, npt.ArrayLike]: + """This function is an alias for :func:`einx.solve_axes`.""" + return solve_axes(description, *tensors, **parameters) + + +def matches(description: str, *tensors: Tensor, **parameters: npt.ArrayLike) -> bool: + """Returns whether the given tensors match the einx expression description under the + given constraints. + + Args: + description: Comma-separated list of tensor expressions in einx notation. + *tensors: Tensors matching the description string. Accepts ``None`` for unknown + shapes. + **parameters: Additional parameters that specify dimension sizes, e.g. ``a=4``. + + Returns: + True if the tensors and constraints match the description, False otherwise. + + Example: + >>> x = np.random.rand(3, 4) + >>> einx.matches("a b", x) + True + >>> einx.matches("a b c", x) + False + """ + try: + solve_shapes(description, *tensors, **parameters) + return True + except: + return False + + +def check(description: str, *tensors: Tensor, **parameters: npt.ArrayLike) -> None: + warnings.warn("einx.check is deprecated and will be removed in a future release. Please call einx.id instead.", DeprecationWarning, stacklevel=2) + _solve(description, [_get_shape(tensor) for tensor in tensors], parameters, reraise=True, cse=True) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..beb0cdac177f112b2b92ed588a4030a0d7bd8f1c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__init__.py @@ -0,0 +1,3 @@ +from .util import ExpressionIndicator +from .solve import solve +from .namedtensor import NamedTensor diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b1ac920d76933022a06fc16481c28860d8900d7 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/namedtensor.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/namedtensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a893ec2dac8cfd1f64ac22cb4901c8289cb6b327 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/namedtensor.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/solve.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/solve.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c02c861786e387c871b456f06ab875c86303b21 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/solve.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/util.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dcbdb4731516dee8d05282c97d4b012340a8fd2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/__pycache__/util.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/namedtensor.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/namedtensor.py new file mode 100644 index 0000000000000000000000000000000000000000..a7ca4fd7849985816208b94227964863259590a0 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/namedtensor.py @@ -0,0 +1,17 @@ +import einx._src.tracer as tracer + + +class NamedTensor: + def __init__(self, value, expr): + if not isinstance(value, tracer.signature.classical.Tensor | tracer.signature.classical.ConvertibleTensor): + raise TypeError(f"Value must be a Tensor/ConvertibleTensor, but got {type(value)}") + if value.shape is None: + raise ValueError("Value must have a shape") + if tuple(value.shape) != tuple(expr.shape): + raise ValueError(f"Shape mismatch: {tuple(value.shape)} vs {tuple(expr.shape)}") + self.value = value + self.expr = expr + + @property + def ndim(self): + return len(self.expr.shape) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/solve.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..a252fa5adfbcefcf8ae3abd2862a63f2bf489489 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/solve.py @@ -0,0 +1,127 @@ +from . import stage1 +from . import stage2 +from . import stage3 +import numpy as np + + +def _idx_to_ordinal(idx, n): + if n <= 0: + return "" + if idx == 0: + return "1st " + elif idx == 1: + return "2nd " + elif idx == 2: + return "3rd " + else: + return f"{idx + 1}th " + + +def _arr_to_str(l): + if l is None: + return "None" + elif isinstance(l, np.ndarray): + if l.ndim == 0: + return str(l.tolist()) + else: + return str(tuple(l.tolist())) + elif isinstance(l, list): + return str(tuple(l)) + else: + return str(l) + + +def solve( + exprs_in, exprs_out, tensor_shapes, invocation, parameters=None, cse=True, cse_concat=False, cse_in_brackets=False, verbose=False, equations_stage3=None +): + if parameters is None: + parameters = {} + if len(exprs_in) != len(tensor_shapes): + raise ValueError(f"The number of input expressions (found {len(exprs_in)}) must match the number of input tensors (found {len(tensor_shapes)})") + + for k, v in parameters.items(): + if not isinstance(k, str): + raise ValueError(f"Axis names passed as constraints must be strings, but found value {k} of type {type(k)}") + try: + x = np.asarray(v) + except Exception as e: + raise ValueError(f"Values passed for axis names as constraints must be convertible to numpy arrays, but found value {v} of type {type(v)}") from e + if not (isinstance(v, tuple) and v == ()) and not (isinstance(v, list) and v == []) and not np.issubdtype(x.dtype, np.integer): + raise ValueError( + f"Values passed for axis names as constraints must have an integral type, but found value {v} with type {type(v)} and dtype {x.dtype}" + ) + + # Remove unused constraints + used_axisnames = {expr.name for expr in list(exprs_in) + list(exprs_out) for expr in expr.nodes() if isinstance(expr, stage1.Axis)} + parameters = {k: v for k, v in parameters.items() if k in used_axisnames} + + if verbose: + print("Stage1:") + for expr_in, tensor_shape in zip(exprs_in, tensor_shapes, strict=False): + print(f" IN {expr_in} = {_arr_to_str(tensor_shape)}") + for expr_out in exprs_out: + print(f" OUT {expr_out}") + + # Transform to stage2 + equations = ( + [ + stage2.Equation( + expr, + tensor_shape, + desc1=f'{_idx_to_ordinal(i, len(exprs_in))}input expression ("{expr}")', + desc2=f"{_idx_to_ordinal(i, len(exprs_in))}input tensor (with shape ({', '.join([str(x) for x in tensor_shape])}))" + if tensor_shape is not None + else None, + ) + for i, (expr, tensor_shape) in enumerate(zip(exprs_in, tensor_shapes, strict=False)) + ] + + [stage2.Equation(expr, desc1=f'{_idx_to_ordinal(i, len(exprs_out))}output expression ("{expr}")') for i, expr in enumerate(exprs_out)] + + [ + stage2.Equation( + k, + np.asarray(v)[..., np.newaxis].astype("int32"), + depth1=None, + depth2=None, + desc1=f"axis {k}", + desc2=f"constraint ({_arr_to_str(np.asarray(v))})", + ) + for k, v in parameters.items() + ] + ) + + exprs1, exprs2 = stage2.solve(equations, invocation=invocation) + + if verbose: + print("Stage2:") + for expr1, expr2 in zip(exprs1, exprs2, strict=False): + print(f" {expr1} = {expr2}") + + # Apply common-subexpression-elimination + if cse: + exprs = stage2.cse(exprs1 + exprs2, cse_concat=cse_concat, cse_in_brackets=cse_in_brackets) + exprs1, exprs2 = exprs[: len(exprs1)], exprs[len(exprs1) :] + + if verbose: + print("Stage2 (after CSE):") + for expr1, expr2 in zip(exprs1, exprs2, strict=False): + print(f" {expr1} = {expr2}") + + # Transform to stage3 + equations = [stage3.Equation(expr1, expr2, eq.desc1, eq.desc2) for eq, expr1, expr2 in zip(equations, exprs1, exprs2, strict=False)] + + if equations_stage3 is not None: + exprs_in = exprs1[: len(exprs_in)] + exprs_out = exprs1[len(exprs_in) : len(exprs_in) + len(exprs_out)] + equations.extend(equations_stage3(exprs_in, exprs_out)) + + exprs1, exprs2 = stage3.solve(equations, invocation=invocation) + + if verbose: + print("Stage3:") + for expr1, expr2 in zip(exprs1, exprs2, strict=False): + print(f" {expr1} = {expr2}") + + exprs_in = exprs1[: len(exprs_in)] + exprs_out = exprs1[len(exprs_in) : len(exprs_in) + len(exprs_out)] + + return exprs_in, exprs_out diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..225d28584ce918782781129897138c95f6565e3c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__init__.py @@ -0,0 +1,18 @@ +from .tree import Expression +from .tree import FlattenedAxis +from .tree import Brackets +from .tree import ConcatenatedAxis +from .tree import Axis +from .tree import Ellipsis +from .tree import List +from .tree import Args +from .tree import Op + +from .parse import parse_op +from .parse import parse_args +from .parse import parse_arg + +from .transform import map +from .transform import remove +from .transform import is_in_brackets +from .transform import split_concatenated_axes diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0875c0feafcb2f43bfff08dc837209d745c3f76d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/parse.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/parse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78d5ad587f6095b5f46b88fe8d5112ae2abecb04 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/parse.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/transform.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/transform.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0be9e707b95947d083c1a0c4c41c92f2ca75474 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/transform.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/tree.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/tree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eec4aaec54e39163f199008a34621e1cd2b162e9 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/__pycache__/tree.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/parse.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/parse.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6d18a44586fcbe433c89f05c14f9496adfbf52 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/parse.py @@ -0,0 +1,424 @@ +from collections import defaultdict +import re +from .. import ExpressionIndicator +from einx._src.frontend.errors import SyntaxError +from .tree import * +from .transform import * +import uuid + + +class Token: + def __init__(self, pos, text): + self.begin_pos = pos + self.end_pos = pos + len(text) + self.text = text + + def __str__(self): + return self.text + + def __repr__(self): + return f'Token("{self.text}")' + + +class TokenList: + def __init__(self, tokens, pos): + if isinstance(tokens, TokenList) and len(tokens) == 1 and isinstance(tokens[0], TokenList): + tokens = tokens[0].tokens + self.tokens = tokens + self.text = "".join([t.text for t in self.tokens]) + self.begin_pos = pos + if len(self.tokens) > 0: + assert self.tokens[0].begin_pos == pos + self.end_pos = self.tokens[-1].end_pos + else: + self.end_pos = pos + + def __str__(self): + return "".join([str(t) for t in self.tokens]) + + def __repr__(self): + return f'TokenList("{self}")' + + +_parentheses = {"(": ")", "[": "]"} +_delimiters_front = set(_parentheses.keys()) +_delimiters_back = set(_parentheses.values()) +_nary_ops = ["->", "|", ",", "+", " "] +_ellipsis = "..." +_axis_name = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*") +_literals = _nary_ops + list(_delimiters_front) + list(_delimiters_back) + [_ellipsis] + + +def _delimiter_to_name(delimiter): + if delimiter in ["(", ")"]: + return "parenthesis" + elif delimiter in ["[", "]"]: + return "bracket" + else: + raise ValueError(f"Invalid delimiter: {delimiter}") + + +def parse_op(text): + indicator = ExpressionIndicator(text) + + # ##### Lexer: Convert string into list of (string-)tokens ##### + tokens = [] + start_pos = 0 + + def next_token(end_pos): + nonlocal start_pos + if start_pos != end_pos: + token_text = text[start_pos:end_pos] + if token_text not in _literals and token_text not in _nary_ops and not _axis_name.fullmatch(token_text) and not token_text.isdigit(): + raise SyntaxError( + text, + pos=range(start_pos, end_pos), + message=f"""The expression '{token_text}' is not allowed:\n%EXPR%\nThe following expressions are allowed: +- Literals: -> + , [ ] ( ) ... whitespace +- Named axes: Must match the regex [a-zA-Z_][a-zA-Z0-9_]* +- Unnamed axes: Must match the regex [0-9]+ +""", + ) + tokens.append(Token(start_pos, token_text)) + start_pos = end_pos + + pos = 0 + while pos < len(text): + for l in _literals: + if text[pos:].startswith(l): + next_token(pos) + next_token(pos + len(l)) + pos += len(l) + break + else: + pos += 1 + next_token(pos) + + # ##### Parser: Remove duplicate whitespaces ##### + tokens2 = [] + last_was_whitespace = False + for token in tokens: + if token.text == " ": + if last_was_whitespace: + continue + last_was_whitespace = True + else: + last_was_whitespace = False + tokens2.append(token) + tokens = tokens2 + + # ##### Parser: Convert list of tokens to tree of tokens ##### + stack = [[]] + for token in tokens: + if token.text in _delimiters_front: + stack.append([]) + stack[-1].append(token) + elif token.text in _delimiters_back: + if len(stack) == 1 or _parentheses[stack[-1][0].text] != token.text: + raise SyntaxError( + text, pos=range(token.begin_pos, token.end_pos), message=f"Found a closing {_delimiter_to_name(token.text)} that is not opened:\n%EXPR%" + ) + stack[-1].append(token) + begin_pos = stack[-1][0].begin_pos + group = stack.pop() + stack[-1].append(TokenList(group, begin_pos)) + else: + stack[-1].append(token) + if len(stack) > 1: + raise SyntaxError( + text, + pos=range(stack[-1][0].begin_pos, stack[-1][0].end_pos), + message=f"Found an opening {_delimiter_to_name(stack[-1][0].text)} that is not closed:\n%EXPR%", + ) + expression = TokenList(stack[0], 0) + + # ##### Parser: Convert tokens to expressions ##### + def parse(in_tokens, is_parent_composition=False): + assert isinstance(in_tokens, TokenList) + begin_pos = in_tokens.begin_pos + end_pos = in_tokens.end_pos + in_tokens = in_tokens.tokens + + # Ignore starting and trailing whitespace + while len(in_tokens) > 0 and in_tokens[0].text == " ": + in_tokens.pop(0) + while len(in_tokens) > 0 and in_tokens[-1].text == " ": + in_tokens.pop(-1) + + # Empty expression + if len(in_tokens) == 0: + return List.create([], begin_pos, end_pos) + elif len(in_tokens) == 1 and isinstance(in_tokens[0], TokenList): + return parse(in_tokens[0], is_parent_composition=is_parent_composition) + + begin_pos = in_tokens[0].begin_pos + end_pos = in_tokens[-1].end_pos + + # Delimiters + if in_tokens[0].text in _delimiters_front: + assert len(in_tokens) >= 2 and in_tokens[-1].text in _delimiters_back + inner = parse(TokenList(in_tokens[1:-1], in_tokens[1].begin_pos), is_parent_composition=in_tokens[0].text == "(") + + if in_tokens[0].text == "(": + if isinstance(inner, ConcatenatedAxis): + return inner + else: + return FlattenedAxis.create(inner, begin_pos, end_pos) + elif in_tokens[0].text == "[": + return Brackets.create(inner, begin_pos, end_pos) + else: + raise AssertionError() + + # N-ary operators + for nary_op in _nary_ops: + if any(t.text == nary_op for t in in_tokens): + # Split expression into operands + operands = [] + current_operand_tokens = [] + for token in in_tokens: + if token.text == nary_op: + operands.append( + TokenList(current_operand_tokens, current_operand_tokens[0].begin_pos if len(current_operand_tokens) > 0 else token.begin_pos) + ) + current_operand_tokens = [] + else: + current_operand_tokens.append(token) + operands.append(TokenList(current_operand_tokens, current_operand_tokens[0].begin_pos if len(current_operand_tokens) > 0 else token.end_pos)) + if nary_op == " ": + # Ignore empty operands + operands = [t for t in operands if len(t.tokens) > 0] + + # Create operands + operands = [parse(operand, is_parent_composition=False) for operand in operands] + + # Create expression + if nary_op == " ": + return List.create(operands, begin_pos, end_pos) + elif nary_op == "->": + return Op(operands, begin_pos, end_pos) + elif nary_op == ",": + return Args(operands, begin_pos, end_pos) + elif nary_op == "+": + invalid_operands = [o for o in operands if not isinstance(o, Axis | FlattenedAxis)] + if len(invalid_operands) > 0: + pos = [] + for operand in invalid_operands: + pos.extend(range(operand.begin_pos, operand.end_pos)) + for t in in_tokens: + if t.text == "+": + pos.extend(range(t.begin_pos, t.end_pos)) + raise SyntaxError( + text, + pos=pos, + message="Only named axes, unnamed axes, and flattened axes are allowed as operands of a concatenation operator ('+').\n%EXPR%", + ) + if not is_parent_composition: + raise SyntaxError(text, pos=range(begin_pos, end_pos), message="Concatenated axes must be wrapped in parentheses.\n%EXPR%") + return ConcatenatedAxis.create(operands, begin_pos, end_pos) + else: + raise AssertionError() + + # Ellipsis + if in_tokens[-1].text == _ellipsis and len(in_tokens) <= 2: + if len(in_tokens) == 1: + operand = Axis(Ellipsis.anonymous_variable_name, None, in_tokens[0].begin_pos, in_tokens[0].begin_pos) + else: + assert len(in_tokens) == 2 + operand = parse(TokenList(in_tokens[:1], in_tokens[0].begin_pos), is_parent_composition=False) + return Ellipsis.create(operand, in_tokens[0].begin_pos, in_tokens[-1].end_pos, ellipsis_id=uuid.uuid4().int) + + # Axis + if len(in_tokens) == 1: + value = in_tokens[0].text.strip() + if value.isdigit(): + name = f"unnamed.{uuid.uuid4().int}" + return Axis(name, int(value), in_tokens[0].begin_pos, in_tokens[0].end_pos) + else: + assert _axis_name.fullmatch(in_tokens[0].text), f"Invalid axis name: {in_tokens[0].text}" + return Axis(value, None, in_tokens[0].begin_pos, in_tokens[0].end_pos) + + message = f"The expression '{text[in_tokens[0].begin_pos : in_tokens[-1].end_pos]}' is not valid." + if len(in_tokens) > 1: + message += " Are you maybe missing a whitespace?" + raise SyntaxError(text, pos=range(in_tokens[0].begin_pos, in_tokens[-1].end_pos), message=message + "\n%EXPR%") + + raise AssertionError() + + expression = parse(expression) + + # ##### Move up and merge Op ##### + def move_up(expr): + if isinstance(expr, Axis): + return Op([expr.__deepcopy__()]) + elif isinstance(expr, FlattenedAxis): + op = move_up(expr.inner) + return Op([FlattenedAxis.create(arglist, expr.begin_pos, expr.end_pos) for arglist in op.children], op.begin_pos, op.end_pos) + elif isinstance(expr, Brackets): + op = move_up(expr.inner) + return Op([Brackets.create(arglist, expr.begin_pos, expr.end_pos) for arglist in op.children], op.begin_pos, op.end_pos) + elif isinstance(expr, Ellipsis): + op = move_up(expr.inner) + return Op([Ellipsis.create(arglist, expr.begin_pos, expr.end_pos, expr.ellipsis_id) for arglist in op.children], op.begin_pos, op.end_pos) + + elif isinstance(expr, List | ConcatenatedAxis | Args): + _class = type(expr) + children = [move_up(c) for c in expr.children] + new_children = [] + + nums = {len(c.children) for c in children if len(c.children) != 1} + if len(nums) > 1: + raise SyntaxError( + text, pos=indicator.get_pos_for_literal("->"), message="All '->' operators must appear at the same level of the expression tree.\n%EXPR%" + ) + num = nums.pop() if len(nums) > 0 else 1 + + new_arglists = [] + for idx in range(num): + new_children = [] + for op in children: + if len(op.children) == 1: + new_children.append(op.children[0]) + else: + new_children.append(op.children[idx]) + new_arglists.append(_class.create(new_children, expr.begin_pos, expr.end_pos)) + + return Op(new_arglists, expr.begin_pos, expr.end_pos) + + elif isinstance(expr, Op): + return Op([arglist for child in expr.children for arglist in move_up(child).children], expr.begin_pos, expr.end_pos) + + else: + raise AssertionError(f"Invalid expression type {type(expr)}") + + expression = move_up(expression) + + # ##### Move up and merge Args ##### + def move_up(expr): + if isinstance(expr, Axis): + return Args([expr.__deepcopy__()]) + elif isinstance(expr, FlattenedAxis): + args = move_up(expr.inner) + return Args([FlattenedAxis.create(arg, expr.begin_pos, expr.end_pos) for arg in args.children], args.begin_pos, args.end_pos) + elif isinstance(expr, Brackets): + args = move_up(expr.inner) + return Args([Brackets.create(arg, expr.begin_pos, expr.end_pos) for arg in args.children], args.begin_pos, args.end_pos) + elif isinstance(expr, Ellipsis): + args = move_up(expr.inner) + return Args([Ellipsis.create(arg, expr.begin_pos, expr.end_pos, expr.ellipsis_id) for arg in args.children], args.begin_pos, args.end_pos) + + elif isinstance(expr, List | ConcatenatedAxis): + _class = type(expr) + children = [move_up(c) for c in expr.children] + new_children = [] + + nums = {len(c.children) for c in children if len(c.children) != 1} + if len(nums) > 1: + raise SyntaxError( + text, pos=indicator.get_pos_for_literal("->"), message="All ',' operators must appear at the same level of the expression tree.\n%EXPR%" + ) + num = nums.pop() if len(nums) > 0 else 1 + + new_args = [] + for idx in range(num): + new_children = [] + for args in children: + if len(args.children) == 1: + new_children.append(args.children[0]) + else: + new_children.append(args.children[idx]) + new_args.append(_class.create(new_children, expr.begin_pos, expr.end_pos)) + + return Args(new_args, expr.begin_pos, expr.end_pos) + + elif isinstance(expr, Args): + return Args([arg for child in expr.children for arg in move_up(child).children], expr.begin_pos, expr.end_pos) + + else: + raise AssertionError() + + assert isinstance(expression, Op) + expression = Op([move_up(c) for c in expression.children], expression.begin_pos, expression.end_pos) + + # ##### Drop redundant brackets ##### + def traverse(expr, is_in_brackets): + if isinstance(expr, list): + return [traverse(e, is_in_brackets) for e in expr] + elif isinstance(expr, Axis): + return expr.__deepcopy__() + elif isinstance(expr, FlattenedAxis): + return FlattenedAxis.create(traverse(expr.inner, is_in_brackets), expr.begin_pos, expr.end_pos) + elif isinstance(expr, List): + return List.create([traverse(c, is_in_brackets) for c in expr.children], expr.begin_pos, expr.end_pos) + elif isinstance(expr, ConcatenatedAxis): + return ConcatenatedAxis.create([traverse(c, is_in_brackets) for c in expr.children], expr.begin_pos, expr.end_pos) + elif isinstance(expr, Brackets): + if is_in_brackets: + return traverse(expr.inner, True) + else: + return Brackets.create(traverse(expr.inner, True), expr.begin_pos, expr.end_pos) + elif isinstance(expr, Ellipsis): + return Ellipsis.create(traverse(expr.inner, is_in_brackets), expr.begin_pos, expr.end_pos, expr.ellipsis_id) + elif isinstance(expr, Op): + return Op([traverse(c, is_in_brackets) for c in expr.children], expr.begin_pos, expr.end_pos) + elif isinstance(expr, Args): + return Args([traverse(c, is_in_brackets) for c in expr.children], expr.begin_pos, expr.end_pos) + else: + raise TypeError(f"Invalid expression type {type(expr)}") + + expression = traverse(expression, False) + + # ##### Semantic checks ##### + + # Op cannot have more than two children + if len(expression.children) > 2: + raise SyntaxError(text, pos=indicator.get_pos_for_literal("->"), message="The expression must not contain more than one '->' operator.\n%EXPR%") + + # Axes may only appear with brackets or without brackets, but not both. + axis_names = {expr.name for expr in expression.nodes() if isinstance(expr, Axis)} + for axis_name in axis_names: + marked = 0 + unmarked = 0 + for expr in expression.nodes(): + if isinstance(expr, Axis) and expr.name == axis_name: + if is_in_brackets(expr): + marked += 1 + else: + unmarked += 1 + if marked > 0 and unmarked > 0: + pos = [] + for expr in expression.nodes(): + if isinstance(expr, Axis) and expr.name == axis_name: + pos.extend(range(expr.begin_pos, expr.end_pos)) + parent = expr.parent + while parent is not None: + if isinstance(parent, Brackets): + pos.extend([parent.begin_pos, parent.end_pos - 1]) + parent = parent.parent + raise SyntaxError( + text, + pos=pos, + message=f"There are multiple occurrences of axis {axis_name} with inconsistent bracket " + "usage:\n%EXPR%\nAn axis may only appear with brackets or without brackets, but not " + "both.", + ) + + return expression + + +def parse_args(text): + indicator = ExpressionIndicator(text) + op = parse_op(text) + if len(op.children) != 1: + raise SyntaxError(text, pos=indicator.get_pos_for_literal("->"), message="The expression must not contain a '->' operator.\n%EXPR%") + assert isinstance(op.children[0], Args) + return op.children[0] + + +def parse_arg(text): + if isinstance(text, Expression): + return text + indicator = ExpressionIndicator(text) + args = parse_args(text) + if len(args.children) != 1: + raise SyntaxError(text, pos=indicator.get_pos_for_literal(","), message="The expression must not contain a ',' operator.\n%EXPR%") + return args.children[0] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/transform.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5fae93830f29deccbc703a5df662734c955ed2 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/transform.py @@ -0,0 +1,112 @@ +from .tree import * + + +def map(expr, _map, include_children): + expr2 = _map(expr) + if expr2 is not None: + if include_children: + expr = expr2 + else: + return expr2 + + if isinstance(expr, Axis): + return expr.__deepcopy__() + elif isinstance(expr, FlattenedAxis): + inner = map(expr.inner, _map, include_children) + return FlattenedAxis.create(inner, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + elif isinstance(expr, List): + children = [map(c, _map, include_children) for c in expr.children] + return List.create(children, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + elif isinstance(expr, ConcatenatedAxis): + children = [map(c, _map, include_children) for c in expr.children] + return ConcatenatedAxis.create(children, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + elif isinstance(expr, Brackets): + inner = map(expr.inner, _map, include_children) + return Brackets.create(inner, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + elif isinstance(expr, Ellipsis): + inner = map(expr.inner, _map, include_children) + return Ellipsis.create(inner, begin_pos=expr.begin_pos, end_pos=expr.end_pos, ellipsis_id=expr.ellipsis_id) + elif isinstance(expr, Args): + children = [map(c, _map, include_children) for c in expr.children] + return Args(children, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + elif isinstance(expr, Op): + children = [map(c, _map, include_children) for c in expr.children] + return Op(children, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + else: + raise ValueError(f"Invalid expression type {type(expr)}") + + +def remove(expr, pred, keep_children=False): + if isinstance(pred, type): + pred = lambda x, pred=pred: isinstance(x, pred) + + if keep_children: + + def _map(expr): + if pred(expr): + # Remove a node but keep its children + if isinstance(expr, FlattenedAxis | Brackets | Ellipsis): + return expr.inner + else: + raise ValueError(f"Cannot remove {type(expr)} with keep_children=True") + else: + return None + + return map(expr, _map, include_children=True) + else: + + def _map(expr): + if pred(expr): + return List([]) + else: + return None + + return map(expr, _map, include_children=False) + + +def any_parent_is(expr, pred, include_self=True): + if not include_self: + if expr.parent is None: + return False + expr = expr.parent + while expr is not None: + if pred(expr): + return True + expr = expr.parent + return False + + +def is_in_brackets(expr): + return any_parent_is(expr, lambda expr: isinstance(expr, Brackets)) + + +def _product(*iterables): + if not iterables: + yield () + else: + first, *rest = iterables + for item in first: + for prod in _product(*rest): + yield (item,) + prod + + +def split_concatenated_axes(expr): + if isinstance(expr, ConcatenatedAxis): + for child in expr.children: + yield from split_concatenated_axes(child) + elif isinstance(expr, Axis): + yield expr + elif isinstance(expr, Ellipsis): + for inner in split_concatenated_axes(expr.inner): + yield Ellipsis.create(inner, expr.begin_pos, expr.end_pos, expr.ellipsis_id) + elif isinstance(expr, FlattenedAxis): + for inner in split_concatenated_axes(expr.inner): + yield FlattenedAxis.create(inner, expr.begin_pos, expr.end_pos) + elif isinstance(expr, Brackets): + for inner in split_concatenated_axes(expr.inner): + yield Brackets.create(inner, expr.begin_pos, expr.end_pos) + elif isinstance(expr, List): + for children in _product(*[list(split_concatenated_axes(child)) for child in expr.children]): + yield List.create(children, expr.begin_pos, expr.end_pos) + else: + raise TypeError(f"Invalid expression type {type(expr)}") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/tree.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..568414bcdf3d66dec21eb9da28896b6dbb2ddd52 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage1/tree.py @@ -0,0 +1,388 @@ +class Expression: + def __init__(self, begin_pos, end_pos): + self.begin_pos = begin_pos + self.end_pos = end_pos + self.parent = None + + @property + def depth(self): + if self.parent is None: + return 0 + elif isinstance(self.parent, Ellipsis): + return 1 + self.parent.depth + else: + return self.parent.depth + + +class FlattenedAxis(Expression): + @staticmethod + def create(inner, begin_pos=-1, end_pos=-1): + if isinstance(inner, FlattenedAxis): + return inner + else: + return FlattenedAxis(inner, begin_pos, end_pos) + + def __init__(self, inner, begin_pos=-1, end_pos=-1): + Expression.__init__(self, begin_pos, end_pos) + self.inner = inner + inner.parent = self + assert not isinstance(inner, FlattenedAxis) + + def nodes(self): + yield self + yield from self.inner.nodes() + + @property + def children(self): + return [self.inner] + + def __str__(self): + return "(" + str(self.inner) + ")" + + def __deepcopy__(self): + return FlattenedAxis(self.inner.__deepcopy__(), self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, FlattenedAxis) and self.inner == other.inner + + def __hash__(self): + return 87123 + hash(self.inner) + + @property + def ndim(self): + return 1 + + @property + def value(self): + return self.inner.value + + +class Brackets(Expression): + @staticmethod + def create(inner, begin_pos=-1, end_pos=-1): + if isinstance(inner, Brackets): + return inner + elif inner.ndim == 0: + return List([]) + else: + return Brackets(inner, begin_pos, end_pos) + + def __init__(self, inner, begin_pos=-1, end_pos=-1): + Expression.__init__(self, begin_pos, end_pos) + self.inner = inner + self.inner.parent = self + assert inner.ndim != 0 + assert not isinstance(inner, Brackets) + + def nodes(self): + yield self + yield from self.inner.nodes() + + @property + def children(self): + return [self.inner] + + def __str__(self): + return "[" + str(self.inner) + "]" + + def __deepcopy__(self): + return Brackets(self.inner.__deepcopy__(), self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, Brackets) and self.inner == other.inner + + def __hash__(self): + return 91236 + hash(self.inner) + + @property + def ndim(self): + return self.inner.ndim + + @property + def value(self): + return self.inner.value + + +class Axis(Expression): + @staticmethod + def create(name, value=None, begin_pos=-1, end_pos=-1): + return Axis(name, value, begin_pos, end_pos) + + def __init__(self, name, value, begin_pos=-1, end_pos=-1): + Expression.__init__(self, begin_pos, end_pos) + if not isinstance(name, str): + raise TypeError("Axis name must be a string") + if value is not None and not isinstance(value, int): + raise TypeError("Axis value must be an integer or None") + self.name = name + self.value = value + + def nodes(self): + yield self + + @property + def children(self): + return [] + + def __str__(self): + return self.name if self.value is None else str(self.value) + + def __deepcopy__(self): + return Axis(self.name, self.value, self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, Axis) and self.name == other.name and self.value == other.value + + def __hash__(self): + return 12345 + hash(self.name) + 2 * hash(self.value) + + @property + def ndim(self): + return 1 + + +class Ellipsis(Expression): + anonymous_variable_name = ".anonymous_ellipsis_axis" + + @staticmethod + def create(inner, begin_pos=-1, end_pos=-1, ellipsis_id=None): + if inner.ndim == 0: + return List([]) + else: + return Ellipsis(inner, begin_pos, end_pos, ellipsis_id) + + def __init__(self, inner, begin_pos=-1, end_pos=-1, ellipsis_id=None): + Expression.__init__(self, begin_pos, end_pos) + if ellipsis_id is None: + raise ValueError("ellipsis_id must be provided") + self.inner = inner + self.inner.parent = self + self.ellipsis_id = ellipsis_id + assert inner.ndim != 0 + + def nodes(self): + yield self + yield from self.inner.nodes() + + @property + def children(self): + return [self.inner] + + def __str__(self): + if isinstance(self.inner, Axis) and self.inner.name == Ellipsis.anonymous_variable_name: + return "..." + n = str(self.inner) + if isinstance(self.inner, List) and len(self.inner.children) != 1: + n = "{" + n + "}" + return f"{n}..." + + def __deepcopy__(self): + return Ellipsis(self.inner.__deepcopy__(), self.begin_pos, self.end_pos, self.ellipsis_id) + + def __eq__(self, other): + return isinstance(other, Ellipsis) and self.inner == other.inner + + def __hash__(self): + return 34567 + hash(self.inner) + + @property + def ndim(self): + if self.inner.ndim == 0: + return 0 + else: + return None + + @property + def value(self): + if self.inner.value == 1: + return 1 + elif self.inner.value == 0: + return 0 + else: + return None + + +class ConcatenatedAxis(Expression): + @staticmethod + def create(children, begin_pos=-1, end_pos=-1): + if len(children) == 1: + return children[0] + elif len(children) == 0: + raise ValueError("ConcatenatedAxis must have at least one child") + else: + return ConcatenatedAxis(children, begin_pos, end_pos) + + def __init__(self, children, begin_pos=-1, end_pos=-1): + Expression.__init__(self, begin_pos, end_pos) + self.children = children + assert len(children) > 1 + for child in self.children: + child.parent = self + assert child.ndim == 1 + + def nodes(self): + yield self + for child in self.children: + yield from child.nodes() + + def __str__(self): + return "(" + " + ".join([str(c) for c in self.children]) + ")" + + def __deepcopy__(self): + return ConcatenatedAxis([c.__deepcopy__() for c in self.children], self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, ConcatenatedAxis) and self.children == other.children + + def __hash__(self): + return 234 + hash(tuple(self.children)) + + @property + def ndim(self): + return 1 + + @property + def value(self): + values = [c.value for c in self.children] + if any(v is None for v in values): + return None + else: + return np.sum(values) + + +class List(Expression): + @staticmethod + def create(children, begin_pos=-1, end_pos=-1): + children2 = [] + + def _add(child): + if isinstance(child, List): + for c in child.children: + _add(c) + else: + children2.append(child) + + for c in children: + _add(c) + children = children2 + + if len(children) == 1: + return children[0] + else: + return List(children, begin_pos, end_pos) + + def __init__(self, children, begin_pos=-1, end_pos=-1): + Expression.__init__(self, begin_pos, end_pos) + self.children = children + assert len(children) != 1 + for child in self.children: + child.parent = self + assert not isinstance(child, List) + + def nodes(self): + yield self + for child in self.children: + yield from child.nodes() + + def __str__(self): + return " ".join([str(c) for c in self.children]) + + def __deepcopy__(self): + return List([c.__deepcopy__() for c in self.children], self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, List) and self.children == other.children + + def __hash__(self): + return 2333 + hash(tuple(self.children)) + + @property + def ndim(self): + child_ndims = [c.ndim for c in self.children] + if any(e is None for e in child_ndims): + return None + else: + return sum(child_ndims) + + @property + def value(self): + values = [c.value for c in self.children] + if any(v is None for v in values): + return None + else: + return np.prod(values) + + +class Args(Expression): + def create(children, begin_pos=-1, end_pos=-1): + return Args(children, begin_pos, end_pos) + + def __init__(self, children, begin_pos=-1, end_pos=-1): + Expression.__init__(self, begin_pos, end_pos) + self.children = children + for child in self.children: + assert not isinstance(child, Args) + child.parent = self + + @property + def ndim(self): + return None + + @property + def value(self): + return None + + def nodes(self): + yield self + for child in self.children: + yield from child.nodes() + + def __str__(self): + return ", ".join([str(c) for c in self.children]) + + def __deepcopy__(self): + return Args([c.__deepcopy__() for c in self.children], self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, Args) and self.children == other.children + + def __hash__(self): + return 233314 + hash(tuple(self.children)) + + +class Op(Expression): + @staticmethod + def create(children, begin_pos=-1, end_pos=-1): + return Op(children, begin_pos, end_pos) + + def __init__(self, children, begin_pos=-1, end_pos=-1): + Expression.__init__(self, begin_pos, end_pos) + assert len(children) >= 1 + self.children = children + for child in self.children: + child.parent = self + + @property + def ndim(self): + return None + + @property + def value(self): + return None + + def nodes(self): + yield self + for child in self.children: + yield from child.nodes() + + def __str__(self): + return " -> ".join([str(c) for c in self.children]) + + def __deepcopy__(self): + return Op([c.__deepcopy__() for c in self.children], self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, Op) and self.children == other.children + + def __hash__(self): + return 961121 + hash(tuple(self.children)) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92223ae97ed3e27de8d2848a39db4e65ce56c949 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__init__.py @@ -0,0 +1,13 @@ +from .tree import Expression +from .tree import FlattenedAxis +from .tree import Brackets +from .tree import ConcatenatedAxis +from .tree import Axis +from .tree import List + +from .solve import solve +from .solve import Equation + +from .transform import is_in_brackets + +from .cse import cse diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ee5b27c9247b688b5c0f43f91ba5d1e8b6b4a0e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/cse.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/cse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f3189b67a9d0e78464f68559f2834cdd2fc37b2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/cse.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/solve.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/solve.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b26e6db6bd489a973f9c5dbc32389a8c2733052b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/solve.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/transform.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/transform.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f68d93ab5d252413574c97b2d6547881a3f9f5de Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/transform.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/tree.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/tree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdcda539bf644c88fa30eda3f380356db4b9b633 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/__pycache__/tree.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/cse.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/cse.py new file mode 100644 index 0000000000000000000000000000000000000000..151a642c2a79eb445af8e8c83b838f46ab61351e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/cse.py @@ -0,0 +1,233 @@ +from collections import defaultdict +from .tree import * +from .transform import * +import numpy as np + + +def cse(expressions, cse_concat=True, cse_in_brackets=False, verbose=False): + expressions = list(expressions) + if any(expr is not None and not isinstance(expr, Expression) for expr in expressions): + raise TypeError("Expected expressions to be of type Expression") + + # Find possible expressions, identified by their string representation + str_to_common_expr = defaultdict(list) + for root in expressions: + if root is not None: + for expr in root.nodes(): + if expr.parent is not None: + str_expr = str(expr) + str_to_common_expr[str_expr].append([expr]) + + if isinstance(expr, List): + for start_index in range(len(expr.children)): + for end_index in range(start_index, len(expr.children)): + children = expr.children[start_index : end_index + 1] + str_expr = " ".join([str(c) for c in children]) + str_to_common_expr[str_expr].append(children) + + if verbose: + print("CSE: All subexpressions") + for k in str_to_common_expr.keys(): + print(f" {k}") + + # Keep only expressions + # 1. with at least one axis + # 2. where axes are not also used outside the expression + common_exprs = set() + for str_expr in str_to_common_expr.keys(): + used_axis_ids = set() + used_axis_names = set() + for exprlist in str_to_common_expr[str_expr]: + for expr in exprlist: + for v in expr.nodes(): + if isinstance(v, Axis): + used_axis_ids.add(id(v)) + used_axis_names.add(v.name) + + if len(used_axis_ids) == 0: + continue + + axes_used_only_in_this_subexpression = True + for root in expressions: + if root is not None: + for global_axis in root.nodes(): + if isinstance(global_axis, Axis) and global_axis.name in used_axis_names: + axes_used_only_in_this_subexpression = axes_used_only_in_this_subexpression and id(global_axis) in used_axis_ids + + if axes_used_only_in_this_subexpression: + common_exprs.add(str_expr) + + common_exprs = [str_to_common_expr[k] for k in common_exprs] # list of common_expr(=list of exprlist) + + if verbose: + print("CSE: Removed expressions with axes that are also used outside the expression") + for v in common_exprs: + print(f" {[' '.join([str(y) for y in x]) for x in v]}") + + def remove_duplicates(common_expr): + new_common_expr = [] + for exprlist1 in common_expr: + is_duplicate = False + for exprlist2 in new_common_expr: + is_duplicate = is_duplicate or ( + len(exprlist1) == len(exprlist2) and all(id(expr1) == id(expr2) for expr1, expr2 in zip(exprlist1, exprlist2, strict=False)) + ) + if not is_duplicate: + new_common_expr.append(exprlist1) + return new_common_expr + + common_exprs = [remove_duplicates(exprlists) for exprlists in common_exprs] + + if verbose: + print("CSE: Removed duplicates") + for v in common_exprs: + print(f" {[' '.join([str(y) for y in x]) for x in v]} {[[id(y) for y in x] for x in v]}") + + # Remove singletons + def is_singleton(expr): + if isinstance(expr, list): + return len(expr) == 1 and is_singleton(expr[0]) + elif isinstance(expr, List): + return is_singleton(expr.children) + elif isinstance(expr, Axis): + return True + elif isinstance(expr, Brackets): + return is_singleton(expr.inner) + else: + return False + + common_exprs = [common_expr for common_expr in common_exprs if not is_singleton(common_expr[0])] + + if verbose: + print("CSE: Removed singletons") + for v in common_exprs: + print(f" {[' '.join([str(y) for y in x]) for x in v]}") + + # Remove expressions with/ in markers + if cse_in_brackets: + common_exprs = [ + common_expr + for common_expr in common_exprs + if not any(isinstance(expr, Brackets) for exprlist in common_expr for expr in exprlist for expr in expr.nodes()) + ] + else: + common_exprs = [ + common_expr + for common_expr in common_exprs + if not any(is_in_brackets(expr) for exprlist in common_expr for expr in exprlist for expr in expr.nodes()) + ] + + # Remove expressions that contain concatenations + if not cse_concat: + common_exprs = [ + common_expr + for common_expr in common_exprs + if not any(isinstance(expr, ConcatenatedAxis) for exprlist in common_expr for expr in exprlist for expr in expr.nodes()) + ] + + if verbose: + print("CSE: Removed expressions with markers") + for v in common_exprs: + print(f" {[' '.join([str(y) for y in x]) for x in v]}") + + # Remove expressions at root level with len > 1 + def get_len(x): + if isinstance(x, list): + return len(x) + else: + return x.ndim + + common_exprs = [ + common_expr for common_expr in common_exprs if not (is_at_root(common_expr[0][0]) and (get_len(common_expr[0]) > 1 or get_len(common_expr[0][0]) > 1)) + ] + + if verbose: + print("CSE: Removed subexpressions of root with len > 1") + for v in common_exprs: + print(f" {[' '.join([str(y) for y in x]) for x in v]}") + + # Remove subexpressions of subexpressions + def any_is_parent_of(parent, child): + if isinstance(parent, list): + return any(any_is_parent_of(p, child) for p in parent) + elif isinstance(child, list): + return any(any_is_parent_of(parent, c) for c in child) + else: + return child.parent is not None and (id(child.parent) == id(parent) or any_is_parent_of(parent, child.parent)) + + common_exprs = [ + common_expr + for common_expr in common_exprs + if not any(id(common_expr) != id(common_expr2) and any_is_parent_of(common_expr2, common_expr) for common_expr2 in common_exprs) + ] + + if verbose: + print("CSE: Removed subexpressions of subexpressions") + for v in common_exprs: + print(f" {[' '.join([str(y) for y in x]) for x in v]}") + + # All subexpressions have been found. Now replace them with new Axis objects. + def replace(expr): + if isinstance(expr, list) and len(expr) == 1: + return replace(expr[0]) + if not isinstance(expr, list): + for idx, common_expr in enumerate(common_exprs): + for exprlist in common_expr: + if len(exprlist) == 1 and id(expr) == id(exprlist[0]): + return [Axis(f"cse.{idx}", expr.value, expr.ellipsis_indices, begin_pos=expr.begin_pos, end_pos=expr.end_pos)] + + if isinstance(expr, list): + result = [] + i = 0 + while i < len(expr): + # Check if a subexpression starts at position i + exprlist_found = None + for idx, common_expr in enumerate(common_exprs): # noqa: B007 + for exprlist in common_expr: + for j in range(len(exprlist)): + if i + j >= len(expr) or id(exprlist[j]) != id(expr[i + j]): + break + else: + exprlist_found = exprlist + if exprlist_found is not None: + break + exprlist = exprlist_found + + if exprlist is not None: + assert len(exprlist) > 0 + values = [e.value for e in exprlist] + if any(v is None for v in values): + value = None + else: + value = np.prod(values) + result.append(Axis(f"cse.{idx}", value, exprlist[0].ellipsis_indices, begin_pos=exprlist[0].begin_pos, end_pos=exprlist[-1].end_pos)) + i += len(exprlist) + else: + result.extend(replace(expr[i])) + i += 1 + + return result + elif isinstance(expr, Axis): + return [expr.__deepcopy__()] + elif isinstance(expr, List): + return replace(expr.children) + elif isinstance(expr, ConcatenatedAxis): + return [ + ConcatenatedAxis.create( + [c2 for c1 in expr.children for c2 in replace(c1)], expr.ellipsis_indices, begin_pos=expr.begin_pos, end_pos=expr.end_pos + ) + ] + elif isinstance(expr, Brackets): + return [ + Brackets.create(List.create(replace(expr.inner), expr.ellipsis_indices), expr.ellipsis_indices, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + ] + elif isinstance(expr, FlattenedAxis): + return [ + FlattenedAxis.create( + List.create(replace(expr.inner), expr.ellipsis_indices), expr.ellipsis_indices, begin_pos=expr.begin_pos, end_pos=expr.end_pos + ) + ] + else: + raise AssertionError() + + return [List.create(replace(root), ellipsis_indices=[]) if root is not None else None for root in expressions] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/solve.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..0329b6f7d4c99ce5492071edbe620576fad3394e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/solve.py @@ -0,0 +1,552 @@ +from collections import defaultdict +import numpy as np +import einx._src.util.solver as solver +from .. import stage1 +from einx._src.frontend.errors import RankError +from .tree import * +import uuid + + +def _input_expr(expr): + if expr is None or isinstance(expr, stage1.Expression): + return expr + elif isinstance(expr, str): + return stage1.parse_arg(expr) + else: + if isinstance(expr, np.ndarray): + pass + elif expr == [] or expr == (): + expr = np.asarray(expr).astype("int32") + else: + try: + expr = np.asarray(expr) + except Exception as e: + raise ValueError(f"Invalid expression '{expr}'") from e + if not np.issubdtype(expr.dtype, np.integer): + raise ValueError(f"Invalid expression '{expr}', must be integers") + expr = " ".join([str(i) for i in expr.flatten()]) + expr = stage1.parse_arg(expr) + return expr + + +def _get_expansion(expr): + if isinstance(expr, str): + return (stage1.parse_arg(expr).ndim,) + elif isinstance(expr, stage1.Expression): + return (expr.ndim,) + elif isinstance(expr, np.ndarray): + return tuple(expr.shape) + else: + return None + + +class Equation: + def __init__(self, expr1, expr2=None, depth1=0, depth2=0, desc1=None, desc2=None): + self.expansion1 = _get_expansion(expr1) + self.expansion2 = _get_expansion(expr2) + self.expr1 = _input_expr(expr1) + self.expr2 = _input_expr(expr2) + if desc1 is None: + desc1 = f'expression "{self.expr1}"' + if desc2 is None: + desc2 = f'expression "{self.expr2}"' + self.depth1 = depth1 + self.depth2 = None if expr2 is None else depth2 + self.desc1 = desc1 + self.desc2 = desc2 + + +def solve(equations, invocation, verbose=False): + exprs1 = [t.expr1 for t in equations] + exprs2 = [t.expr2 for t in equations] + expansions1 = [t.expansion1 for t in equations] + expansions2 = [t.expansion2 for t in equations] + depths1 = [t.depth1 for t in equations] + depths2 = [t.depth2 for t in equations] + descs1 = [t.desc1 for t in equations] + descs2 = [t.desc2 for t in equations] + if any(expr is not None and not isinstance(expr, stage1.Expression) for expr in exprs1 + exprs2): + raise ValueError("Can only expand stage1.Expression") + + if verbose: + print("(1) Equations:") + for expansion1, expansion2, expr1, expr2, depth1, depth2, _, _ in zip( + expansions1, expansions2, exprs1, exprs2, depths1, depths2, descs1, descs2, strict=False + ): + print(f'"{expr1}" (expansion={expansion1} depth={depth1}) = "{expr2}" (expansion={expansion2} depth={depth2})') + + expr_id_to_expr = {} + ellipsis_id_to_exprs = defaultdict(list) + axis_name_to_exprs = defaultdict(list) + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + expr_id_to_expr[id(expr)] = expr + if isinstance(expr, stage1.Ellipsis): + ellipsis_id_to_exprs[expr.ellipsis_id].append(expr) + elif isinstance(expr, stage1.Axis): + axis_name_to_exprs[expr.name].append(expr) + + # ##### 1. Find expression depths ##### + equations = [] + + symbolic_expr_depths = {} + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + symbolic_expr_depths[id(expr)] = solver.Variable(f"symbolic_expr_depths[{id(expr)}]", str(expr)) + + # Add equations: Depth relations between subexpressions + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + if isinstance(expr, stage1.Ellipsis): + # Ellipsis increases depth by one + if verbose: + print(f"1. Depth({expr}) + 1 = Depth({expr.inner})") + equations.append((symbolic_expr_depths[id(expr)] + 1, symbolic_expr_depths[id(expr.inner)])) + else: + # All other expressions have the same depth as their children + for child in expr.children: + if verbose: + print(f"2. Depth({expr}) = Depth({child})") + equations.append((symbolic_expr_depths[id(expr)], symbolic_expr_depths[id(child)])) + + # Add equations: Depth arguments + for root, depth in zip(exprs1 + exprs2, depths1 + depths2, strict=False): + if root is not None and depth is not None: + if verbose: + print(f"3. Depth({root}) = {depth}") + equations.append((symbolic_expr_depths[id(root)], depth)) + + # Add equations: Root depths + for root1, root2, expansion1, expansion2 in zip(exprs1, exprs2, expansions1, expansions2, strict=False): + if root1 is not None and root2 is not None and expansion1 is not None and expansion2 is not None: + if verbose: + print(f"4. Depth({root1}) + {len(expansion1)} = Depth({root2}) + {len(expansion2)}") + equations.append((symbolic_expr_depths[id(root1)] + len(expansion1), symbolic_expr_depths[id(root2)] + len(expansion2))) + + # Add equations: Multiple occurrences of the same named axis must have the same depth + symbolic_axis_depths = {} + for root in exprs1 + exprs2: + if root is not None: + for axis in root.nodes(): + if isinstance(axis, stage1.Axis): + if axis.name not in symbolic_axis_depths: + symbolic_axis_depths[axis.name] = solver.Variable(f"symbolic_axis_depths[{axis.name}]", axis.name) + equations.append((symbolic_expr_depths[id(axis)], symbolic_axis_depths[axis.name])) + + # Add equations: Ellipses with the same id must have the same depth + symbolic_ellipsis_depths = {} + for root in exprs1 + exprs2: + if root is not None: + for ellipsis in root.nodes(): + if isinstance(ellipsis, stage1.Ellipsis): + if ellipsis.ellipsis_id not in symbolic_ellipsis_depths: + symbolic_ellipsis_depths[ellipsis.ellipsis_id] = solver.Variable(f"symbolic_ellipsis_depths[{ellipsis.ellipsis_id}]", str(ellipsis)) + equations.append((symbolic_expr_depths[id(ellipsis)], symbolic_ellipsis_depths[ellipsis.ellipsis_id])) + + # Solve + def solve(equations): + solutions = solver.solve(equations) + + expr_depths = {} + for k, v in solutions.items(): + if k.startswith("symbolic_expr_depths["): + expr_depths[int(k[len("symbolic_expr_depths[") : -1])] = int(v) + + # Raise exception on negative depths + failed_exprs = set() + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + if id(expr) in expr_depths and expr_depths[id(expr)] < 0: + failed_exprs.add(str(expr)) + if len(failed_exprs) > 0: + raise solver.SolveExceptionNoSolution() + + # Raise exception on missing depths + failed_exprs = set() + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + if id(expr) not in expr_depths: + failed_exprs.add(str(expr)) + if len(failed_exprs) > 0: + raise solver.SolveExceptionTooManySolutions() + + return expr_depths + + illegal_depth_message = ( + "Please check the following:\n" + " - Each axis name may be used either with or without an ellipsis, " + "but not both.\n - The rank of a constraint " + "must be equal to or less than the number of ellipses around the corresponding axis." + ) + try: + expr_depths = solve(equations) + except solver.SolveExceptionTooManySolutions as e: + raise RankError( + invocation, + message=f"Found an invalid usage of ellipses and/or constraints.\n%EXPR%\n{illegal_depth_message}", + constraints=zip(exprs1, exprs2, strict=False), + ) from e + except solver.SolveExceptionNoSolution as e: + # Check which axes are leading to contradiction + def axisnames_in_equation(eq): + axisnames = set() + for term in eq: + if isinstance(term, solver.Expression): + for var in term: + if isinstance(var, solver.Variable): + if var.id.startswith("symbolic_axis_depths["): + axisnames.add(var.id[len("symbolic_axis_depths[") : -1]) + elif var.id.startswith("symbolic_expr_depths["): + expr_id = var.id[len("symbolic_expr_depths[") : -1] + expr = expr_id_to_expr.get(int(expr_id), None) + for expr in expr.nodes(): + if isinstance(expr, stage1.Axis): + axisnames.add(expr.name) + return list(axisnames) + + def equation_contains_axisconsistency(eq, axis_name): + for term in eq: + if isinstance(term, solver.Expression): + for var in term: + if isinstance(var, solver.Variable): + if var.id == f"symbolic_axis_depths[{axis_name}]": + return True + return False + + contradicting_axis_names = [] + for axis_name in axis_name_to_exprs.keys(): + try_equations = [eq for eq in equations if [axis_name] != axisnames_in_equation(eq) and not equation_contains_axisconsistency(eq, axis_name)] + try: + solve(try_equations) + still_contradicts = False + except solver.SolveExceptionNoSolution: + still_contradicts = True + except solver.SolveExceptionTooManySolutions: + still_contradicts = False + if not still_contradicts: + contradicting_axis_names.append(axis_name) + + if len(contradicting_axis_names) > 0: + contradicting_axis_names = sorted(contradicting_axis_names) + if len(contradicting_axis_names) == 1: + axis = f"axis {contradicting_axis_names[0]}" + else: + axis = f"axes {', '.join(contradicting_axis_names)}" + raise RankError( + invocation, + message=f"Found an invalid usage of ellipses and/or constraints for the {axis}:\n%EXPR%\n{illegal_depth_message}", + pos=invocation.indicator.get_pos_for_axisnames(exprs1 + exprs2, contradicting_axis_names), + constraints=zip(exprs1, exprs2, strict=False), + ) from e + else: + raise RankError( + invocation, + message=f"Found an invalid usage of ellipses and/or constraints.\n%EXPR%\n{illegal_depth_message}", + constraints=zip(exprs1, exprs2, strict=False), + ) from e + + # Expand ellipses and add missing dimensions to expansions + for exprs, expansions, _depths in zip([exprs1, exprs2], [expansions1, expansions2], [depths1, depths2], strict=False): + for i in range(len(exprs)): + if exprs[i] is not None: + missing_depth = expr_depths[id(exprs[i])] + assert missing_depth >= 0 + + # Add missing dimensions to expansions + if expansions[i] is not None: + assert len(expansions[i]) >= 1 + if missing_depth > 0: + expansions[i] = [None] * missing_depth + list(expansions[i]) + + # Add missing ellipses around root expressions + if missing_depth > 0: + for _ in range(missing_depth): + exprs[i] = stage1.Ellipsis(exprs[i], -1, -1, ellipsis_id=uuid.uuid4().int) + expr_depths[id(exprs[i])] = expr_depths[id(exprs[i].inner)] - 1 + + # ##### 2. Find ellipsis expansions ##### + if verbose: + print("##################### Finding ellipsis expansions #####################") + equations = [] + + symbolic_expr_expansions = {} + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + for depth in range(expr_depths[id(expr)] + 1): + key = (id(expr), depth) + symbolic_expr_expansions[key] = solver.Variable(f"symbolic_expr_expansions[{id(expr)},{depth}]", f"{expr} at depth {depth}") + + # Add equations: Expansion of an expression at depth d (less than own depth) + # is equal to the expansion of each child at depth d + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + for depth in range(expr_depths[id(expr)]): + for child in expr.children: + if verbose: + print(f"1. Expansion({expr}, depth={depth}) = Expansion({child}, depth={depth})") + equations.append((symbolic_expr_expansions[(id(expr), depth)], symbolic_expr_expansions[(id(child), depth)])) + + # Add equations: Relations between expressions and their children + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + depth = expr_depths[id(expr)] + if isinstance(expr, stage1.List): + v = sum(symbolic_expr_expansions[(id(child), depth)] for child in expr.children) + if verbose: + if len(expr.children) > 0: + print( + f"2. Expansion({expr}, depth={depth}) = " + " + ".join([f"Expansion({child}, depth={depth})" for child in expr.children]) + "" + ) + else: + print(f"2. Expansion({expr}, depth={depth}) = 0") + elif isinstance(expr, stage1.ConcatenatedAxis): + v = 1 + if verbose: + print(f"2. Expansion({expr}, depth={depth}) = 1") + elif isinstance(expr, stage1.Axis): + v = 1 + if verbose: + print(f"2. Expansion({expr}, depth={depth}) = 1") + elif isinstance(expr, stage1.FlattenedAxis): + v = 1 + if verbose: + print(f"2. Expansion({expr}, depth={depth}) = 1") + elif isinstance(expr, stage1.Brackets): + v = symbolic_expr_expansions[(id(expr.inner), depth)] + if verbose: + print(f"2. Expansion({expr}, depth={depth}) = Expansion({expr.inner}, depth={depth})") + elif isinstance(expr, stage1.Ellipsis): + v = symbolic_expr_expansions[(id(expr.inner), depth)] + if verbose: + print(f"2. Expansion({expr}, depth={depth}) = Expansion({expr.inner}, depth={depth})") + else: + raise AssertionError(f"{expr}") + equations.append((symbolic_expr_expansions[(id(expr), depth)], v)) + + # Add equations: Expansions stored in "expansions" + for expansion1, expansion2, expr1, expr2, desc1, desc2 in zip(expansions1, expansions2, exprs1, exprs2, descs1, descs2, strict=False): + if expansion1 is not None and expansion2 is not None: + if len(expansion1) != len(expansion2) or any( + e1 is not None and e2 is not None and e1 != e2 for e1, e2 in zip(expansion1, expansion2, strict=False) + ): + raise RankError( + invocation, + message=f"The number of dimensions of the {desc1} does not match the number of dimensions of the {desc2}.\n%EXPR%", + constraints=zip(exprs1, exprs2, strict=False), + ) + + if expansion1 is not None and expansion2 is not None: + expansion = [e1 if e1 is not None else e2 for e1, e2 in zip(expansion1, expansion2, strict=False)] + elif expansion1 is not None: + expansion = expansion1 + elif expansion2 is not None: + expansion = expansion2 + else: + expansion = None + + if expansion is not None: + for depth, e in enumerate(expansion): + if e is not None: + if expr1 is not None and depth <= expr_depths[id(expr1)]: + if verbose: + print(f"3. Expansion({expr1}, depth={depth}) = {int(e)}") + equations.append((symbolic_expr_expansions[(id(expr1), depth)], int(e))) + if expr2 is not None and depth <= expr_depths[id(expr2)]: + if verbose: + print(f"3. Expansion({expr2}, depth={depth}) = {int(e)}") + equations.append((symbolic_expr_expansions[(id(expr2), depth)], int(e))) + + # Add equations: Multiple occurrences of the same named axis must have the same expansions + symbolic_axis_expansions = {} + for root in exprs1 + exprs2: + if root is not None: + for axis in root.nodes(): + if isinstance(axis, stage1.Axis): + for depth in range(expr_depths[id(axis)] + 1): + if axis.name not in symbolic_axis_expansions: + symbolic_axis_expansions[(axis.name, depth)] = solver.Variable( + f"symbolic_axis_expansions[{axis.name},{depth}]", f"{axis.name} at depth {depth}" + ) + equations.append((symbolic_expr_expansions[(id(axis), depth)], symbolic_axis_expansions[(axis.name, depth)])) + + # Add equations: Ellipses with the same id must be repeated the same number of times + symbolic_ellipsis_repetitions = {} + for root in exprs1 + exprs2: + if root is not None: + for ellipsis in root.nodes(): + if isinstance(ellipsis, stage1.Ellipsis): + for depth in range(expr_depths[id(ellipsis)] + 1): + if ellipsis.ellipsis_id not in symbolic_ellipsis_repetitions: + symbolic_ellipsis_repetitions[(ellipsis.ellipsis_id, depth)] = solver.Variable( + f"symbolic_ellipsis_repetitions[{ellipsis.ellipsis_id},{depth}]", f"{ellipsis} at depth {depth}" + ) + repetition = symbolic_ellipsis_repetitions[(ellipsis.ellipsis_id, depth)] + + if verbose: + print( + f"4. Repetition({ellipsis}, depth={depth}) * Expansion({ellipsis.inner}, depth={depth + 1}) = " + f"Expansion({ellipsis}, depth={depth})" + ) + + equations.append(( + repetition * symbolic_expr_expansions[(id(ellipsis.inner), depth + 1)], + symbolic_expr_expansions[(id(ellipsis), depth)], + )) + + # Add equations: Same root expansions + for root1, root2 in zip(exprs1, exprs2, strict=False): + if root1 is not None and root2 is not None: + assert expr_depths[id(root1)] == expr_depths[id(root2)] + for depth in range(expr_depths[id(root1)] + 1): + equations.append((symbolic_expr_expansions[(id(root1), depth)], symbolic_expr_expansions[(id(root2), depth)])) + if verbose: + print(f"5. Expansion({root1}, depth={depth}) = Expansion({root2}, depth={depth})") + + # TODO: add equations: empty ellipses have expansion 0 + + # Solve + def solve(equations): + solutions = solver.solve(equations) + + expansion_values = {} + for k, v in solutions.items(): + if k.startswith("symbolic_expr_expansions["): + k = k[len("symbolic_expr_expansions[") : -1] + id_expr, depth = str(k).split(",") + try: + id_expr = int(id_expr) + except ValueError: + continue + depth = int(depth) + expansion_values[(id_expr, depth)] = int(v) + + # Raise exception on negative expansions + failed_exprs = set() + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + depth = expr_depths[id(expr)] + key = (id(expr), depth) + if key in expansion_values and expansion_values[key] < 0: + failed_exprs.add(expr) + if len(failed_exprs) > 0: + raise solver.SolveExceptionNoSolution() + + # Raise exception on missing expansions for expressions not wrapped in flattened-axis + def is_at_root(expr): + parent = expr.parent + while parent is not None: + if isinstance(parent, stage1.FlattenedAxis): + return False + parent = parent.parent + return True + + failed_exprs = [] + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + if not is_at_root(expr): + continue + depth = expr_depths[id(expr)] + key = (id(expr), depth) + if key not in expansion_values: + failed_exprs.append(expr) + if len(failed_exprs) > 0: + raise solver.SolveExceptionTooManySolutions() + + return expansion_values + + try: + expansion_values = solve(equations) + except solver.SolveExceptionTooManySolutions as e: + raise RankError( + invocation, + message="Failed to uniquely determine the expansion of ellipses in the expression. Please provide more constraints.\n%EXPR%", + pos=invocation.indicator.get_pos_for_ellipses(exprs1 + exprs2), + constraints=zip(exprs1, exprs2, strict=False), + ) from e + except solver.SolveExceptionNoSolution as e: + if any(isinstance(expr, stage1.Ellipsis) for expr in exprs1 + exprs2): + message = "Failed to find an expansion of ellipses in the expression such that the number of dimensions matches all given constraints.\n%EXPR%" + else: + message = "The number of tensor dimensions and axes in the expression does not match." + raise RankError( + invocation, message=message, pos=invocation.indicator.get_pos_for_ellipses(exprs1 + exprs2), constraints=zip(exprs1, exprs2, strict=False) + ) from e + + # Expand ellipses and map stage1 expressions to stage2 expressions + def map(expr, ellipsis_indices): + if isinstance(expr, list): + return [c for expr in expr for c in map(expr, ellipsis_indices=ellipsis_indices)] + elif isinstance(expr, stage1.Axis): + return [ + Axis( + expr.name + "".join(f".{idx}" for idx, _ in ellipsis_indices), + expr.value, + ellipsis_indices=ellipsis_indices, + begin_pos=expr.begin_pos, + end_pos=expr.end_pos, + ) + ] + elif isinstance(expr, stage1.List): + return map(expr.children, ellipsis_indices=ellipsis_indices) + elif isinstance(expr, stage1.ConcatenatedAxis): + return [ + ConcatenatedAxis.create( + [List.create(map(c, ellipsis_indices=ellipsis_indices), ellipsis_indices=ellipsis_indices) for c in expr.children], + ellipsis_indices=ellipsis_indices, + begin_pos=expr.begin_pos, + end_pos=expr.end_pos, + ) + ] + elif isinstance(expr, stage1.FlattenedAxis): + return [ + FlattenedAxis.create( + List.create(map(expr.inner, ellipsis_indices=ellipsis_indices), ellipsis_indices=ellipsis_indices), + ellipsis_indices=ellipsis_indices, + begin_pos=expr.begin_pos, + end_pos=expr.end_pos, + ) + ] + elif isinstance(expr, stage1.Brackets): + return [ + Brackets.create( + List.create(map(expr.inner, ellipsis_indices=ellipsis_indices), ellipsis_indices=ellipsis_indices), + ellipsis_indices=ellipsis_indices, + begin_pos=expr.begin_pos, + end_pos=expr.end_pos, + ) + ] + elif isinstance(expr, stage1.Ellipsis): + key = (id(expr), expr_depths[id(expr)]) + if key in expansion_values: + # Ellipsis is expanded + expansion = expansion_values[key] + assert expansion >= 0 + return [c for i in range(expansion) for c in map(expr.inner, ellipsis_indices=ellipsis_indices + [(i, expansion)])] + else: + # Ellipsis is not expanded -> convert to named axis + return [ + Axis( + f"UnexpandedEllipsis({expr})" + "".join(f".{idx}" for idx, _ in ellipsis_indices), + expr.value, + ellipsis_indices=ellipsis_indices, + begin_pos=expr.begin_pos, + end_pos=expr.end_pos, + ) + ] + else: + raise AssertionError(f"{expr}") + + exprs1 = [List.create(map(root, ellipsis_indices=[]), ellipsis_indices=[]) if root is not None else None for root in exprs1] + exprs2 = [List.create(map(root, ellipsis_indices=[]), ellipsis_indices=[]) if root is not None else None for root in exprs2] + + return exprs1, exprs2 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/transform.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..3ae2b4071818a0b0184594a03f6ec54dee0ed2a6 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/transform.py @@ -0,0 +1,21 @@ +from .tree import * + + +def any_parent_is(expr, pred, include_self=True): + if not include_self: + if expr.parent is None: + return False + expr = expr.parent + while expr is not None: + if pred(expr): + return True + expr = expr.parent + return False + + +def is_in_brackets(expr): + return any_parent_is(expr, lambda expr: isinstance(expr, Brackets)) + + +def is_at_root(expr): + return not any_parent_is(expr, lambda expr: isinstance(expr, FlattenedAxis), include_self=False) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/tree.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..04252253e637552129a72e11719dc34d37df2be4 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage2/tree.py @@ -0,0 +1,214 @@ +import numpy as np + + +class Expression: + def __init__(self, ellipsis_indices, begin_pos=None, end_pos=None): + self.ellipsis_indices = ellipsis_indices + self.parent = None + self.begin_pos = begin_pos + self.end_pos = end_pos + + +class FlattenedAxis(Expression): + @staticmethod + def create(inner, ellipsis_indices, begin_pos=None, end_pos=None): + if isinstance(inner, FlattenedAxis): + return inner + else: + return FlattenedAxis(inner, ellipsis_indices, begin_pos, end_pos) + + def __init__(self, inner, ellipsis_indices, begin_pos=None, end_pos=None): + Expression.__init__(self, ellipsis_indices, begin_pos=begin_pos, end_pos=end_pos) + self.inner = inner + inner.parent = self + assert not isinstance(inner, FlattenedAxis) + + def __str__(self): + return f"({self.inner})" + + @property + def ndim(self): + return 1 + + @property + def value(self): + return self.inner.value + + def __iter__(self): + yield self + + def __deepcopy__(self): + return FlattenedAxis(self.inner.__deepcopy__(), ellipsis_indices=self.ellipsis_indices, begin_pos=self.begin_pos, end_pos=self.end_pos) + + def nodes(self): + yield self + yield from self.inner.nodes() + + +class List(Expression): + @staticmethod + def create(children, ellipsis_indices, begin_pos=-1, end_pos=-1): + children2 = [] + + def _add(child): + if isinstance(child, List): + for c in child.children: + _add(c) + else: + children2.append(child) + + for c in children: + _add(c) + children = children2 + + if len(children) == 1: + return children[0] + else: + return List(children, ellipsis_indices, begin_pos, end_pos) + + def __init__(self, children, ellipsis_indices, begin_pos=None, end_pos=None): + Expression.__init__(self, ellipsis_indices, begin_pos=begin_pos, end_pos=end_pos) + self.children = children + assert len(self.children) != 1 + for c in children: + c.parent = self + assert not isinstance(c, List) + + def __str__(self): + return " ".join([str(c) for c in self.children]) + + @property + def ndim(self): + return sum(c.ndim for c in self.children) + + @property + def value(self): + values = [c.value for c in self.children] + if any(v is None for v in values): + return None + else: + return np.prod(values) + + def __iter__(self): + for c in self.children: + yield from c + + def __deepcopy__(self): + return List([c.__deepcopy__() for c in self.children], ellipsis_indices=self.ellipsis_indices, begin_pos=self.begin_pos, end_pos=self.end_pos) + + def nodes(self): + yield self + for c in self.children: + yield from c.nodes() + + +class Axis(Expression): + def __init__(self, name, value, ellipsis_indices, begin_pos=None, end_pos=None): + Expression.__init__(self, ellipsis_indices, begin_pos=begin_pos, end_pos=end_pos) + if not isinstance(name, str): + raise TypeError(f"Axis name must be a string, but got {type(name)}") + if value is not None and not isinstance(value, int | np.integer): + raise TypeError(f"Axis value must be an int or None, but got {type(value)}") + self.name = name + self.value = int(value) if value is not None else None + + def __str__(self): + return self.name if self.value is None else str(self.value) + + @property + def ndim(self): + return 1 + + def __iter__(self): + yield self + + def __deepcopy__(self): + return Axis(self.name, self.value, ellipsis_indices=self.ellipsis_indices, begin_pos=self.begin_pos, end_pos=self.end_pos) + + def nodes(self): + yield self + + +class ConcatenatedAxis(Expression): + @staticmethod + def create(children, ellipsis_indices, begin_pos=None, end_pos=None): + if len(children) == 1: + return children[0] + elif len(children) == 0: + raise ValueError("ConcatenatedAxis must have at least one child") + else: + return ConcatenatedAxis(children, ellipsis_indices, begin_pos, end_pos) + + def __init__(self, children, ellipsis_indices, begin_pos=None, end_pos=None): + Expression.__init__(self, ellipsis_indices, begin_pos=begin_pos, end_pos=end_pos) + for c in children: + if c.ndim != 1: + raise ValueError(f"ConcatenatedAxis can only be used on expressions of length 1, but got expression '{c}'") + self.children = children + for c in children: + c.parent = self + + def __str__(self): + return "(" + " + ".join([str(c) for c in self.children]) + ")" + + @property + def ndim(self): + return 1 + + @property + def value(self): + values = [c.value for c in self.children] + if any(v is None for v in values): + return None + else: + return np.sum(values) + + def __iter__(self): + yield self + + def __deepcopy__(self): + return ConcatenatedAxis( + [c.__deepcopy__() for c in self.children], ellipsis_indices=self.ellipsis_indices, begin_pos=self.begin_pos, end_pos=self.end_pos + ) + + def nodes(self): + yield self + for c in self.children: + yield from c.nodes() + + +class Brackets(Expression): + @staticmethod + def create(inner, ellipsis_indices, begin_pos=None, end_pos=None): + if isinstance(inner, Brackets): + return inner + elif inner.ndim == 0: + return List([], ellipsis_indices) + else: + return Brackets(inner, ellipsis_indices, begin_pos, end_pos) + + def __init__(self, inner, ellipsis_indices, begin_pos=None, end_pos=None): + Expression.__init__(self, ellipsis_indices, begin_pos=begin_pos, end_pos=end_pos) + self.inner = inner + inner.parent = self + + def __str__(self): + return f"[{self.inner}]" + + @property + def ndim(self): + return self.inner.ndim + + @property + def value(self): + return self.inner.value + + def __iter__(self): + yield from self.inner + + def __deepcopy__(self): + return Brackets(self.inner.__deepcopy__(), ellipsis_indices=self.ellipsis_indices, begin_pos=self.begin_pos, end_pos=self.end_pos) + + def nodes(self): + yield self + yield from self.inner.nodes() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..24d974164a368ae8bea73d19fff45be432ba45a1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__init__.py @@ -0,0 +1,13 @@ +from .tree import Expression +from .tree import FlattenedAxis +from .tree import Brackets +from .tree import ConcatenatedAxis +from .tree import Axis +from .tree import List + +from .solve import solve +from .solve import Equation + +from .transform import map +from .transform import remove +from .transform import is_in_brackets diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..473640233b8bbdc620e8330389ed09e7eecb8967 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/solve.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/solve.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3776bf5ed8b90ac03834fce761ea96c591ff478 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/solve.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/transform.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/transform.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68f7c368be9a068d09517fed2bee516a31c256d7 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/transform.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/tree.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/tree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2e6b0fd0072e51616659f89d714e2030e77f637 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/__pycache__/tree.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/solve.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..91739e80902cb20a6cc06ec0009474910ec2c507 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/solve.py @@ -0,0 +1,149 @@ +import einx._src.util.solver as solver +from .. import stage2 +from einx._src.frontend.errors import AxisSizeError +from .tree import * + + +class Equation: + def __init__(self, expr1, expr2=None, desc1=None, desc2=None): + self.expr1 = expr1 + self.expr2 = expr2 + if desc1 is None: + desc1 = f'expression "{self.expr1}"' + if desc2 is None: + desc2 = f'expression "{self.expr2}"' + self.desc1 = desc1 + self.desc2 = desc2 + + +def solve(equations, invocation, verbose=False): + exprs1 = [eq.expr1 for eq in equations] + exprs2 = [eq.expr2 for eq in equations] + if any(expr is not None and not isinstance(expr, stage2.Expression) for expr in exprs1 + exprs2): + raise ValueError("Can only expand stage2.Expression") + + if verbose: + print("Inputs:") + for eq in equations: + print(f" {eq.expr1} ({eq.desc1}) = {eq.expr2} ({eq.desc2})") + + equations = [] + + symbolic_expr_values = {} + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + symbolic_expr_values[id(expr)] = solver.Variable(f"symbolic_expr_values[{id(expr)}]", str(expr)) + + # Add equations: Relations between expressions and their children + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + if isinstance(expr, stage2.List): + equations.append((solver.Product([symbolic_expr_values[id(c)] for c in expr.children]), symbolic_expr_values[id(expr)])) + elif isinstance(expr, stage2.ConcatenatedAxis): + equations.append((solver.Sum([symbolic_expr_values[id(c)] for c in expr.children]), symbolic_expr_values[id(expr)])) + elif isinstance(expr, stage2.Brackets) or isinstance(expr, stage2.FlattenedAxis): + equations.append((symbolic_expr_values[id(expr)], symbolic_expr_values[id(expr.inner)])) + + # Add equations: Same root values + for root1, root2 in zip(exprs1, exprs2, strict=False): + if root1 is not None and root2 is not None: + assert root1.ndim == root2.ndim + for expr1, expr2 in zip(root1, root2, strict=False): + equations.append((symbolic_expr_values[id(expr1)], symbolic_expr_values[id(expr2)])) + + # Add equations: Constant axis values + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + if isinstance(expr, stage2.Axis) and expr.value is not None: + equations.append((symbolic_expr_values[id(expr)], int(expr.value))) + + # Add equations: Multiple occurrences of the same axis must have the same value + sympy_axis_values = {} + for root in exprs1 + exprs2: + if root is not None: + for axis in root.nodes(): + if isinstance(axis, stage2.Axis): + if axis.name not in sympy_axis_values: + sympy_axis_values[axis.name] = solver.Variable(f"sympy_axis_values[{axis.name}]", axis.name) + equations.append((symbolic_expr_values[id(axis)], sympy_axis_values[axis.name])) + + # Solve + def solve(equations): + solutions = solver.solve(equations) + + axis_values = {} + for k, v in solutions.items(): + if k.startswith("symbolic_expr_values["): + axis_values[int(k[len("symbolic_expr_values[") : -1])] = int(v) + + failed_axes = set() + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + if isinstance(expr, stage2.Axis): + if id(expr) not in axis_values: + failed_axes.add(expr) + if len(failed_axes) > 0: + failed_axes = sorted({str(x) for x in failed_axes}) + raise solver.SolveExceptionTooManySolutions(", ".join(failed_axes)) + + # Raise exception on non-positive values + failed_exprs = set() + for root in exprs1 + exprs2: + if root is not None: + for expr in root.nodes(): + if isinstance(expr, stage2.Axis) and axis_values[id(expr)] <= 0: + failed_exprs.add(expr) + if len(failed_exprs) > 0: + raise solver.SolveExceptionNoSolution() + + return axis_values + + try: + axis_values = solve(equations) + except solver.SolveExceptionTooManySolutions as e: + if e.message is None: + raise AxisSizeError( + invocation=invocation, + message="Failed to uniquely determine the size of all axes in the expression. Please provide more constraints.\n%EXPR%", + constraints=zip(exprs1, exprs2, strict=False), + ) from e + else: + axis_names = e.message.split(", ") + axesaxis = "axes" if len(axis_names) > 1 else "axis" + raise AxisSizeError( + invocation, + message=f"Failed to uniquely determine the size of the {axesaxis} {', '.join(axis_names)}. Please provide more constraints.\n%EXPR%", + pos=invocation.indicator.get_pos_for_axisnames(exprs1 + exprs2, axis_names), + constraints=zip(exprs1, exprs2, strict=False), + ) from e + except solver.SolveExceptionNoSolution as e: + raise AxisSizeError( + invocation, + message="Failed to determine the size of all axes in the expression under the given constraints.\n%EXPR%", + constraints=zip(exprs1, exprs2, strict=False), + ) from e + + # Map stage2 expressions to stage3 expressions + def map(expr): + if isinstance(expr, stage2.Axis): + assert id(expr) in axis_values and axis_values[id(expr)] > 0 + return Axis(expr.name, axis_values[id(expr)], expr.begin_pos, expr.end_pos) + elif isinstance(expr, stage2.List): + return List.create([map(child) for child in expr.children], expr.begin_pos, expr.end_pos) + elif isinstance(expr, stage2.ConcatenatedAxis): + return ConcatenatedAxis.create([map(child) for child in expr.children], expr.begin_pos, expr.end_pos) + elif isinstance(expr, stage2.Brackets): + return Brackets.create(map(expr.inner), expr.begin_pos, expr.end_pos) + elif isinstance(expr, stage2.FlattenedAxis): + return FlattenedAxis.create(map(expr.inner), expr.begin_pos, expr.end_pos) + else: + raise AssertionError(type(expr)) + + exprs1 = [map(root) if root is not None else None for root in exprs1] + exprs2 = [map(root) if root is not None else None for root in exprs2] + + return exprs1, exprs2 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/transform.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd0d0a10dca5cd1281b1d93022d6a6fed48ebfa --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/transform.py @@ -0,0 +1,71 @@ +from .tree import * + + +def map(expr, _map, include_children): + expr2 = _map(expr) + if expr2 is not None: + if include_children: + expr = expr2 + else: + return expr2 + + if isinstance(expr, Axis): + return expr.__deepcopy__() + elif isinstance(expr, FlattenedAxis): + inner = map(expr.inner, _map, include_children) + return FlattenedAxis.create(inner, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + elif isinstance(expr, List): + children = [map(c, _map, include_children) for c in expr.children] + return List.create(children, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + elif isinstance(expr, ConcatenatedAxis): + children = [map(c, _map, include_children) for c in expr.children] + return ConcatenatedAxis.create(children, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + elif isinstance(expr, Brackets): + inner = map(expr.inner, _map, include_children) + return Brackets.create(inner, begin_pos=expr.begin_pos, end_pos=expr.end_pos) + else: + raise ValueError(f"Invalid expression type {type(expr)}") + + +def remove(expr, pred, keep_children=False): + if isinstance(pred, type): + pred = lambda x, pred=pred: isinstance(x, pred) + + if keep_children: + + def _map(expr): + if pred(expr): + # Remove a node but keep its children + if isinstance(expr, FlattenedAxis | Brackets): + return expr.inner + else: + raise ValueError(f"Cannot remove {type(expr)} with keep_children=True") + else: + return None + + return map(expr, _map, include_children=True) + else: + + def _map(expr): + if pred(expr): + return List([]) + else: + return None + + return map(expr, _map, include_children=False) + + +def any_parent_is(expr, pred, include_self=True): + if not include_self: + if expr.parent is None: + return False + expr = expr.parent + while expr is not None: + if pred(expr): + return True + expr = expr.parent + return False + + +def is_in_brackets(expr): + return any_parent_is(expr, lambda expr: isinstance(expr, Brackets)) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/tree.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..0d5b0b87b5ea72591e23e3b656c2e10676c0036c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/stage3/tree.py @@ -0,0 +1,225 @@ +import numpy as np +import uuid + + +class Expression: + def __init__(self, value, begin_pos=None, end_pos=None): + if not isinstance(value, (int, np.integer)): + raise TypeError(f"Expected int, got {type(value)}") + self.value = int(value) + self.parent = None + self.begin_pos = begin_pos + self.end_pos = end_pos + + @property + def shape(self): + return tuple(x.value for x in self) + + @property + def ndim(self): + return len(self.shape) + + def __len__(self): + return self.ndim + + +class FlattenedAxis(Expression): + @staticmethod + def create(inner, begin_pos=None, end_pos=None): + if isinstance(inner, FlattenedAxis): + return inner + else: + return FlattenedAxis(inner, begin_pos=begin_pos, end_pos=end_pos) + + def __init__(self, inner, begin_pos=None, end_pos=None): + Expression.__init__(self, inner.value, begin_pos=begin_pos, end_pos=end_pos) + self.inner = inner + inner.parent = self + assert not isinstance(inner, FlattenedAxis) + + def __str__(self): + return f"({self.inner})" + + def __iter__(self): + yield self + + def __deepcopy__(self): + return FlattenedAxis(self.inner.__deepcopy__(), self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, FlattenedAxis) and self.inner == other.inner + + def __hash__(self): + return 8716123 + hash(self.inner) + + def nodes(self): + yield self + yield from self.inner.nodes() + + +class List(Expression): + @staticmethod + def create(children, begin_pos=None, end_pos=None): + children2 = [] + + def _add(child): + if isinstance(child, List): + for c in child.children: + _add(c) + else: + children2.append(child) + + for c in children: + _add(c) + children = children2 + + if len(children) == 1: + return children[0] + else: + return List(children, begin_pos, end_pos) + + def __init__(self, children, begin_pos=None, end_pos=None): + Expression.__init__(self, np.prod([c.value for c in children]).astype("int32"), begin_pos=begin_pos, end_pos=end_pos) + self.children = children + assert len(children) != 1 + for c in children: + c.parent = self + assert not isinstance(c, List) + + def __str__(self): + return " ".join([str(c) for c in self.children]) + + def __getitem__(self, i): + return self.children[i] + + def __iter__(self): + for c in self.children: + yield from c + + def __deepcopy__(self): + return List([c.__deepcopy__() for c in self.children], self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, List) and self.children == other.children + + def __hash__(self): + return 6563 + hash(tuple(self.children)) + + def nodes(self): + yield self + for c in self.children: + yield from c.nodes() + + +class Axis(Expression): + @staticmethod + def new_unnamed(value): + name = f"unnamed.{uuid.uuid4().int}" + return Axis(name, value) + + def __init__(self, name, value, begin_pos=None, end_pos=None): + Expression.__init__(self, value, begin_pos=begin_pos, end_pos=end_pos) + if not isinstance(name, str): + raise TypeError(f"Expected str, got {type(name)}") + if value is None: + raise ValueError("Axis value cannot be None") + self.name = name + self._is_unnamed = self.name.startswith("unnamed.") + + def __str__(self): + return self.name if not self._is_unnamed else str(self.value) + + def __iter__(self): + yield self + + def __deepcopy__(self): + return Axis(self.name, self.value, self.begin_pos, self.end_pos) + + def __eq__(self, other): + if not isinstance(other, Axis): + return False + if self.value != other.value: + return False + return self.name == other.name + + def __hash__(self): + return 9817234 + hash(self.name) + 3 * hash(self.value) + + def nodes(self): + yield self + + +class ConcatenatedAxis(Expression): + @staticmethod + def create(children, begin_pos=None, end_pos=None): + if len(children) == 1: + return children[0] + elif len(children) == 0: + raise ValueError("ConcatenatedAxis must have at least one child") + else: + return ConcatenatedAxis(children, begin_pos, end_pos) + + def __init__(self, children, begin_pos=None, end_pos=None): + if len(children) == 0: + raise ValueError("ConcatenatedAxis must have at least one child") + Expression.__init__(self, np.sum([c.value for c in children]).astype("int32"), begin_pos=begin_pos, end_pos=end_pos) + self.children = children + for c in children: + if len(c) != 1: + raise ValueError(f"ConcatenatedAxis can only be used on expressions of length 1, butgot expression '{c}'") + c.parent = self + + def __str__(self): + return "(" + " + ".join([str(c) for c in self.children]) + ")" + + def __iter__(self): + yield self + + def __deepcopy__(self): + return ConcatenatedAxis([c.__deepcopy__() for c in self.children], self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, ConcatenatedAxis) and self.children == other.children + + def __hash__(self): + return 123 + hash(tuple(self.children)) + + def nodes(self): + yield self + for c in self.children: + yield from c.nodes() + + +class Brackets(Expression): + @staticmethod + def create(inner, begin_pos=None, end_pos=None): + if isinstance(inner, Brackets): + return inner + elif inner.ndim == 0: + return List([]) + else: + return Brackets(inner, begin_pos, end_pos) + + def __init__(self, inner, begin_pos=None, end_pos=None): + Expression.__init__(self, inner.value, begin_pos=begin_pos, end_pos=end_pos) + self.inner = inner + inner.parent = self + + def __str__(self): + return f"[{self.inner}]" + + def __iter__(self): + yield from self.inner + + def __deepcopy__(self): + return Brackets(self.inner.__deepcopy__(), self.begin_pos, self.end_pos) + + def __eq__(self, other): + return isinstance(other, Brackets) and self.inner == other.inner + + def __hash__(self): + return 6433236 + hash(self.inner) + + def nodes(self): + yield self + yield from self.inner.nodes() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/util.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/util.py new file mode 100644 index 0000000000000000000000000000000000000000..03b88a8188b63ce83fd5a4aba6221b1721c249f0 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/namedtensor/util.py @@ -0,0 +1,82 @@ +class ExpressionIndicator: + def __init__(self, text): + self.text = text + + def create(self, pos): + return f'Expression: "{self.text}"\n' + " " * 13 + "".join([("^" if i in pos else " ") for i in range(len(self.text))]) + + def get_pos_for_literal(self, literal): + pos = [] + for i in range(len(self.text)): + if self.text[i:].startswith(literal): + pos.extend(range(i, i + len(literal))) + assert all(p >= 0 and p < len(self.text) for p in pos), f"{pos}" + return pos + + def get_pos_for_exprs(self, exprs): + if not isinstance(exprs, tuple | list): + exprs = [exprs] + pos = [] + for expr in exprs: + pos.extend(range(expr.begin_pos, expr.end_pos)) + assert all(p >= 0 and p < len(self.text) for p in pos), f"{pos}" + return pos + + def get_pos_for_axisnames(self, exprs, axisnames): + if not isinstance(exprs, tuple | list): + exprs = [exprs] + from . import stage1, stage2, stage3 + + pos = [] + for expr in exprs: + if expr is not None: + for expr in expr.nodes(): + if isinstance(expr, stage1.Axis | stage2.Axis | stage3.Axis) and expr.name in axisnames: + pos.extend(range(expr.begin_pos, expr.end_pos)) + assert all(p >= 0 and p < len(self.text) for p in pos), f"{pos}" + return pos + + def get_pos_for_ellipses(self, exprs): + if not isinstance(exprs, tuple | list): + exprs = [exprs] + from . import stage1 + + pos = [] + for expr in exprs: + if expr is not None: + for expr in expr.nodes(): + if isinstance(expr, stage1.Ellipsis): + if expr.begin_pos >= 0: + pos.extend(range(expr.end_pos - 3, expr.end_pos)) + assert all(p >= 0 and p < len(self.text) for p in pos), f"{pos}" + return pos + + def get_pos_for_concat(self, exprs): + if not isinstance(exprs, tuple | list): + exprs = [exprs] + from . import stage1 + + pos = [] + for expr in exprs: + if expr is not None: + for expr in expr.nodes(): + if isinstance(expr, stage1.ConcatenatedAxis): + if expr.begin_pos >= 0: + pos.extend(range(expr.begin_pos, expr.end_pos)) + assert all(p >= 0 and p < len(self.text) for p in pos), f"{pos}" + return pos + + def get_pos_for_brackets(self, exprs): + if not isinstance(exprs, tuple | list): + exprs = [exprs] + from . import stage1 + + pos = [] + for expr in exprs: + if expr is not None: + for expr in expr.nodes(): + if isinstance(expr, stage1.Brackets): + if expr.begin_pos >= 0: + pos.extend([expr.begin_pos, expr.end_pos - 1]) + assert all(p >= 0 and p < len(self.text) for p in pos), f"{pos}" + return pos diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..57edb04ed15af69bc3f4337ed8f35e25f1d8db22 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__init__.py @@ -0,0 +1,4 @@ +from .graph import * +from . import compiler +from . import signature +from .optimizer.optimizer import optimize diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccfeea99e4e75933153d2e7a61f876e413fb6be7 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__pycache__/graph.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__pycache__/graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae86098a4be518154100f17da1fb0cc7efe36fd2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__pycache__/graph.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__pycache__/visualize.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__pycache__/visualize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fc1ced71e24433dc6faa22be3d74fbeb26d8280 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/__pycache__/visualize.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8599e12bc61b4cb89bf18167271ac151fb409d0b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/__init__.py @@ -0,0 +1,2 @@ +from . import run +from . import python diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0aa66d1ccfd0b373352cf768073937cd93bd9056 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/__pycache__/run.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/__pycache__/run.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c098b8aec38274e65afaac20e2d954c42fce457 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/__pycache__/run.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..782bca8b5fe791a0d50d509b3b537694d23e8e70 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__init__.py @@ -0,0 +1,652 @@ +import einx._src.tracer as tracer +import numpy as np +from collections import defaultdict +import itertools +from einx._src.util import pytree + + +class Block: + def __init__(self): + self.statements = [] + + def prepend(self, definition): + self.statements.insert(0, definition) + + def prepend_after_comments(self, definition): + for i, statement in enumerate(self.statements): + if not isinstance(statement, CommentStatement): + self.statements.insert(i, definition) + break + else: + self.statements.append(definition) + + def append(self, definition): + self.statements.append(definition) + + def to_code(self, value_to_code): + lines = [] + for statement in self.statements: + output = statement.to_code(value_to_code) + if isinstance(output, str): + lines.append(output) + else: + lines.extend(output) + return lines + + +class Statement: + def __init__(self, to_code, inputs, output_variables, block): + self.to_code = to_code + self.inputs = list(pytree.flatten(inputs)) + self.output_variables = list(pytree.flatten(output_variables)) + self.block = block + + @property + def input_variables(self): + return {var for input in self.inputs for var in input.used_variables} + + +class CommentStatement(Statement): + def __init__(self, comment, block): + def to_code(value_to_code): + return f"# {comment}" + + Statement.__init__(self, to_code, inputs=[], output_variables=[], block=block) + + +def comment_statement(comment, block): + # def to_code(value_to_code): + # return f"# {comment}" + + # return Statement(to_code, inputs=[], output_variables=[], block=block) + return CommentStatement(comment, block) + + +class Expression: + def __init__(self, inputs, block): + self.inputs = inputs + self.block = block + + +class Variable(Expression): + def __init__(self, block, allow_reusing_name): + Expression.__init__(self, inputs=[], block=block) + self.allow_reusing_name = allow_reusing_name + + @property + def used_variables(self): + return [self] + + +class Literal(Expression): + def __init__(self, code, block): + Expression.__init__(self, inputs=[], block=block) + self.code = code + + @property + def used_variables(self): + return [] + + +class Inlined(Expression): + def __init__(self, to_code, inputs, block): + Expression.__init__(self, inputs=inputs, block=block) + self.to_code = to_code + + @property + def used_variables(self): + return {var for input in self.inputs for var in input.used_variables} + + +class CodeObject: + def __init__(self, object): + self.cached_expressions = {} + + from .scope import get_scopes + + self.scopes = get_scopes(object) + + from .usage import get_usages + + self.max_usage_num = get_usages(object) + + self.scopeid_to_block = {id(scope): Block() for scope in self.scopes.values()} + self.root_block = self.scopeid_to_block[id(self.scopes.root)] + + def _to_key(self, x): + if isinstance(x, list): + return (0,) + tuple(id(i) for i in x) + elif isinstance(x, tuple): + return (1,) + tuple(id(i) for i in x) + elif isinstance(x, dict): + return (2,) + tuple(sorted(id(i) for i in x.keys())) + tuple(sorted(id(i) for i in x.values())) + else: + return id(x) + + def to_code(self, value_to_code): + return self.root_block.to_code(value_to_code) + + @property + def variables(self): + return [v for v in self.cached_expressions.values() if isinstance(v, Variable)] + + @property + def blocks(self): + return list(self.scopeid_to_block.values()) + + def _get_scope_for(self, obj): + return self.scopes[obj] + + def get_block_for(self, obj): + scope = self._get_scope_for(obj) + return self.scopeid_to_block[id(scope)] + + def add_variable_for(self, obj, allow_reusing_name=True): + variable = Variable(block=self.get_block_for(obj), allow_reusing_name=allow_reusing_name) + self[obj] = variable + return variable + + def define(self, obj, expression, no_inline=False, force_inline=False): + if self.max_usage_num[obj] > 1: + no_inline = True + + if no_inline and force_inline: + raise ValueError("Cannot have both no_inline and force_inline set to True.") + + inline = force_inline or not no_inline + + if inline: + self[obj] = expression + else: + variable = self.add_variable_for(obj) + + def left_to_code(value_to_code): + return value_to_code(variable) + + def to_code(value_to_code): + left = left_to_code(value_to_code) + right = expression.to_code(value_to_code) + return f"{left} = {right}" + + block = self.get_block_for(obj) + block.append(Statement(to_code, inputs=[expression], output_variables=[variable], block=block)) + + def __contains__(self, obj): + return self._to_key(obj) in self.cached_expressions + + def __getitem__(self, obj): + return self.cached_expressions[self._to_key(obj)] + + def __setitem__(self, obj, expression): + if not isinstance(obj, tracer.Tracer | list | tuple | dict | tracer.Graph): + raise ValueError(f"Got invalid object {obj} of type {type(obj)}.") + if not isinstance(expression, Expression): + raise ValueError(f"Got invalid expression {expression} of type {type(expression)}.") + key = self._to_key(obj) + assert key not in self.cached_expressions + self.cached_expressions[key] = expression + + if isinstance(obj, list | tuple): + for k, v in enumerate(obj): + + def to_code(value_to_code, k=k): + return f"{value_to_code(expression)}[{k}]" + + self[v] = Inlined(to_code, inputs=[expression], block=expression.block) + elif isinstance(obj, dict): + for k, v in obj.items(): + + def to_code(value_to_code, k=k): + return f"{value_to_code(expression)}[{k}]" + + self[v] = Inlined(to_code, inputs=[expression], block=expression.block) + + +def _debug_value_to_code(x): + if isinstance(x, Variable): + return "V" + elif isinstance(x, Literal): + return "L" + elif isinstance(x, Inlined): + return x.to_code(_debug_value_to_code) + else: + raise ValueError(f"Got {x} of type {type(x)}.") + + +def compile(object, return_code=False): + name_hints = defaultdict(list) + + code = CodeObject(object) + + def _at(obj, key): + obj = _get_expression_for(obj) + slices = key + if not isinstance(slices, tuple): + slices = (slices,) + assert isinstance(slices, tuple) + + def _get_expression_for_slice(s): + if isinstance(s, slice): + return slice( + _get_expression_for(s.start) if s.start is not None else None, + _get_expression_for(s.stop) if s.stop is not None else None, + _get_expression_for(s.step) if s.step is not None else None, + ) + else: + return _get_expression_for(s) + + slices = [_get_expression_for_slice(s) for s in slices] + + inputs = [obj] + for s in slices: + if isinstance(s, slice): + if s.start is not None: + inputs.append(s.start) + if s.stop is not None: + inputs.append(s.stop) + if s.step is not None: + inputs.append(s.step) + else: + inputs.append(s) + + def to_code(value_to_code): + if len(slices) == 0: + key = "()" + else: + + def slice_to_code(s): + if isinstance(s, slice): + x = "" + if s.start is not None: + x += value_to_code(s.start) + x += ":" + if s.stop is not None: + x += value_to_code(s.stop) + if s.step is not None: + x += ":" + value_to_code(s.step) + return x + else: + return value_to_code(s) + + key = ", ".join(slice_to_code(s) for s in slices) + + return f"{value_to_code(obj)}[{key}]" + + return to_code, inputs + + allow_inline_functions = [tracer.signature.python.builtins.isinstance, tracer.signature.python.builtins.tuple, tracer.signature.python.builtins.list] + + variableid_to_constant = {} + + def _eval_app(origin): + if isinstance(origin, tracer.signature.python.Call): + # ################## __call__ ################## + function = _get_expression_for(origin.function) + args = [_get_expression_for(i) for i in origin.args] + kwargs = {k: _get_expression_for(v) for k, v in origin.kwargs.items()} + + def to_code(value_to_code): + args_code = [value_to_code(i) for i in args] + [f"{k}={value_to_code(v)}" for k, v in kwargs.items()] + return f"{value_to_code(function)}({', '.join(args_code)})" + + code.define( + origin.output, + Inlined(to_code, inputs=[function] + args + list(kwargs.values()), block=code.get_block_for(origin.output)), + no_inline=not any(origin.function == f for f in allow_inline_functions), + ) + + elif isinstance(origin, tracer.signature.python.CallInplace): + # ################## __call__ inplace ################## + xs = _get_expression_for(origin.xs) + function = _get_expression_for(origin.function) + args = [_get_expression_for(i) for i in origin.args] + kwargs = {k: _get_expression_for(v) for k, v in origin.kwargs.items()} + + def to_code(value_to_code): + args_code = [value_to_code(i) for i in args] + [f"{k}={value_to_code(v)}" for k, v in kwargs.items()] + return f"{value_to_code(function)}({', '.join(args_code)})" + + block = code.get_block_for(origin.output) + block.append(Statement(to_code, inputs=[xs, function] + args + list(kwargs.values()), output_variables=[], block=block)) + + def to_code(value_to_code): + return value_to_code(xs) + + code.define(origin.output, Inlined(to_code, inputs=[xs], block=block), force_inline=True) + + elif isinstance(origin, tracer.signature.python.GetAttr): + # ################## __getattr__ ################## + obj = _get_expression_for(origin.obj) + key = _get_expression_for(origin.key) + if isinstance(key, Literal): + + def to_code(value_to_code): + assert key.code.startswith('"') and key.code.endswith('"') + return f"{value_to_code(obj)}.{key.code[1:-1]}" + + else: + + def to_code(value_to_code): + return f"getattr({value_to_code(obj)}, {value_to_code(key)})" + + code.define(origin.output, Inlined(to_code, inputs=[obj, key], block=code.get_block_for(origin.output))) + + elif isinstance(origin, tracer.signature.python.GetItem): + # ################## __getitem__ ################## + to_code, inputs = _at(origin.obj, origin.key) + code.define(origin.output, Inlined(to_code, inputs=inputs, block=code.get_block_for(origin.output))) + + elif isinstance(origin, tracer.signature.python.UpdateItem): + # ################## __setitem__ __additem__ ... ################## + at_to_code, inputs = _at(origin.obj, origin.key) + updates = _get_expression_for(origin.value) + obj = _get_expression_for(origin.obj) + + def to_code(value_to_code): + return f"{at_to_code(value_to_code)} {origin.op} {value_to_code(updates)}" + + block = code.get_block_for(origin.output) + block.append(Statement(to_code, inputs=inputs + [updates, obj], output_variables=[], block=block)) + + def to_code(value_to_code): + return value_to_code(obj) + + code.define(origin.output, Inlined(to_code, inputs=[obj], block=block), force_inline=True) + + # TODO: should invalidate everything that comes before, including stuff before reshape! + + elif isinstance(origin, tracer.signature.python.Import): + # ################## import ################## + variable = code.add_variable_for(origin.output, allow_reusing_name=False) + + def to_code(value_to_code): + if origin.from_ is None: + code = f"import {origin.import_}" + else: + code = f"from {origin.from_} import {origin.import_}" + name = value_to_code(variable) + if name != origin.import_: + code += f" as {name}" + return code + + if origin.as_ is not None: + name_hints[id(variable)].append(origin.as_) + elif "." not in origin.import_: + name_hints[id(variable)].append(origin.import_) + + block = code.get_block_for(origin.output) + block.prepend_after_comments(Statement(to_code, inputs=[], output_variables=[variable], block=block)) + + elif isinstance(origin, tracer.signature.python.OperatorApplication): + # ################## operator ################## + operands = [_get_expression_for(i) for i in origin.operands] + if len(operands) == 1: + to_code = lambda value_to_code: f"{origin.operator}({value_to_code(operands[0])})" + elif len(operands) == 2: + to_code = lambda value_to_code: f"({value_to_code(operands[0])} {origin.operator} {value_to_code(operands[1])})" + else: + raise NotImplementedError(f"Don't know how to handle operator {origin.operator} with {len(operands)} operands.") + + code.define(origin.output, Inlined(to_code, inputs=operands, block=code.get_block_for(origin.output))) + + elif isinstance(origin, tracer.signature.python.Assert): + # ################## assert ################## + xs = _get_expression_for(origin.xs) + condition = _get_expression_for(origin.condition) + + message = origin.message + if message is not None: + + def to_code(value_to_code): + return f'assert {value_to_code(condition)}, "{message}"' + + else: + + def to_code(value_to_code): + return f"assert {value_to_code(condition)}" + + block = code.get_block_for(origin.output) + block.append(Statement(to_code, inputs=[xs, condition], output_variables=[], block=block)) + + def to_code(value_to_code): + return value_to_code(xs) + + code.define(origin.output, Inlined(to_code, inputs=[xs], block=code.get_block_for(origin.output)), force_inline=True) + + elif isinstance(origin, tracer.signature.python.Builtin): + # ################## builtin ################## + name = origin.name + to_code = lambda value_to_code: name # TODO: check if name is in scope. Option 1: prevent this. Option 2: import builtins + code.define(origin.output, Inlined(to_code, inputs=[], block=code.get_block_for(origin.output))) + + elif isinstance(origin, tracer.Cast): + # ################## tracer.cast ################## + input = _get_expression_for(origin.input) + to_code = lambda value_to_code: value_to_code(input) + code.define(origin.output, Inlined(to_code, inputs=[input], block=code.get_block_for(origin.output)), force_inline=True) + + elif isinstance(origin, tracer.signature.python.Constant): + # ################## tracer.constant ################## + variable = code.add_variable_for(origin.output, allow_reusing_name=False) + assert id(variable) not in variableid_to_constant + variableid_to_constant[id(variable)] = origin.value + + name_hints[id(variable)].append(f"const{len(variableid_to_constant)}") + value_str = str(origin.value).replace("\n", " ") + code.root_block.prepend(comment_statement(f"Constant const{len(variableid_to_constant)}: {value_str}", code.root_block)) + + else: + raise NotImplementedError(f"Don't know how to handle application {origin} with type {type(origin)}.") + + def _get_expression_for2(x): + if x in code: + return code[x] + elif isinstance(x, tracer.Tracer): + # ################## Tracer ################## + assert x.origin is not None, f"Got {x} of type {type(x)} with no origin." + _eval_app(x.origin) + return code[x] + elif isinstance(x, str): + # ################## str ################## + return Literal(f'"{x}"', block=code.root_block) + elif isinstance(x, int | float | np.integer | np.floating | bool): + # ################## Numeric ################## + return Literal(str(x), block=code.root_block) + elif x is None: + # ################## None ################## + return Literal("None", block=code.root_block) + elif isinstance(x, list): + # ################## list ################## + values = [_get_expression_for(i) for i in x] + if x in code: + # Previous applications already resulted in an expression for the entire list + return code[x] + + def to_code(value_to_code): + return f"[{', '.join([value_to_code(i) for i in values])}]" + + return Inlined(to_code, inputs=values, block=code.get_block_for(x)) + elif isinstance(x, tuple): + # ################## tuple ################## + values = [_get_expression_for(i) for i in x] + if x in code: + # Previous applications already resulted in an expression for the entire tuple + return code[x] + comma = "," if len(values) == 1 else "" + + def to_code(value_to_code): + return f"({', '.join([value_to_code(i) for i in values])}{comma})" + + return Inlined(to_code, inputs=values, block=code.get_block_for(x)) + elif isinstance(x, dict): + # ################## dict ################## + keys = [_get_expression_for(k) for k in x.keys()] + values = [_get_expression_for(v) for v in x.values()] + if x in code: + # Previous applications already resulted in an expression for the entire dict + return code[x] + + def to_code(value_to_code): + return f"{{{', '.join([f'{value_to_code(k)}: {value_to_code(v)}' for k, v in zip(keys, values, strict=False)])}}}" + + return Inlined(to_code, inputs=keys + values, block=code.get_block_for(x)) + elif isinstance(x, tracer.Graph): + # ################## def function(...): ################## + graph = x + outer_block = code.get_block_for(graph) + inner_block = code.get_block_for(graph.output) + + output_variable = code.add_variable_for(graph) + if graph.name is not None: + name_hints[id(output_variable)].append(graph.name) + + # Graph input + parameter_variables = [code.add_variable_for(input) for input in graph.inputs] + + # Graph output + return_value = _get_expression_for(graph.output) + to_code = lambda value_to_code: f"return {value_to_code(return_value)}" + inner_block.append(Statement(to_code, inputs=[return_value], output_variables=[], block=inner_block)) + + def to_code(value_to_code): + function_name = value_to_code(output_variable) + parameter_variable_names = [value_to_code(i) for i in parameter_variables] + lines = [f"def {function_name}({', '.join(parameter_variable_names)}):"] + for line in inner_block.to_code(value_to_code): + lines.append(f" {line}") + return lines + + outer_block.append(Statement(to_code, inputs=[], output_variables=[output_variable], block=outer_block)) + + return output_variable + else: + raise NotImplementedError(f"Don't know how to handle object {x} with type {type(x)}.") + + currently_evaluating_ids = set() + + def _get_expression_for(x): + assert id(x) not in currently_evaluating_ids + currently_evaluating_ids.add(id(x)) + result = _get_expression_for2(x) + currently_evaluating_ids.remove(id(x)) + return result + + object_expression = _get_expression_for(object) + + variables = code.variables + statements = [statement for block in code.blocks for statement in block.statements] + + # Gather dependents per variable + variableid_to_dependentstatements = {id(var): [] for var in variables} + for statement in statements: + for input_variable in statement.input_variables: + variableid_to_dependentstatements[id(input_variable)].append(statement) + + # Find groups of variables that will be assigned the same name + variableid_to_group = {id(var): [var] for var in variables} + + def fuse(var1, var2): + varid1 = id(var1) + varid2 = id(var2) + group1 = variableid_to_group[varid1] + group2 = variableid_to_group[varid2] + if group1 is group2: + return + for var in group2: + variableid_to_group[id(var)] = group1 + group1.append(var) + + for block in code.blocks: + seen_statement_ids = set() + for statement in block.statements: + seen_statement_ids.add(id(statement)) + + output_variables = {v for v in statement.output_variables if v.allow_reusing_name} + if len(output_variables) == 1: + output_variable = output_variables.pop() + + input_variables = statement.input_variables + + # Consider only input variables that allow reusing their name + input_variables = {v for v in input_variables if v.allow_reusing_name} + + # Consider only input variables that are not used in any other block + input_variables = {v for v in input_variables if all(v.block == statement.block for statement in variableid_to_dependentstatements[id(v)])} + + # Consider only input variables that are not used in any later statement + input_variables = { + v for v in input_variables if all(id(statement) in seen_statement_ids for statement in variableid_to_dependentstatements[id(v)]) + } + + if len(input_variables) == 1: + input_variable = input_variables.pop() + if id(input_variable.block) == id(output_variable.block): + fuse(input_variable, output_variable) + + groups = [] + group_ids = set() + for group in variableid_to_group.values(): + if id(group) not in group_ids: + groups.append(group) + group_ids.add(id(group)) + + # Assign names to variables + variableid_to_name = {} + + def names(): + chars = [chr(i) for i in range(ord("a"), ord("z") + 1)] + length = 1 + while True: + for name in itertools.product(chars, repeat=length): + yield "".join(name) + length += 1 + + names = names() + for group in groups: + group_name_hints = [name_hints[id(var)] for var in group if id(var) in name_hints] + group_name_hints = [name for names in group_name_hints for name in names] + if len(group_name_hints) != 1: + name = next(names) + else: + name = group_name_hints[0] + for var in group: + assert id(var) not in variableid_to_name + variableid_to_name[id(var)] = name + + # Generate dictionary of constants + name_to_constant = {variableid_to_name[varid]: constant for varid, constant in variableid_to_constant.items()} + + # Generate code + def value_to_code(x): + if isinstance(x, Variable): + return variableid_to_name[id(x)] + elif isinstance(x, Literal): + return x.code + elif isinstance(x, Inlined): + return x.to_code(value_to_code) + else: + raise ValueError(f"Got {x} of type {type(x)}.") + + exec_code = code.to_code(value_to_code) + exec_code = "\n".join(exec_code) # Used to run the code + eval_code = value_to_code(object_expression) # Used to retrieve the result from the locals_globals dictionary + + locals_globals = {**name_to_constant} + try: + exec(exec_code, locals_globals, locals_globals) + compiled_object = eval(eval_code, locals_globals, locals_globals) + except Exception as e: + message = "The code that was created for this operation failed to compile. The following code was generated:\n" + for i, line in enumerate(exec_code.splitlines(), 1): + message += f"{i:4}: {line}\n" + message += "\nThe error was: " + if hasattr(type(e), "__name__"): + message += f"{type(e).__name__}" + if len(str(e)) > 0: + message += f": {e}" + raise Exception(message) from e + + if return_code: + return compiled_object, exec_code + else: + return compiled_object diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6df704715ca7290c87b7d0f2fb564b678ff10dde Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__pycache__/scope.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__pycache__/scope.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbbe21bcafc195ce128d46903349dbafd9d42acf Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__pycache__/scope.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__pycache__/usage.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__pycache__/usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59fd3fc269688442ab0a84565adb73dfd14d4ce5 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/__pycache__/usage.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/scope.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/scope.py new file mode 100644 index 0000000000000000000000000000000000000000..9b4c3ce622eef06660a5f6ae80a3920ca3934d37 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/scope.py @@ -0,0 +1,184 @@ +import einx._src.tracer as tracer +import einx._src.util.pytree as pytree +import numpy as np + + +class Scope: + def __init__(self): + self.required_scopes = None + self.parent = None + + def is_predecessor_of(self, other): + if other is None: + raise ValueError("Other scope is None.") + elif id(self) == id(other): + return True + elif other.parent is None: + return False + else: + return self.is_predecessor_of(other.parent) + + +class _IntermediateMap: + def __init__(self, global_scope): + self.id_to_scopes = {} + self.global_scope = global_scope + + def __contains__(self, x): + if isinstance(x, str | int | float | bool | np.integer | np.floating | np.bool_) or x is None or x == () or x == []: + return True + + return all(id(y) in self.id_to_scopes for y in pytree.flatten(x)) + + def __getitem__(self, x): + if isinstance(x, str | int | float | bool | np.integer | np.floating | np.bool_) or x is None or x == () or x == []: + return [self.global_scope] + + result = [scope for y in pytree.flatten(x) for scope in self.id_to_scopes[id(y)]] + assert isinstance(result, list) and all(isinstance(s, Scope) for s in result) and len(result) > 0 + return result + + def __setitem__(self, x, scopes): + assert isinstance(scopes, list) and all(isinstance(s, Scope) for s in scopes) and len(scopes) > 0 + if isinstance(x, tracer.Tracer | tracer.Graph): + self.id_to_scopes[id(x)] = scopes + else: + raise TypeError(f"Unsupported type for key: {type(x)}") + + def items(self): + return self.id_to_scopes.items() + + def all_scopes(self): + scopes = [scope for scopes in self.id_to_scopes.values() for scope in scopes] + scopes = list({id(s): s for s in scopes}.values()) + return scopes + + +class Map: + def __init__(self, global_scope, scopes): + self.id_to_scope = {} + self.global_scope = global_scope + self.scopes = scopes + + def _find_common_scope(self, scopes): + scopes = list({id(s): s for s in scopes}.values()) + [self.global_scope] + + scope = scopes[0] + for scope2 in scopes[1:]: + if id(scope) == id(scope2): + pass + elif scope.is_predecessor_of(scope2): + scope = scope2 + elif scope2.is_predecessor_of(scope): + pass + else: + raise ValueError(f"Scopes {scope} and {scope2} are not in a predecessor relationship, cannot determine common scope.") + return scope + + def __getitem__(self, x): + if isinstance(x, str | int | float | bool | np.integer | np.floating | np.bool_) or x is None or x == () or x == []: + return self.global_scope + + if id(x) in self.id_to_scope: + return self.id_to_scope[id(x)] + elif isinstance(x, list | tuple): + return self._find_common_scope([self[y] for y in x]) + elif isinstance(x, dict): + return self._find_common_scope([self[y] for y in list(x.keys()) + list(x.values())]) + else: + raise KeyError(f"Key {x} not found in scope map.") + + @property + def root(self): + return self.global_scope + + def values(self): + return self.scopes + + +def get_scopes(x): + # Determine required scopes for each tracer and dependencies between scopes + # {tracer -> [required scopes]} + global_scope = Scope() + global_scope.required_scopes = [global_scope] + required_scopes = _IntermediateMap(global_scope) + + def _get_required_scopes(x): + if x not in required_scopes: + if isinstance(x, tracer.Tracer) and x.origin is None: + raise ValueError(f"Tracer {x} has no origin, cannot determine required scopes.") + elif isinstance(x, tracer.Tracer) and x.origin is not None: + input_scopes = [scope for input in x.origin.inputs for scope in _get_required_scopes(input)] + [global_scope] + result = list({id(s): s for s in input_scopes}.values()) + required_scopes[x] = result + + for output in pytree.flatten(x.origin.output): + _get_required_scopes(output) + + elif isinstance(x, list | tuple): + input_scopes = [scope for input in x for scope in _get_required_scopes(input)] + [global_scope] + result = list({id(s): s for s in input_scopes}.values()) + elif isinstance(x, dict): + input_scopes = [scope for input in list(x.keys()) + list(x.values()) for scope in _get_required_scopes(input)] + [global_scope] + result = list({id(s): s for s in input_scopes}.values()) + elif isinstance(x, tracer.Graph): + inner_scope = Scope() + for input in x.inputs: + required_scopes[input] = [inner_scope] + required_output_scopes = _get_required_scopes(x.output) + required_output_scopes = [scope for scope in required_output_scopes if id(scope) != id(inner_scope)] + if len(required_output_scopes) == 0: + required_output_scopes = [global_scope] + assert len(required_output_scopes) > 0 + inner_scope.required_scopes = required_output_scopes + required_scopes[x] = required_output_scopes + result = required_output_scopes + else: + result = [global_scope] + else: + result = required_scopes[x] + + assert isinstance(result, list) and all(isinstance(s, Scope) for s in result) and len(result) > 0 + return result + + _get_required_scopes(x) + + scopes = required_scopes.all_scopes() + + # Convert dependencies to parent-child relationships + def _is_predecessor_of(scope, scope2): + assert scope2.required_scopes is not None + if id(scope) == id(scope2): + return True + elif scope in scope2.required_scopes: + return True + else: + return any(_is_predecessor_of(scope, s) for s in scope2.required_scopes) + + def _find_common_scope(scopes): + scopes = list({id(s): s for s in scopes}.values()) + if len(scopes) == 0: + raise ValueError("No scopes found") + + scope = scopes[0] + for scope2 in scopes[1:]: + if id(scope) == id(scope2): + pass + elif _is_predecessor_of(scope, scope2): + scope = scope2 + elif _is_predecessor_of(scope2, scope): + pass + else: + raise ValueError(f"Scopes {scope} and {scope2} are not in a predecessor relationship, cannot determine common scope.") + return scope + + for scope in scopes: + if id(scope) != id(global_scope): + scope.parent = _find_common_scope(scope.required_scopes) + + # Create scopes map: {tracer -> innermost scope} + scopes_map = Map(global_scope, scopes) + for tracerid, scopes in required_scopes.items(): + scopes_map.id_to_scope[tracerid] = scopes_map._find_common_scope(scopes) + + return scopes_map diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/usage.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/usage.py new file mode 100644 index 0000000000000000000000000000000000000000..67b54a841e3c55d36c1a662e5ef146da005989ba --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/python/usage.py @@ -0,0 +1,51 @@ +import einx._src.tracer as tracer +import einx._src.util.pytree as pytree +from collections import defaultdict +import numpy as np + + +class Map: + def __init__(self): + self.id_to_usagenum = defaultdict(lambda: 0) + + def __getitem__(self, key): + if id(key) in self.id_to_usagenum: + return self.id_to_usagenum[id(key)] + elif isinstance(key, tuple | list): + return max(self[k] for k in key) + elif isinstance(key, dict): + return max(self[k] for k in list(key.keys()) + list(key.values())) + else: + raise KeyError(f"Key {key} not found in usage map.") + + +def get_usages(object): + map = Map() + done = set() + + def _recurse(x): + if isinstance(x, str | int | float | np.integer | np.floating | bool) or x is None: + return + if id(x) in done: + return + done.add(id(x)) + + map.id_to_usagenum[id(x)] += 1 + if isinstance(x, tracer.Tracer): + if x.origin is not None: + for input in x.origin.inputs: + _recurse(input) + for output in pytree.flatten(x.origin.output): + _recurse(output) + elif isinstance(x, list | tuple): + for input in x: + _recurse(input) + elif isinstance(x, dict): + for input in list(x.keys()) + list(x.values()): + _recurse(input) + elif isinstance(x, tracer.Graph): + _recurse(x.output) + + _recurse(object) + + return map diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/run.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/run.py new file mode 100644 index 0000000000000000000000000000000000000000..b5771502c5e0dcbfa3881470d847673f079a171d --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/compiler/run.py @@ -0,0 +1,113 @@ +import einx._src.tracer as tracer +import importlib +import operator +import builtins +import numpy as np + +from einx._src.util import pytree + +name_to_operator = {"+": operator.add, "*": operator.mul, "-": operator.sub, "==": operator.eq, "!=": operator.ne} + + +class CompilationCache: + def __init__(self): + self.tracerid_to_concrete = {} + self.enter_num = 0 + + def __enter__(self): + assert self.enter_num >= 0 + if self.enter_num == 0: + self.tracerid_to_concrete.clear() + self.enter_num += 1 + + def __exit__(self, *args): + self.enter_num -= 1 + if self.enter_num == 0: + self.tracerid_to_concrete.clear() + assert self.enter_num >= 0 + + def _get_new(self, x): + if isinstance(x, tracer.Graph): + return CompiledGraph(x, self) + assert isinstance(x, tracer.Tracer) and x.origin is not None + + for input in x.origin.inputs: + self.__getitem__(input) + + if isinstance(x.origin, tracer.signature.python.GetAttr): + return getattr(self.__getitem__(x.origin.obj), x.origin.key) + elif isinstance(x.origin, tracer.signature.python.GetItem): + return self.__getitem__(x.origin.obj)[self.__getitem__(x.origin.key)] + elif isinstance(x.origin, tracer.signature.python.Call): + func = self.__getitem__(x.origin.function) + args = [self.__getitem__(arg) for arg in x.origin.args] + kwargs = {k: self.__getitem__(v) for k, v in x.origin.kwargs.items()} + return func(*args, **kwargs) + elif isinstance(x.origin, tracer.signature.python.Import): + if x.origin.from_ is None: + module = x.origin.import_ + return importlib.import_module(module) + else: + module = x.origin.from_ + module = importlib.import_module(module) + return getattr(module, x.origin.import_) + elif isinstance(x.origin, tracer.signature.python.OperatorApplication): + return name_to_operator[x.origin.operator](*[self.__getitem__(arg) for arg in x.origin.operands]) + elif isinstance(x.origin, tracer.Cast): + concrete_output = self.__getitem__(x.origin.input) + pytree.map(self.__setitem__, x.origin.output, concrete_output) + return self[x] + elif isinstance(x.origin, tracer.signature.python.Assert): + condition = self.__getitem__(x.origin.condition) + assert condition, x.origin.message + return self.__getitem__(x.origin.xs) + elif isinstance(x.origin, tracer.signature.python.Builtin): + return getattr(builtins, x.origin.name) + elif isinstance(x.origin, tracer.signature.python.Constant): + return x.origin.value + else: + raise NotImplementedError(f"Unsupported operation: {type(x.origin)}") + + def __getitem__(self, x): + if isinstance(x, str | int | float | np.integer | np.floating | bool) or x is None: + return x + if isinstance(x, list): + return [self.__getitem__(item) for item in x] + elif isinstance(x, tuple): + return tuple(self.__getitem__(item) for item in x) + elif isinstance(x, dict): + return {self.__getitem__(k): self.__getitem__(v) for k, v in x.items()} + elif id(x) in self.tracerid_to_concrete: + return self.tracerid_to_concrete[id(x)] + else: + concrete = self._get_new(x) + assert id(concrete) not in self.tracerid_to_concrete + self.tracerid_to_concrete[id(x)] = concrete + return concrete + + def __setitem__(self, x, concrete): + assert isinstance(x, tracer.Tracer) + assert id(x) not in self.tracerid_to_concrete + self.tracerid_to_concrete[id(x)] = concrete + + +class CompiledGraph: + def __init__(self, graph, cache): + self.graph = graph + self.cache = cache + + def __call__(self, *args): + if len(args) != len(self.graph.inputs): + raise ValueError(f"Expected {len(self.graph.inputs)} arguments, got {len(args)}") + with self.cache: + for input, concrete in zip(self.graph.inputs, args, strict=False): + self.cache[input] = concrete + return self.cache[self.graph.output] + + +def compile(object, return_code=False): + function = CompilationCache()[object] + if return_code: + return function, None + else: + return function diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/graph.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..0c60c3e55d08a1fa667b75f6022dc162eee36f5e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/graph.py @@ -0,0 +1,97 @@ +from einx._src.util import pytree +import threading + + +class Tracer: + def __init__(self, origin): + if origin is not None and not isinstance(origin, Application): + raise TypeError(f"origin must be Application, not {type(origin)}") + self.origin = origin + + +class Graph: + def __init__(self, inputs, output, name=None): + self.inputs = inputs + self.output = output + self.name = name + + def __eq__(self, other): + if not isinstance(other, Graph): + return False + if self.name != other.name: + return False + if self.inputs != other.inputs: + return False + if self.output != other.output: + return False + return True + + +_dependon = threading.local() + + +class DependOn: + def __init__(self, dependencies): + self.dependencies = list(dependencies) + + def __enter__(self): + if not hasattr(_dependon, "stack"): + _dependon.stack = [] + _dependon.stack.append(self.dependencies) + + def __exit__(self, exc_type, exc_value, traceback): + _dependon.stack.pop() + + +def depend_on(*dependencies): + return DependOn(dependencies) + + +def get_additional_dependencies(): + result = [] + if hasattr(_dependon, "stack"): + for deps in _dependon.stack: + result.extend(deps) + return result + + +class Application: + def __init__(self, inputs, output): + self.output = output(origin=self) + self.inputs = inputs + + +def depends_on(x, predecessor): + if isinstance(x, Tracer) and isinstance(predecessor, Tracer): + if id(x) == id(predecessor): + return True + elif x.origin is not None: + return any(depends_on(inp, predecessor) for inp in x.origin.inputs) + else: + return False + else: + return False + + +class Cast(Application): + def __init__(self, input, output): + super().__init__(inputs=[input], output=output) + self.input = input + if not isinstance(input, Tracer): + raise TypeError(f"input must be Tracer, not {type(input)}") + + def _tracer_transform(self, transform): + return Cast(transform(self.input), lambda origin: pytree.map(lambda x: x._tracer_type(origin), self.output)) + + def __eq__(self, other): + if not isinstance(other, Cast): + return False + if self.input != other.input: + return False + if pytree.map(lambda x: x._tracer_type, self.output) != pytree.map(lambda x: x._tracer_type, other.output): + return False + return True + + +def cast(input, output): + return Cast(input, output).output diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3271a5e5e6fd105ad5e6340a10e3231a88308d9a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__init__.py @@ -0,0 +1,3 @@ +from . import classical +from .graph import InlineGraph +from .graph import SkipCast diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccb80010e28438d76c6aaf9e6f589badf4f0d405 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/_util.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea7874b7e52c7a36c8090a05097859f1522973fe Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/_util.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/classical.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/classical.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86764a45b59f227064d57110770fb2030426d3b9 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/classical.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/graph.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bf3518659ea356e4c399200404ca9ebab52a47c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/graph.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/optimizer.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/optimizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96149b869fc4012ffdbb3bdb3c52c73434b218eb Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/__pycache__/optimizer.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/_util.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc9ef6e0b4b34fa63bf517f3196139f98f477da --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/_util.py @@ -0,0 +1,21 @@ +from einx._src.util import pytree +import einx._src.tracer as tracer + + +def _skip_id(output): + if isinstance(output, tuple): + output = tuple(_skip_id(i) for i in output) + elif isinstance(output, list): + output = [_skip_id(i) for i in output] + elif isinstance(output, dict): + output = {k: _skip_id(v) for k, v in output.items()} + + origins = [x.origin for x in pytree.flatten(output) if isinstance(x, tracer.Tracer)] + if len(origins) == 0: + return output + origin = origins[0] + + if isinstance(origin, tracer.Cast) and pytree.all(lambda x, y: id(x) == id(y), origin.output, output): + return _skip_id(origin.input) + else: + return output diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/classical.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/classical.py new file mode 100644 index 0000000000000000000000000000000000000000..d91d2019a5b0731f23c347b396e8db4c883f4d51 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/classical.py @@ -0,0 +1,97 @@ +import numpy as np +import einx._src.tracer as tracer +from einx._src.util import pytree +from ._util import _skip_id + + +class SkipReshape: + def __init__(self, reshape): + self.reshape = reshape + + def _is_result_of_call(self, x): + return isinstance(x, tracer.Tracer) and isinstance(x.origin, tracer.signature.python.Call) and x.origin.function == self.reshape + + def __call__(self, x, transform): + if self._is_result_of_call(x): + input = x.origin.args[0] + if isinstance(input, tracer.signature.python.Value): + return False, None + + shape = x.origin.args[1] + + if isinstance(shape, tuple | list | np.ndarray) and tuple(shape) == tuple(input.shape): + # Skip nop reshape + return True, transform(input) + input = _skip_id(input) + if self._is_result_of_call(input): + # Merge consecutive reshapes + input_of_input = input.origin.args[0] + return True, tracer.signature.python.call(transform(x.origin.function), [transform(input_of_input), shape]) + return False, None + + +class SkipTranspose: + def __init__(self, transpose): + self.transpose = transpose + + def _is_result_of_call(self, x): + return isinstance(x, tracer.Tracer) and isinstance(x.origin, tracer.signature.python.Call) and x.origin.function == self.transpose + + def __call__(self, x, transform): + if self._is_result_of_call(x): + input = x.origin.args[0] + if isinstance(input, tracer.signature.python.Value): + return False, None + + perm = x.origin.args[1] + + if isinstance(perm, tuple | list | np.ndarray) and tuple(perm) == tuple(range(input.ndim)): + # Skip nop transpose + return True, transform(input) + input = _skip_id(input) + if self._is_result_of_call(input): + # Merge consecutive transposes + input_of_input = input.origin.args[0] + perm1 = input.origin.args[1] + perm2 = perm + assert all(isinstance(p, int) for p in perm1) and all(isinstance(p, int) for p in perm2) + new_perm = tuple(perm1[p] for p in perm2) + return True, tracer.signature.python.call(transform(x.origin.function), [transform(input_of_input), new_perm]) + return False, None + + +class SkipConcatenate: + def __init__(self, concatenate): + self.concatenate = concatenate + + def _is_result_of_call(self, x): + return isinstance(x, tracer.Tracer) and isinstance(x.origin, tracer.signature.python.Call) and x.origin.function == self.concatenate + + def __call__(self, x, transform): + if self._is_result_of_call(x): + tensors = x.origin.args[0] + if isinstance(tensors, list | tuple) and len(tensors) == 1: + # Skip concatenate + return True, transform(tensors[0]) + return False, None + + +class SkipBroadcastTo: + def __init__(self, broadcast_to): + self.broadcast_to = broadcast_to + + def _is_result_of_call(self, x): + return isinstance(x, tracer.Tracer) and isinstance(x.origin, tracer.signature.python.Call) and x.origin.function == self.broadcast_to + + def __call__(self, x, transform): + if self._is_result_of_call(x): + input = x.origin.args[0] + if isinstance(input, tracer.signature.python.Value): + return False, None + + shape = x.origin.args[1] + + if isinstance(shape, tuple | list | np.ndarray) and tuple(shape) == tuple(input.shape): + # Skip broadcast_to + return True, transform(input) + return False, None diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/graph.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..dbac12d26be5168895b60a5878c989fc16b62237 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/graph.py @@ -0,0 +1,43 @@ +import einx._src.tracer as tracer +import einx._src.util.pytree as pytree +from ._util import _skip_id + + +class InlineGraph: + def __call__(self, x, transform): + if isinstance(x, tracer.Graph): + output = _skip_id(x.output) + if isinstance(output, tracer.Tracer) and isinstance(output.origin, tracer.signature.python.Call) and len(output.origin.kwargs) == 0: + function_inputs = [_skip_id(i) for i in output.origin.args] + graph_inputs = x.inputs + + if [id(i) for i in graph_inputs] != [id(i) for i in function_inputs]: + # Function is not called with the same inputs as the graph + return False, None + + if any(tracer.depends_on(output.origin.function, input) for input in graph_inputs): + # Function depends on graph inputs + return False, None + + return True, transform(output.origin.function) + + return False, None + + +class SkipCast: + def _is_result_of_call(self, x): + return isinstance(x, tracer.Tracer) and isinstance(x.origin, tracer.Cast) + + def __call__(self, x, transform): + if self._is_result_of_call(x): + input = x.origin.input + output = x.origin.output + input_signature = pytree.map(lambda x: x._tracer_type(None), input) + output_signature = pytree.map(lambda x: x._tracer_type(None), output) + + if input_signature == output_signature: + # Skip cast + return True, transform(input) + # TODO: merge consecutive casts + + return False, None diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/optimizer.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..1c534d0d87e0fd5a7bdf715e6b5bb331d23d58d2 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/optimizer/optimizer.py @@ -0,0 +1,72 @@ +import numpy as np +import einx._src.tracer as tracer +from einx._src.util import pytree + + +class Optimizer: + def __init__(self, optimizations): + self.id_to_newobj = {} + self.changed = False + self.optimizations = optimizations + + def _set(self, oldobj, newobj): + self.id_to_newobj[id(oldobj)] = newobj + + def _optimize(self, x): + if id(x) in self.id_to_newobj: + return self.id_to_newobj[id(x)] + + for pattern in self.optimizations: + changed, newobj = pattern(x, self._optimize) + if changed: + pytree.map(self._set, x, newobj) + self.changed = True + return newobj + + # No pattern matched -> apply optimization to all predecessors + if isinstance(x, str | int | float | np.integer | np.floating | np.ndarray) or x is None: + return x + elif isinstance(x, tracer.Graph): + # Create inputs + new_inputs = [] + for old_input in x.inputs: + new_input = old_input._tracer_type(None) + pytree.map(self._set, old_input, new_input) + new_inputs.append(new_input) + + # Optimize to output + new_output = self._optimize(x.output) + + return tracer.Graph(new_inputs, new_output, x.name) + elif isinstance(x, tracer.Tracer): + if x.origin is None: + return x._tracer_type(None) + else: + new_origin = x.origin._tracer_transform(self._optimize) + assert type(new_origin) == type(x.origin) + assert len(new_origin.inputs) == len(x.origin.inputs) + assert type(new_origin.output) == type(x.origin.output) + + pytree.map(self._set, x.origin.output, new_origin.output) + + return self.id_to_newobj[id(x)] + elif isinstance(x, list): + return [self._optimize(i) for i in x] + elif isinstance(x, tuple): + return tuple(self._optimize(i) for i in x) + elif isinstance(x, dict): + return {self._optimize(k): self._optimize(v) for k, v in x.items()} + elif isinstance(x, slice): + return slice(self._optimize(x.start), self._optimize(x.stop), self._optimize(x.step)) + else: + raise NotImplementedError(f"Unsupported type: {type(x)}") + + +def optimize(x, optimizations): + if len(optimizations) > 0: + while True: + optimizer = Optimizer(optimizations) + x = optimizer._optimize(x) + if not optimizer.changed: + break + return x diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f68be88882e8497f8283423b1b2c8c394b79a0f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/__init__.py @@ -0,0 +1,10 @@ +from . import python +from . import classical +from .classical.numpy import numpy +from .classical.jax import jax +from .classical.torch import torch +from .classical.mlx import mlx +from .classical.tensorflow import tensorflow +from .classical.arrayapi import arrayapi +from .classical.tinygrad import tinygrad +from . import functorchdim diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d023ad0fb2ee715fc94a76cfad86715c9771b601 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/__pycache__/python.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/__pycache__/python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfdff7925a3c70436c2b6f3bac24492a38945723 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/__pycache__/python.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca02d227065c3d062c7f63ffbeb8475a590c639e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__init__.py @@ -0,0 +1,22 @@ +from .tensor import Tensor +from .tensor import ConvertibleTensor + +from .functions import preserve_shape +from .functions import set_shape +from .functions import transpose +from .functions import diagonal +from .functions import reduce +from .functions import elementwise +from .functions import take +from .functions import inplace +from .functions import getitem +from .functions import setitem +from .functions import arange +from .functions import concatenate +from .functions import split +from .functions import dot +from .functions import matmul +from .functions import einsum +from .functions import tensordot +from .functions import vmap +from .functions import at diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4507ceee0cbc94a95ac3505c7d5104dac7ab868 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/arrayapi.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/arrayapi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3767b2b1d7414469eea5c665d8dcdceb3425cbbb Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/arrayapi.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/functions.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..832365e672c96785b884e5bd02a3664cc109780b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/functions.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/jax.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/jax.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa900e7246480e435731d351a5b0c570fa2cd938 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/jax.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/mlx.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/mlx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70d9fe015c290476b739f39341fbb424d46bf5c6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/mlx.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/numpy.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/numpy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61b113145824c50bda674efe6cefb9b3e2a1dac1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/numpy.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/tensor.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0575158450e8bafdb2df1ed68b8117377e7f5c64 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/tensor.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/tensorflow.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/tensorflow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..134e35f73aac847846788c5bf4acbee9d5ac7c62 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/tensorflow.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/tinygrad.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/tinygrad.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b1a5a851593b39a183bfb5164e41f4b3a39ec64 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/tinygrad.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/torch.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23739e5f6d34242ec8667a3f075f625871e60650 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/__pycache__/torch.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/arrayapi.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/arrayapi.py new file mode 100644 index 0000000000000000000000000000000000000000..a44ff73e76824a592bc79fb357d6d8742e59aa12 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/arrayapi.py @@ -0,0 +1,101 @@ +import einx._src.tracer as tracer +import einx._src.tracer.signature as signature +from einx._src.util.functools import use_name_of +import types + + +class Lazy: + def __init__(self, get_xp): + self.get_xp = get_xp + + def __getattr__(self, name): + @use_name_of(name) + def inner(*args, **kwargs): + xp = self.get_xp() + op = getattr(xp, name) + return op(*args, **kwargs) + + return inner + + +class arrayapi: + def __init__(self, get_xp): + self._get_xp = get_xp + xp = Lazy(get_xp) + + self.asarray = signature.classical.preserve_shape(xp.asarray) + self.reshape = signature.classical.set_shape(xp.reshape) + self.permute_dims = signature.classical.transpose(xp.permute_dims) + self.broadcast_to = signature.classical.set_shape(xp.broadcast_to) + self.arange = signature.classical.arange(xp.arange) + self.concat = signature.classical.concatenate(xp.concat) + + self.add = signature.classical.elementwise(xp.add, num_outputs=1) + self.subtract = signature.classical.elementwise(xp.subtract, num_outputs=1) + self.multiply = signature.classical.elementwise(xp.multiply, num_outputs=1) + self.true_divide = signature.classical.elementwise(xp.true_divide, num_outputs=1) + self.floor_divide = signature.classical.elementwise(xp.floor_divide, num_outputs=1) + self.divide = signature.classical.elementwise(xp.divide, num_outputs=1) + self.logical_and = signature.classical.elementwise(xp.logical_and, num_outputs=1) + self.logical_or = signature.classical.elementwise(xp.logical_or, num_outputs=1) + self.where = signature.classical.elementwise(xp.where, num_outputs=1) + self.maximum = signature.classical.elementwise(xp.maximum, num_outputs=1) + self.minimum = signature.classical.elementwise(xp.minimum, num_outputs=1) + self.less = signature.classical.elementwise(xp.less, num_outputs=1) + self.less_equal = signature.classical.elementwise(xp.less_equal, num_outputs=1) + self.greater = signature.classical.elementwise(xp.greater, num_outputs=1) + self.greater_equal = signature.classical.elementwise(xp.greater_equal, num_outputs=1) + self.equal = signature.classical.elementwise(xp.equal, num_outputs=1) + self.not_equal = signature.classical.elementwise(xp.not_equal, num_outputs=1) + self.logaddexp = signature.classical.elementwise(xp.logaddexp, num_outputs=1) + self.exp = signature.classical.elementwise(xp.exp, num_outputs=1) + self.log = signature.classical.elementwise(xp.log, num_outputs=1) + self.negative = signature.classical.elementwise(xp.negative, num_outputs=1) + self.remainder = signature.classical.elementwise(xp.remainder, num_outputs=1) + + self.sum = signature.classical.reduce(xp.sum) + self.mean = signature.classical.reduce(xp.mean) + self.var = signature.classical.reduce(xp.var) + self.std = signature.classical.reduce(xp.std) + self.prod = signature.classical.reduce(xp.prod) + self.count_nonzero = signature.classical.reduce(xp.count_nonzero) + self.all = signature.classical.reduce(xp.all) + self.any = signature.classical.reduce(xp.any) + self.min = signature.classical.reduce(xp.min) + self.max = signature.classical.reduce(xp.max) + self.argmax = signature.classical.reduce(xp.argmax) + self.argmin = signature.classical.reduce(xp.argmin) + + self.getitem = signature.classical.getitem() + self.take = signature.classical.take(xp.take) + + self.dot = signature.classical.dot(xp.dot) + self.matmul = signature.classical.matmul(xp.matmul) + self.einsum = signature.classical.einsum(xp.einsum) + + self.roll = signature.classical.preserve_shape(xp.roll) + self.flip = signature.classical.preserve_shape(xp.flip) + self.sort = signature.classical.preserve_shape(xp.sort) + self.argsort = signature.classical.preserve_shape(xp.argsort) + + self.linalg = types.SimpleNamespace(diagonal=signature.classical.diagonal(lambda x: self._get_xp().linalg.diagonal(x), axis_always_last=True)) + + @property + def int32(self): + return self._get_xp().int32 + + @property + def int64(self): + return self._get_xp().int64 + + @property + def float32(self): + return self._get_xp().float32 + + @property + def float64(self): + return self._get_xp().float64 + + @property + def bool(self): + return self._get_xp().bool diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/functions.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..7c0bf7472e9cee0c4bfbf0b2d8be826aca9027e4 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/functions.py @@ -0,0 +1,511 @@ +import einx._src.tracer as tracer +import numpy as np +from functools import partial +from einx._src.util.functools import use_name_of +import einx._src.util.pytree as pytree + + +def _get_shape(x): + if isinstance(x, tracer.signature.classical.Tensor | tracer.signature.classical.ConvertibleTensor): + return tuple(x.shape) + elif isinstance(x, int | float | bool | np.integer | np.floating | np.bool_): + return () + else: + raise ValueError(f"Object of type {type(x)} is not a tensor or scalar") + + +def preserve_shape(op, num_outputs=1): + @use_name_of(op) + def inner(x, **kwargs): + shape = _get_shape(x) + x = op(x, **kwargs) + + if num_outputs == 1: + output = partial(tracer.signature.classical.Tensor, shape=shape) + else: + assert num_outputs > 1 + output = lambda origin: tuple(tracer.signature.classical.Tensor(origin, shape=shape) for _ in range(num_outputs)) + + return tracer.cast(x, output) + + return inner + + +def set_shape(op): + @use_name_of(op) + def inner(x, shape): + x = op(x, shape) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape)) + return x + + return inner + + +def transpose(op): + @use_name_of(op) + def inner(x, axes): + shape_in = _get_shape(x) + shape = tuple(shape_in[i] for i in axes) + x = op(x, axes) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape)) + return x + + return inner + + +def diagonal(op, argname_axis1="axis1", argname_axis2="axis2", axis_always_last=False): + @use_name_of(op) + def inner(x, **kwargs): + if axis_always_last: + axis1 = x.ndim - 2 + axis2 = x.ndim - 1 + else: + if argname_axis1 not in kwargs: + raise ValueError(f"Missing required argument '{argname_axis1}' in diagonal") + if argname_axis2 not in kwargs: + raise ValueError(f"Missing required argument '{argname_axis2}' in diagonal") + axis1 = kwargs.pop(argname_axis1) + axis2 = kwargs.pop(argname_axis2) + + shape_in = list(_get_shape(x)) + if axis1 < 0: + axis1 += len(shape_in) + if axis2 < 0: + axis2 += len(shape_in) + if axis1 < 0 or axis1 >= len(shape_in) or axis2 < 0 or axis2 >= len(shape_in): + raise ValueError(f"Invalid axis indices for diagonal: {axis1}, {axis2}") + + if shape_in[axis1] != shape_in[axis2]: + raise ValueError(f"Cannot take diagonal over axes of different length: {shape_in[axis1]} and {shape_in[axis2]}") + l = shape_in[axis1] + + shape_out = list(shape_in) + del shape_out[max(axis1, axis2)] + del shape_out[min(axis1, axis2)] + shape_out.append(l) + shape_out = tuple(shape_out) + + if not axis_always_last: + kwargs = {argname_axis1: axis1, argname_axis2: axis2} | kwargs + x = op(x, **kwargs) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape_out)) + + return x + + return inner + + +def reduce(op, argname_axis="axis", argname_keepdims="keepdims"): + @use_name_of(op) + def inner(x, **kwargs): + shape = list(_get_shape(x)) + if argname_axis not in kwargs or kwargs[argname_axis] is None: + axes = list(range(x.ndim)) + elif isinstance(kwargs[argname_axis], int): + axes = [kwargs[argname_axis]] + else: + axes = kwargs[argname_axis] + + if argname_keepdims in kwargs and kwargs[argname_keepdims]: + for a in axes: + shape[a] = 1 + else: + for a in sorted(axes, reverse=True): + del shape[a] + shape = tuple(shape) + x = op(x, **kwargs) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape)) + return x + + return inner + + +def elementwise(op, num_outputs=1): + @use_name_of(op) + def inner(*xs): + shape = None + for a in xs: + if hasattr(a, "shape"): + if shape is None: + shape = a.shape + else: + shape2 = a.shape + while len(shape) < len(shape2): + shape = (1,) + shape + while len(shape2) < len(shape): + shape2 = (1,) + shape2 + shape = np.maximum(shape, shape2) + if shape is None: + raise ValueError("elementwise operation requires at least one tensor as argument") + + x = op(*xs) + + if num_outputs == 1: + output = partial(tracer.signature.classical.Tensor, shape=shape) + else: + assert num_outputs > 1 + output = lambda origin: tuple(tracer.signature.classical.Tensor(origin, shape=shape) for _ in range(num_outputs)) + + return tracer.cast(x, output) + + return inner + + +def matmul(op): + def matmul(x, y): + if x.ndim != y.ndim: + raise ValueError(f"matmul requires input tensors to have the same number of dimensions, got {x.ndim} and {y.ndim}") + if x.ndim < 2 or y.ndim < 2: + raise ValueError(f"matmul requires input tensors to have at least 2 dimensions, got {x.ndim} and {y.ndim}") + shape = tuple(np.maximum(x.shape[:-2], y.shape[:-2])) + (x.shape[-2], y.shape[-1]) + + x = op(x, y) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape)) + return x + + return matmul + + +def take(op, argname_axis="axis"): + @use_name_of(op) + def inner(x, indices, **kwargs): + if argname_axis in kwargs: + axis = kwargs[argname_axis] + else: + axis = None + if axis is None: + shape = indices.shape + else: + axis2 = axis + if axis2 < 0: + axis2 += x.ndim + if axis2 < 0 or axis2 >= x.ndim: + raise ValueError(f"axis {axis} out of bounds for array of dimension {x.ndim}") + if hasattr(indices, "shape"): + indices_shape = tuple(indices.shape) + else: + indices_shape = () + + shape = tuple(x.shape[:axis2]) + indices_shape + tuple(x.shape[axis2 + 1 :]) + + x = op(x, indices, **kwargs) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape)) + return x + + return inner + + +def inplace(op): + if not isinstance(op, tracer.Tracer): + raise ValueError("op must be Tracer") + + @use_name_of(op) + def inner(x, *args, **kwargs): + return tracer.signature.python.call_inplace(x, op, [x, *args], kwargs) + + return inner + + +def getitem(): + def getitem(tensor, key): + if isinstance(key, tuple): + # Tuple of indices are given -> one for each dimension of tensor + if len(key) != tensor.ndim: + raise ValueError(f"Number of indices ({len(key)}) must match the rank of the tensor ({tensor.ndim})") + + in_shape = list(tensor.shape) + shape = [] + for k in key: + if isinstance(k, np.integer | int) or ( + isinstance(k, tracer.signature.classical.Tensor | tracer.signature.classical.ConvertibleTensor) and k.ndim == 0 + ): + in_shape = in_shape[1:] + elif k == slice(None) or k == slice(None, None, -1): + shape.append(in_shape[0]) + in_shape = in_shape[1:] + elif k is None: + shape.append(1) + else: + raise NotImplementedError(f"Key type {type(k)} not supported") + shape = tuple(shape) + tuple(in_shape) + else: + # Single index given -> only supported for 1D tensors + if tensor.ndim != 1: + raise ValueError(f"Single index only supported for 1D tensors, got {tensor.ndim}D tensor") + shape = tuple(key.shape) + + x = tracer.signature.python.getitem(tensor, key) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape)) + return x + + return getitem + + +def setitem(op=None): + if op is None: + op = tracer.signature.python.setitem + + def setitem(x, *args, **kwargs): + tracer_type = x._tracer_type + x = op(x, *args, **kwargs) + x = tracer.cast(x, tracer_type) + return x + + return setitem + + +def arange(op): + @use_name_of(op) + def inner(n, *args, **kwargs): + shape = (n,) + x = op(n, *args, **kwargs) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape)) + return x + + return inner + + +def concatenate(op, argname_axis="axis"): + @use_name_of(op) + def inner(xs, **kwargs): + if argname_axis in kwargs: + axis = kwargs[argname_axis] + else: + axis = 0 + if axis < 0: + axis += xs[0].ndim + if axis < 0 or axis >= xs[0].ndim: + raise ValueError(f"axis {axis} out of bounds for array of dimension {xs[0].ndim}") + + shape = list(xs[0].shape) + shape[axis] = sum(x.shape[axis] for x in xs) + shape = tuple(shape) + + x = op(xs, **kwargs) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape)) + return x + + return inner + + +def split(op, cumulative, argname_axis="axis"): + @use_name_of(op) + def inner(x, arg1, **kwargs): + if argname_axis in kwargs: + axis = kwargs[argname_axis] + else: + axis = 0 + if axis < 0: + axis += x.ndim + if axis < 0 or axis >= x.ndim: + raise ValueError(f"axis {axis} out of bounds for array of dimension {x.ndim}") + + if isinstance(arg1, int): + section_length = x.shape[axis] // arg1 + if section_length * arg1 != x.shape[0]: + raise ValueError(f"array split does not result in an equal division: {x.shape[axis]} % {arg1} != 0") + lengths = [section_length] * arg1 + else: + if cumulative: + indices = [0] + list(arg1) + [x.shape[axis]] + lengths = [indices[i + 1] - indices[i] for i in range(len(indices) - 1)] + else: + lengths = arg1 + + shapes = [] + for length in lengths: + shape = list(x.shape) + shape[axis] = int(length) + shapes.append(tuple(shape)) + + xs = op(x, arg1, **kwargs) + xs = tracer.cast(xs, lambda origin: [tracer.signature.classical.Tensor(origin, shape=shape) for shape in shapes]) + return xs + + return inner + + +def dot(op): + @use_name_of(op) + def inner(x, y): + if x.ndim != 1 or y.ndim != 1: + raise ValueError(f"dot only supports 1D tensors, got {x.ndim}D and {y.ndim}D") + + x = op(x, y) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=())) + return x + + return inner + + +def tensordot(op, argname_axes="axes"): + @use_name_of(op) + def inner(a, b, **kwargs): + if argname_axes in kwargs: + axes = kwargs[argname_axes] + else: + raise ValueError(f"Missing required argument '{argname_axes}' in tensordot") + + if isinstance(axes, int): + axes_a = list(range(a.ndim - axes, a.ndim)) + axes_b = list(range(axes)) + elif isinstance(axes, tuple | list) and len(axes) == 2: + axes_a, axes_b = axes + if isinstance(axes_a, int): + axes_a = [axes_a] + if isinstance(axes_b, int): + axes_b = [axes_b] + else: + raise ValueError(f"Invalid axes argument for tensordot: {axes}") + if len(axes_a) != len(axes_b): + raise ValueError(f"Axes lengths do not match: {len(axes_a)} != {len(axes_b)}") + + def canonicalize_axis(axis, ndim): + if axis < 0: + axis += ndim + if axis < 0 or axis >= ndim: + raise ValueError("Invalid axis index in tensordot") + return axis + + axes_a = [canonicalize_axis(axis, a.ndim) for axis in axes_a] + axes_b = [canonicalize_axis(axis, b.ndim) for axis in axes_b] + + a_remain = [i for i in range(a.ndim) if i not in axes_a] + b_remain = [i for i in range(b.ndim) if i not in axes_b] + shape = tuple([a.shape[i] for i in a_remain] + [b.shape[i] for i in b_remain]) + + x = op(a, b, **kwargs) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape)) + return x + + return inner + + +def einsum(op): + @use_name_of(op) + def inner(subscripts, *tensors): + exprs = subscripts.split("->")[0].split(",") + if len(exprs) != len(tensors): + raise ValueError(f"Expected {len(exprs)} tensors, got {len(tensors)}") + values = {} + for i, (expr, tensor) in enumerate(zip(exprs, tensors, strict=False)): + expr = expr.strip().replace(" ", "") + if len(expr) != len(tensor.shape): + raise ValueError(f"Expected {len(expr)} axes, got {len(tensor.shape)} for {i}-th (zero-based) input tensor") + for axis, value in zip(expr, tensor.shape, strict=False): + if axis in values: + if values[axis] != value: + raise ValueError(f"Got conflicting values for axis {axis}: {values[axis]} and {value}") + else: + values[axis] = value + expr_out = subscripts.split("->")[-1].strip().replace(" ", "") + shape_out = tuple(values[axis] for axis in expr_out) + + x = op(subscripts, *tensors) + x = tracer.cast(x, partial(tracer.signature.classical.Tensor, shape=shape_out)) + return x + + return inner + + +def _to_shapes_inner(axes, shapes_outer): + shapes_inner = [] + n = None + for axis, shape_outer in zip(axes, shapes_outer, strict=False): + shape_inner = list(shape_outer) + if axis is not None: + if axis < 0: + axis += len(shape_outer) + if axis < 0 or axis >= len(shape_outer): + raise ValueError("Invalid axis index in vmap") + if n is None: + n = shape_inner[axis] + elif n != shape_inner[axis]: + raise ValueError("Inconsistent axis sizes in vmap") + del shape_inner[axis] + shapes_inner.append(shape_inner) + return shapes_inner, n + + +def _to_shapes_outer(axes, shapes_inner, n): + shapes_outer = [] + for axis, shape_inner in zip(axes, shapes_inner, strict=False): + shape_outer = list(shape_inner) + if axis is not None: + if axis < 0: + axis += len(shape_inner) + 1 + if axis < 0 or axis >= len(shape_inner) + 1: + raise ValueError("Invalid axis index in vmap") + shape_outer.insert(axis, n) + shapes_outer.append(shape_outer) + return shapes_outer + + +def vmap(original_vmap): + @use_name_of(original_vmap) + def vmap_with_shapes(op, in_axes=0, out_axes=0): + if isinstance(in_axes, int | np.integer): + in_axes = (in_axes,) + if isinstance(out_axes, int | np.integer): + out_axes = (out_axes,) + if not isinstance(in_axes, tuple): + raise ValueError(f"Expected in_axes to be a tuple or int, got {type(in_axes)}") + if not isinstance(out_axes, tuple): + raise ValueError(f"Expected out_axes to be a tuple or int, got {type(out_axes)}") + + def vmapped_op_with_shapes(*tensors): + if len(tensors) != len(in_axes): + raise ValueError(f"Expected {len(in_axes)} arguments in vmapped function, got {len(tensors)}") + + # Get vmapped input shapes + in_shapes_outer = [t.shape for t in tensors] + in_shapes_inner, vmapped_axis_len = _to_shapes_inner(in_axes, in_shapes_outer) + + # Create inner graph + in_tracers_inner = [tracer.signature.classical.Tensor(None, shape) for shape in in_shapes_inner] + out_tracers_inner = op(*in_tracers_inner) + if not isinstance(out_tracers_inner, tracer.signature.classical.Tensor) and not ( + isinstance(out_tracers_inner, tuple) and all(isinstance(t, tracer.signature.classical.Tensor) for t in out_tracers_inner) + ): + raise ValueError(f"Expected vmapped function to return a tensor or tuple of tensor, got {pytree.map(type, out_tracers_inner)}") + graph = tracer.Graph(in_tracers_inner, out_tracers_inner) + + # Get vmapped output shapes + if isinstance(out_tracers_inner, tracer.Tracer): + out_tracers_inner = [out_tracers_inner] + out_shapes_inner = [t.shape for t in out_tracers_inner] + out_shapes_outer = _to_shapes_outer(out_axes, out_shapes_inner, vmapped_axis_len) + + # Run vmapped function (return value is a simple tracer, since original_vmap is a simple tracer) + tensors = original_vmap(graph, in_axes=in_axes if len(in_axes) > 1 else in_axes[0], out_axes=out_axes if len(out_axes) > 1 else out_axes[0])( + *tensors + ) + + # Cast return values to the expected tensor types + if len(out_axes) == 1: + return tracer.cast(tensors, partial(tracer.signature.classical.Tensor, shape=out_shapes_outer[0])) + else: + return tracer.cast(tensors, lambda origin: tuple(tracer.signature.classical.Tensor(origin, shape=shape) for shape in out_shapes_outer)) + + return vmapped_op_with_shapes + + return vmap_with_shapes + + +class at: + def __init__(self, x, indices): + self._x = x + self._indices = indices + self.set = _at_updater(self, "set") + self.add = _at_updater(self, "add") + self.subtract = _at_updater(self, "subtract") + + +def _at_updater(self, op): + @use_name_of(op) + def inner(updates): + x = tracer.signature.python.getattr(tracer.signature.python.getattr(self._x, "at")[self._indices], op)(updates) + x = tracer.cast(x, self._x._tracer_type) + return x + + return inner diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/jax.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/jax.py new file mode 100644 index 0000000000000000000000000000000000000000..c6d9d4f54f2d11486c629ada94aac92fcc08813b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/jax.py @@ -0,0 +1,20 @@ +import einx._src.tracer as tracer +import einx._src.tracer.signature as signature +import types + + +class jax: + def __init__(self): + jax = tracer.signature.python.import_("jax") + jnp = tracer.signature.python.import_("jax.numpy", as_="jnp") + + self.numpy = signature.numpy(jnp) + self.numpy.ndarray.at = signature.classical.at + + self.vmap = signature.classical.vmap(jax.vmap) + self.nn = types.SimpleNamespace( + logsumexp=signature.classical.reduce(jax.nn.logsumexp), + softmax=signature.classical.preserve_shape(jax.nn.softmax), + log_softmax=signature.classical.preserve_shape(jax.nn.log_softmax), + ) + self.lax = types.SimpleNamespace(stop_gradient=signature.classical.preserve_shape(jax.lax.stop_gradient)) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/mlx.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/mlx.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1e1c4792a1d027376e1cbd518f3cb6d952342e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/mlx.py @@ -0,0 +1,89 @@ +import einx._src.tracer as tracer +import einx._src.tracer.signature as signature +from functools import partial + + +class nn: + def __init__(self, nn): + self.softmax = signature.classical.preserve_shape(nn.softmax) + self.log_softmax = signature.classical.preserve_shape(nn.log_softmax) + + +class core: + def __init__(self, mx): + self.array = mx.array + self.array.__getitem__ = signature.classical.getitem() + self.array.__setitem__ = signature.classical.setitem() + self.array.at = signature.classical.at + + self.reshape = signature.classical.set_shape(mx.reshape) + self.transpose = signature.classical.transpose(mx.transpose) + self.broadcast_to = signature.classical.set_shape(mx.broadcast_to) + self.arange = signature.classical.arange(mx.arange) + self.concatenate = signature.classical.concatenate(mx.concatenate) + self.split = signature.classical.split(mx.split, cumulative=True) + self.diagonal = signature.classical.diagonal(mx.diagonal) + + self.add = signature.classical.elementwise(mx.add, num_outputs=1) + self.subtract = signature.classical.elementwise(mx.subtract, num_outputs=1) + self.multiply = signature.classical.elementwise(mx.multiply, num_outputs=1) + self.true_divide = signature.classical.elementwise(mx.true_divide, num_outputs=1) + self.floor_divide = signature.classical.elementwise(mx.floor_divide, num_outputs=1) + self.divide = signature.classical.elementwise(mx.divide, num_outputs=1) + self.logical_and = signature.classical.elementwise(mx.logical_and, num_outputs=1) + self.logical_or = signature.classical.elementwise(mx.logical_or, num_outputs=1) + self.where = signature.classical.elementwise(mx.where, num_outputs=1) + self.maximum = signature.classical.elementwise(mx.maximum, num_outputs=1) + self.minimum = signature.classical.elementwise(mx.minimum, num_outputs=1) + self.less = signature.classical.elementwise(mx.less, num_outputs=1) + self.less_equal = signature.classical.elementwise(mx.less_equal, num_outputs=1) + self.greater = signature.classical.elementwise(mx.greater, num_outputs=1) + self.greater_equal = signature.classical.elementwise(mx.greater_equal, num_outputs=1) + self.equal = signature.classical.elementwise(mx.equal, num_outputs=1) + self.not_equal = signature.classical.elementwise(mx.not_equal, num_outputs=1) + self.logaddexp = signature.classical.elementwise(mx.logaddexp, num_outputs=1) + self.exp = signature.classical.elementwise(mx.exp, num_outputs=1) + self.log = signature.classical.elementwise(mx.log, num_outputs=1) + self.negative = signature.classical.elementwise(mx.negative, num_outputs=1) + self.divmod = signature.classical.elementwise(mx.divmod, num_outputs=2) + + self.sum = signature.classical.reduce(mx.sum) + self.mean = signature.classical.reduce(mx.mean) + self.var = signature.classical.reduce(mx.var) + self.std = signature.classical.reduce(mx.std) + self.prod = signature.classical.reduce(mx.prod) + self.count_nonzero = signature.classical.reduce(mx.count_nonzero) + self.all = signature.classical.reduce(mx.all) + self.any = signature.classical.reduce(mx.any) + self.min = signature.classical.reduce(mx.min) + self.max = signature.classical.reduce(mx.max) + self.argmax = signature.classical.reduce(mx.argmax) + self.argmin = signature.classical.reduce(mx.argmin) + self.logsumexp = signature.classical.reduce(mx.logsumexp) + + self.take = signature.classical.take(mx.take) + + self.tensordot = signature.classical.tensordot(mx.tensordot) + self.matmul = signature.classical.matmul(mx.matmul) + self.einsum = signature.classical.einsum(mx.einsum) + + self.roll = signature.classical.preserve_shape(mx.roll) + self.flip = signature.classical.preserve_shape(mx.flip) + self.sort = signature.classical.preserve_shape(mx.sort) + self.argsort = signature.classical.preserve_shape(mx.argsort) + + self.vmap = signature.classical.vmap(mx.vmap) + + self.int32 = mx.int32 + self.int64 = mx.int64 + self.float32 = mx.float32 + self.float64 = mx.float64 + self.bool = mx.bool_ + + self.stop_gradient = signature.classical.preserve_shape(mx.stop_gradient) + + +class mlx: + def __init__(self): + self.core = core(tracer.signature.python.import_("mlx.core", as_="mx")) + self.nn = nn(tracer.signature.python.import_("mlx.nn", as_="mnn")) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/numpy.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..684a67648f93382d144e173ca56592754456287d --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/numpy.py @@ -0,0 +1,70 @@ +import einx._src.tracer as tracer +import einx._src.tracer.signature as signature + + +class numpy: + def __init__(self, np=None): + if np is None: + np = tracer.signature.python.import_("numpy", as_="np") + + self.ndarray = np.ndarray + self.ndarray.__getitem__ = signature.classical.getitem() + + self.asarray = signature.classical.preserve_shape(np.asarray) + self.reshape = signature.classical.set_shape(np.reshape) + self.transpose = signature.classical.transpose(np.transpose) + self.broadcast_to = signature.classical.set_shape(np.broadcast_to) + self.arange = signature.classical.arange(np.arange) + self.concatenate = signature.classical.concatenate(np.concatenate) + self.split = signature.classical.split(np.split, cumulative=True) + self.diagonal = signature.classical.diagonal(np.diagonal) + + self.add = signature.classical.elementwise(np.add, num_outputs=1) + self.subtract = signature.classical.elementwise(np.subtract, num_outputs=1) + self.multiply = signature.classical.elementwise(np.multiply, num_outputs=1) + self.true_divide = signature.classical.elementwise(np.true_divide, num_outputs=1) + self.floor_divide = signature.classical.elementwise(np.floor_divide, num_outputs=1) + self.divide = signature.classical.elementwise(np.divide, num_outputs=1) + self.logical_and = signature.classical.elementwise(np.logical_and, num_outputs=1) + self.logical_or = signature.classical.elementwise(np.logical_or, num_outputs=1) + self.where = signature.classical.elementwise(np.where, num_outputs=1) + self.maximum = signature.classical.elementwise(np.maximum, num_outputs=1) + self.minimum = signature.classical.elementwise(np.minimum, num_outputs=1) + self.less = signature.classical.elementwise(np.less, num_outputs=1) + self.less_equal = signature.classical.elementwise(np.less_equal, num_outputs=1) + self.greater = signature.classical.elementwise(np.greater, num_outputs=1) + self.greater_equal = signature.classical.elementwise(np.greater_equal, num_outputs=1) + self.equal = signature.classical.elementwise(np.equal, num_outputs=1) + self.not_equal = signature.classical.elementwise(np.not_equal, num_outputs=1) + self.logaddexp = signature.classical.elementwise(np.logaddexp, num_outputs=1) + self.exp = signature.classical.elementwise(np.exp, num_outputs=1) + self.log = signature.classical.elementwise(np.log, num_outputs=1) + self.negative = signature.classical.elementwise(np.negative, num_outputs=1) + self.divmod = signature.classical.elementwise(np.divmod, num_outputs=2) + + self.sum = signature.classical.reduce(np.sum) + self.mean = signature.classical.reduce(np.mean) + self.var = signature.classical.reduce(np.var) + self.std = signature.classical.reduce(np.std) + self.prod = signature.classical.reduce(np.prod) + self.count_nonzero = signature.classical.reduce(np.count_nonzero) + self.all = signature.classical.reduce(np.all) + self.any = signature.classical.reduce(np.any) + self.min = signature.classical.reduce(np.min) + self.max = signature.classical.reduce(np.max) + self.argmax = signature.classical.reduce(np.argmax) + self.argmin = signature.classical.reduce(np.argmin) + + self.take = signature.classical.take(np.take) + self.put = signature.classical.inplace(np.put) + self.add.at = signature.classical.inplace(np.add.at) + self.subtract.at = signature.classical.inplace(np.subtract.at) + + self.dot = signature.classical.dot(np.dot) + self.matmul = signature.classical.matmul(np.matmul) + self.einsum = signature.classical.einsum(np.einsum) + + self.roll = signature.classical.preserve_shape(np.roll) + self.flip = signature.classical.preserve_shape(np.flip) + self.sort = signature.classical.preserve_shape(np.sort) + self.argsort = signature.classical.preserve_shape(np.argsort) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/tensor.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..3ed244812cf2a2ed1f28cdfdf0ca6a7d3468bf41 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/tensor.py @@ -0,0 +1,52 @@ +import einx._src.tracer as tracer +from functools import partial +from einx._src.util.lru_cache import _freeze_value + + +class ConvertibleTensor(tracer.Tracer): + def __init__(self, origin, concrete, shape): + tracer.Tracer.__init__(self, origin=origin) + if not hasattr(concrete, "type"): + raise ValueError("Concrete must have a 'type' attribute.") + self.concrete = concrete + self.shape = tuple(int(s) for s in shape) if shape is not None else None + + @property + def _tracer_type(self): + return partial(ConvertibleTensor, concrete=self.concrete, shape=self.shape) + + def __eq__(self, other): + if isinstance(other, ConvertibleTensor): + return self.origin == other.origin and self.concrete == other.concrete and self.shape == other.shape + return False + + def __hash__(self): + if self.origin is not None: + raise ValueError("Can only hash a tracer without an origin.") + return hash(self.shape) + hash(_freeze_value(self.concrete)) + + @property + def ndim(self): + return len(self.shape) + + +class Tensor(tracer.Tracer): + def __init__(self, origin, shape): + super().__init__(origin=origin) + self.shape = tuple(int(s) for s in shape) + + @property + def _tracer_type(self): + return partial(Tensor, shape=self.shape) + + def __eq__(self, other): + if isinstance(other, Tensor): + return self.origin == other.origin and self.shape == other.shape + return False + + def __hash__(self): + return 1 + hash(self.shape) + + @property + def ndim(self): + return len(self.shape) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/tensorflow.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..108a3b685f9c806aa13a21cfffdd15e71c4d1491 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/tensorflow.py @@ -0,0 +1,94 @@ +import einx._src.tracer as tracer +import einx._src.tracer.signature as signature +import types + + +class math: + def __init__(self, math): + self.add = signature.classical.elementwise(math.add, num_outputs=1) + self.subtract = signature.classical.elementwise(math.subtract, num_outputs=1) + self.multiply = signature.classical.elementwise(math.multiply, num_outputs=1) + self.truediv = signature.classical.elementwise(math.truediv, num_outputs=1) + self.floordiv = signature.classical.elementwise(math.floordiv, num_outputs=1) + self.floormod = signature.classical.elementwise(math.floormod, num_outputs=1) + self.divide = signature.classical.elementwise(math.divide, num_outputs=1) + self.logical_and = signature.classical.elementwise(math.logical_and, num_outputs=1) + self.logical_or = signature.classical.elementwise(math.logical_or, num_outputs=1) + + self.maximum = signature.classical.elementwise(math.maximum, num_outputs=1) + self.minimum = signature.classical.elementwise(math.minimum, num_outputs=1) + self.less = signature.classical.elementwise(math.less, num_outputs=1) + self.less_equal = signature.classical.elementwise(math.less_equal, num_outputs=1) + self.greater = signature.classical.elementwise(math.greater, num_outputs=1) + self.greater_equal = signature.classical.elementwise(math.greater_equal, num_outputs=1) + self.equal = signature.classical.elementwise(math.equal, num_outputs=1) + self.not_equal = signature.classical.elementwise(math.not_equal, num_outputs=1) + self.exp = signature.classical.elementwise(math.exp, num_outputs=1) + self.log = signature.classical.elementwise(math.log, num_outputs=1) + self.negative = signature.classical.elementwise(math.negative, num_outputs=1) + + self.reduce_sum = signature.classical.reduce(math.reduce_sum) + self.reduce_mean = signature.classical.reduce(math.reduce_mean) + self.reduce_variance = signature.classical.reduce(math.reduce_variance) + self.reduce_std = signature.classical.reduce(math.reduce_std) + self.reduce_prod = signature.classical.reduce(math.reduce_prod) + self.count_nonzero = signature.classical.reduce(math.count_nonzero) + self.reduce_all = signature.classical.reduce(math.reduce_all) + self.reduce_any = signature.classical.reduce(math.reduce_any) + self.reduce_min = signature.classical.reduce(math.reduce_min) + self.reduce_max = signature.classical.reduce(math.reduce_max) + self.reduce_logsumexp = signature.classical.reduce(math.reduce_logsumexp) + self.argmax = signature.classical.reduce(math.argmax) + self.argmin = signature.classical.reduce(math.argmin) + + +class tensorflow: + def __init__(self, tf=None): + if tf is None: + tf = tracer.signature.python.import_("tensorflow", as_="tf") + + self.Tensor = tf.Tensor + self.Tensor.__getitem__ = signature.classical.getitem() + + self.as_dtype = tf.as_dtype + + self.convert_to_tensor = signature.classical.preserve_shape(tf.convert_to_tensor) + self.reshape = signature.classical.set_shape(tf.reshape) + self.transpose = signature.classical.transpose(tf.transpose) + self.broadcast_to = signature.classical.set_shape(tf.broadcast_to) + self.range = signature.classical.arange(tf.range) + self.concat = signature.classical.concatenate(tf.concat) + self.split = signature.classical.split(tf.split, cumulative=False) + + self.where = signature.classical.elementwise(tf.where, num_outputs=1) + + self.tensordot = signature.classical.tensordot(tf.tensordot) + self.matmul = signature.classical.matmul(tf.matmul) + self.einsum = signature.classical.einsum(tf.einsum) + + self.roll = signature.classical.preserve_shape(tf.roll) + self.reverse = signature.classical.preserve_shape(tf.reverse) + self.sort = signature.classical.preserve_shape(tf.sort) + self.argsort = signature.classical.preserve_shape(tf.argsort) + + self.argmin = signature.classical.reduce(tf.argmin) + self.argmax = signature.classical.reduce(tf.argmax) + + self.stop_gradient = signature.classical.preserve_shape(tf.stop_gradient) + + self.gather = signature.classical.take(tf.gather) + self.tensor_scatter_nd_update = signature.classical.setitem(tf.tensor_scatter_nd_update) + self.tensor_scatter_nd_add = signature.classical.setitem(tf.tensor_scatter_nd_add) + self.tensor_scatter_nd_sub = signature.classical.setitem(tf.tensor_scatter_nd_sub) + + self.math = math(tf.math) + + # self.experimental = types.SimpleNamespace( + # numpy=signature.numpy(tf.experimental.numpy), + # ) + + self.linalg = types.SimpleNamespace(diag_part=signature.classical.diagonal(tf.linalg.diag_part, axis_always_last=True)) + + self.nn = types.SimpleNamespace( + softmax=signature.classical.preserve_shape(tf.nn.softmax), log_softmax=signature.classical.preserve_shape(tf.nn.log_softmax) + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/tinygrad.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/tinygrad.py new file mode 100644 index 0000000000000000000000000000000000000000..2c55fbbf1055552366c53f40c96142f103dcc412 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/tinygrad.py @@ -0,0 +1,88 @@ +import einx._src.tracer as tracer +import einx._src.tracer.signature as signature + + +class tinygrad: + def __init__(self, tinygrad=None): + if tinygrad is None: + tinygrad = tracer.signature.python.import_("tinygrad") + + if isinstance(tinygrad, tracer.Tracer): + self.Tensor = tracer.cast(tinygrad.Tensor, lambda origin: Tensor(tinygrad.Tensor, origin=origin)) + else: + self.Tensor = Tensor(tinygrad.Tensor) + + +class Tensor(tracer.Tracer): + @property + def _tracer_type(self): + return lambda origin: Tensor(self._Tensor, origin=origin) + + def __init__(self, Tensor, origin=None): + super().__init__(origin=origin) + self._Tensor = Tensor + + self.__getitem__ = signature.classical.getitem() + + if isinstance(Tensor, tracer.Tracer): + getattr = tracer.signature.python.getattr + else: + getattr = globals()["getattr"] + + self.reshape = signature.classical.set_shape(Tensor.reshape) + self.permute = signature.classical.transpose(Tensor.permute) + self.expand = signature.classical.set_shape(Tensor.expand) + self.arange = signature.classical.arange(Tensor.arange) + self.cat = signature.classical.concatenate(lambda tensors, **kwargs: Tensor.cat(*tensors, **kwargs), argname_axis="dim") + self.split = signature.classical.split(Tensor.split, cumulative=False, argname_axis="dim") + + self.detach = signature.classical.preserve_shape(Tensor.detach) + + self.add = signature.classical.elementwise(Tensor.add, num_outputs=1) + self.sub = signature.classical.elementwise(Tensor.sub, num_outputs=1) + self.mul = signature.classical.elementwise(Tensor.mul, num_outputs=1) + self.div = signature.classical.elementwise(Tensor.div, num_outputs=1) + self.idiv = signature.classical.elementwise(Tensor.idiv, num_outputs=1) + self.where = signature.classical.elementwise(Tensor.where, num_outputs=1) + self.maximum = signature.classical.elementwise(Tensor.maximum, num_outputs=1) + self.minimum = signature.classical.elementwise(Tensor.minimum, num_outputs=1) + self.__lt__ = signature.classical.elementwise(getattr(Tensor, "__lt__"), num_outputs=1) + self.__le__ = signature.classical.elementwise(getattr(Tensor, "__le__"), num_outputs=1) + self.__gt__ = signature.classical.elementwise(getattr(Tensor, "__gt__"), num_outputs=1) + self.__ge__ = signature.classical.elementwise(getattr(Tensor, "__ge__"), num_outputs=1) + self.__eq__ = signature.classical.elementwise(getattr(Tensor, "__eq__"), num_outputs=1) + self.__ne__ = signature.classical.elementwise(getattr(Tensor, "__ne__"), num_outputs=1) + self.logaddexp = signature.classical.elementwise(Tensor.logaddexp, num_outputs=1) + self.exp = signature.classical.elementwise(Tensor.exp, num_outputs=1) + self.log = signature.classical.elementwise(Tensor.log, num_outputs=1) + self.neg = signature.classical.elementwise(Tensor.neg, num_outputs=1) + + self.sum = signature.classical.reduce(Tensor.sum, argname_keepdims="keepdim") + self.mean = signature.classical.reduce(Tensor.mean, argname_keepdims="keepdim") + self.var = signature.classical.reduce(Tensor.var, argname_keepdims="keepdim") + self.std = signature.classical.reduce(Tensor.std, argname_keepdims="keepdim") + self.prod = signature.classical.reduce(Tensor.prod, argname_keepdims="keepdim") + self.all = signature.classical.reduce(Tensor.all, argname_keepdims="keepdim") + self.any = signature.classical.reduce(Tensor.any, argname_keepdims="keepdim") + self.min = signature.classical.reduce(Tensor.min, argname_keepdims="keepdim") + self.max = signature.classical.reduce(Tensor.max, argname_keepdims="keepdim") + self.argmax = signature.classical.reduce(Tensor.argmax, argname_keepdims="keepdim") + self.argmin = signature.classical.reduce(Tensor.argmin, argname_keepdims="keepdim") + self.logsumexp = signature.classical.reduce(Tensor.logsumexp, argname_keepdims="keepdim") + + self.gather = signature.classical.take(lambda x, indices, axis=0: Tensor.gather(x, axis, indices)) + self.scatter = signature.classical.setitem(Tensor.scatter) + self.scatter_reduce = signature.classical.setitem(Tensor.scatter_reduce) + + self.dot = signature.classical.dot(Tensor.dot) + self.einsum = signature.classical.einsum(Tensor.einsum) + + self.roll = signature.classical.preserve_shape(Tensor.roll) + self.flip = signature.classical.preserve_shape(Tensor.flip) + self.sort = signature.classical.preserve_shape(Tensor.sort, num_outputs=2) + + self.softmax = signature.classical.preserve_shape(Tensor.softmax) + self.log_softmax = signature.classical.preserve_shape(Tensor.log_softmax) + + def __call__(self, *args, **kwargs): + return tracer.signature.python.call(self, args, kwargs) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/torch.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/torch.py new file mode 100644 index 0000000000000000000000000000000000000000..df7ddb6f65ef09e91485b12a9a69f8076bffdd4f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/classical/torch.py @@ -0,0 +1,92 @@ +import einx._src.tracer as tracer +import einx._src.tracer.signature as signature +import types + +from functools import partial + + +class torch: + def __init__(self, torch=None): + if torch is None: + torch = tracer.signature.python.import_("torch") + + self.Tensor = torch.Tensor + self.Tensor.__getitem__ = signature.classical.getitem() + self.Tensor.detach = signature.classical.preserve_shape(torch.Tensor.detach) + + self.asarray = signature.classical.preserve_shape(torch.asarray) + self.reshape = signature.classical.set_shape(torch.reshape) + self.permute = signature.classical.transpose(torch.permute) + self.broadcast_to = signature.classical.set_shape(torch.broadcast_to) + self.arange = signature.classical.arange(torch.arange) + self.cat = signature.classical.concatenate(torch.cat, argname_axis="dim") + self.split = signature.classical.split(torch.split, cumulative=False, argname_axis="dim") + self.diagonal = signature.classical.diagonal(torch.diagonal, argname_axis1="dim1", argname_axis2="dim2") + + self.add = signature.classical.elementwise(torch.add, num_outputs=1) + self.subtract = signature.classical.elementwise(torch.subtract, num_outputs=1) + self.multiply = signature.classical.elementwise(torch.multiply, num_outputs=1) + self.true_divide = signature.classical.elementwise(torch.true_divide, num_outputs=1) + self.floor_divide = signature.classical.elementwise(torch.floor_divide, num_outputs=1) + self.divide = signature.classical.elementwise(torch.divide, num_outputs=1) + self.remainder = signature.classical.elementwise(torch.remainder, num_outputs=1) + self.logical_and = signature.classical.elementwise(torch.logical_and, num_outputs=1) + self.logical_or = signature.classical.elementwise(torch.logical_or, num_outputs=1) + self.where = signature.classical.elementwise(torch.where, num_outputs=1) + self.maximum = signature.classical.elementwise(torch.maximum, num_outputs=1) + self.minimum = signature.classical.elementwise(torch.minimum, num_outputs=1) + self.less = signature.classical.elementwise(torch.less, num_outputs=1) + self.less_equal = signature.classical.elementwise(torch.less_equal, num_outputs=1) + self.greater = signature.classical.elementwise(torch.greater, num_outputs=1) + self.greater_equal = signature.classical.elementwise(torch.greater_equal, num_outputs=1) + self.eq = signature.classical.elementwise(torch.eq, num_outputs=1) + self.ne = signature.classical.elementwise(torch.ne, num_outputs=1) + self.logaddexp = signature.classical.elementwise(torch.logaddexp, num_outputs=1) + self.exp = signature.classical.elementwise(torch.exp, num_outputs=1) + self.log = signature.classical.elementwise(torch.log, num_outputs=1) + self.neg = signature.classical.elementwise(torch.neg, num_outputs=1) + + self.sum = signature.classical.reduce(torch.sum, argname_axis="dim", argname_keepdims="keepdim") + self.mean = signature.classical.reduce(torch.mean, argname_axis="dim", argname_keepdims="keepdim") + self.var = signature.classical.reduce(torch.var, argname_axis="dim", argname_keepdims="keepdim") + self.std = signature.classical.reduce(torch.std, argname_axis="dim", argname_keepdims="keepdim") + self.prod = signature.classical.reduce(torch.prod, argname_axis="dim", argname_keepdims="keepdim") + self.count_nonzero = signature.classical.reduce(torch.count_nonzero, argname_axis="dim", argname_keepdims="keepdim") + self.all = signature.classical.reduce(torch.all, argname_axis="dim", argname_keepdims="keepdim") + self.any = signature.classical.reduce(torch.any, argname_axis="dim", argname_keepdims="keepdim") + self.amin = signature.classical.reduce(torch.amin, argname_axis="dim", argname_keepdims="keepdim") + self.amax = signature.classical.reduce(torch.amax, argname_axis="dim", argname_keepdims="keepdim") + self.logsumexp = signature.classical.reduce(torch.logsumexp, argname_axis="dim", argname_keepdims="keepdim") + self.argmax = signature.classical.reduce(torch.argmax, argname_axis="dim", argname_keepdims="keepdim") + self.argmin = signature.classical.reduce(torch.argmin, argname_axis="dim", argname_keepdims="keepdim") + + self.take = signature.classical.take(torch.take) + self.index_put_ = signature.classical.setitem( + lambda x, key, value, *, accumulate: tracer.signature.python.getattr(x, "index_put_")((key,), value, accumulate=accumulate) + ) + + self.dot = signature.classical.dot(torch.dot) + self.matmul = signature.classical.matmul(torch.matmul) + self.einsum = signature.classical.einsum(torch.einsum) + + self.roll = signature.classical.preserve_shape(torch.roll) + self.flip = signature.classical.preserve_shape(torch.flip) + self.sort = signature.classical.preserve_shape(lambda *args, **kwargs: torch.sort(*args, **kwargs)[0]) + self.argsort = signature.classical.preserve_shape(torch.argsort) + + self.vmap = lambda func, in_dims, out_dims: signature.classical.vmap( + lambda func, in_axes, out_axes: torch.vmap(func, in_dims=in_axes, out_dims=out_axes) + )(func, in_axes=in_dims, out_axes=out_dims) + + self.nn = types.SimpleNamespace( + functional=types.SimpleNamespace( + softmax=signature.classical.preserve_shape(torch.nn.functional.softmax), + log_softmax=signature.classical.preserve_shape(torch.nn.functional.log_softmax), + ) + ) + + self.int32 = torch.int32 + self.int64 = torch.int64 + self.float32 = torch.float32 + self.float64 = torch.float64 + self.bool = torch.bool diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d870b9e5065bdc6cc92976250f345afbebfd204f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/__init__.py @@ -0,0 +1 @@ +from .tensor import Tensor diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3cb2881cfff5404a7552c6a5c36bcef2f1dc704c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/__pycache__/tensor.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/__pycache__/tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca69096ef374e9a8e93775c812bff4d904698119 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/__pycache__/tensor.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/tensor.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..fb10fd477ae0c997e7b5b4ae5bc2b1d4b28cb25f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/functorchdim/tensor.py @@ -0,0 +1,26 @@ +import einx._src.tracer as tracer +from functools import partial + + +class Tensor(tracer.Tracer): + def __init__(self, origin, shape): + super().__init__(origin=origin) + self.shape = shape + + @property + def _tracer_type(self): + return partial(Tensor, shape=self.shape) + + def __eq__(self, other): + if isinstance(other, Tensor): + return self.origin == other.origin and self.shape == other.shape + return False + + def __hash__(self): + return 234 + hash(self.shape) + + def dims(self): + return tracer.signature.python.call(tracer.signature.python.getattr(self, "dims")) + + def order(self, *dims): + return tracer.signature.python.call(tracer.signature.python.getattr(self, "order"), dims) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/python.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/python.py new file mode 100644 index 0000000000000000000000000000000000000000..6358b783537c349b313d6fc58f8fad8125d6d84b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/signature/python.py @@ -0,0 +1,362 @@ +import einx._src.tracer as tracer +from einx._src.util import pytree +import inspect + + +class GetAttr(tracer.Application): + def __init__(self, obj, key): + if not isinstance(key, str): + raise TypeError(f"key must be str, not {type(key)}") + super().__init__(inputs=[obj, key], output=Value) + self.obj = obj + self.key = key + + def _tracer_transform(self, transform): + return GetAttr(transform(self.obj), self.key) + + def __eq__(self, other): + if isinstance(other, GetAttr): + return self.obj == other.obj and self.key == other.key + return False + + +def getattr(obj, key): + return GetAttr(obj, key).output + + +class GetItem(tracer.Application): + def __init__(self, obj, key): + super().__init__(inputs=[obj, key], output=Value) + self.obj = obj + self.key = key + + def _tracer_transform(self, transform): + return GetItem(transform(self.obj), transform(self.key)) + + def __eq__(self, other): + if isinstance(other, GetItem): + return self.obj == other.obj and self.key == other.key + return False + + +def getitem(obj, key): + return GetItem(obj, key).output + + +class UpdateItem(tracer.Application): + def __init__(self, obj, key, value, op): + super().__init__(inputs=[obj, key, value], output=Value) + if not isinstance(op, str): + raise TypeError(f"op must be str, not {type(op)}") + self.obj = obj + self.key = key + self.value = value + self.op = op + + def _tracer_transform(self, transform): + return UpdateItem(transform(self.obj), transform(self.key), transform(self.value), self.op) + + def __eq__(self, other): + if isinstance(other, UpdateItem): + return self.obj == other.obj and self.key == other.key and self.value == other.value and self.op == other.op + return False + + +def setitem(obj, key, value): + return UpdateItem(obj, key, value, "=").output + + +def additem(obj, key, value): + return UpdateItem(obj, key, value, "+=").output + + +def subtractitem(obj, key, value): + return UpdateItem(obj, key, value, "-=").output + + +class Call(tracer.Application): + def __init__(self, function, args, kwargs, additional_dependencies): + if args is None: + args = [] + if kwargs is None: + kwargs = {} + if not isinstance(args, list | tuple): + raise ValueError("args must be a list or tuple") + if not isinstance(kwargs, dict): + raise ValueError("kwargs must be a dict") + for k in kwargs: + if not isinstance(k, str): + raise TypeError(f"key in kwargs must be str, not {type(k)}") + super().__init__(inputs=[function] + list(args) + list(kwargs.values()) + list(additional_dependencies), output=Value) + self.function = function + self.args = list(args) + self.kwargs = dict(kwargs) + self.additional_dependencies = additional_dependencies + + def _tracer_transform(self, transform): + return Call( + transform(self.function), + [transform(arg) for arg in self.args], + {k: transform(v) for k, v in self.kwargs.items()}, + [transform(dep) for dep in self.additional_dependencies], + ) + + def __eq__(self, other): + if isinstance(other, Call): + return ( + self.function == other.function + and self.args == other.args + and self.kwargs == other.kwargs + and self.additional_dependencies == other.additional_dependencies + ) + return False + + +def call(func, args=None, kwargs=None): + return Call(func, args, kwargs, list(tracer.get_additional_dependencies())).output + + +class CallInplace(tracer.Application): + def __init__(self, xs, function, args, kwargs, additional_dependencies): + if args is None: + args = [] + if kwargs is None: + kwargs = {} + if not isinstance(function, tracer.Tracer): + raise ValueError("function must be Tracer") + if not isinstance(args, list | tuple): + raise ValueError("args must be a list or tuple") + if not isinstance(kwargs, dict): + raise ValueError("kwargs must be a dict") + for k in kwargs: + if not isinstance(k, str): + raise TypeError(f"key in kwargs must be str, not {type(k)}") + super().__init__(inputs=[xs, function] + list(args) + list(kwargs.values()) + list(additional_dependencies), output=xs._tracer_type) + self.xs = xs + self.function = function + self.args = list(args) + self.kwargs = dict(kwargs) + self.additional_dependencies = additional_dependencies + + def _tracer_transform(self, transform): + return CallInplace( + transform(self.xs), + transform(self.function), + [transform(arg) for arg in self.args], + {k: transform(v) for k, v in self.kwargs.items()}, + [transform(dep) for dep in self.additional_dependencies], + ) + + def __eq__(self, other): + if isinstance(other, CallInplace): + return ( + self.xs == other.xs + and self.function == other.function + and self.args == other.args + and self.kwargs == other.kwargs + and self.additional_dependencies == other.additional_dependencies + ) + return False + + +def call_inplace(xs, func, args=None, kwargs=None): + return CallInplace(xs, func, args, kwargs, list(tracer.get_additional_dependencies())).output + + +class Import(tracer.Application): + def __init__(self, import_, from_=None, as_=None): + if not isinstance(import_, str): + raise TypeError(f"import_ must be str, not {type(import_)}") + if from_ is not None and not isinstance(from_, str): + raise TypeError(f"from_ must be str, not {type(from_)}") + if as_ is not None and not isinstance(as_, str): + raise TypeError(f"as_ must be str, not {type(as_)}") + if as_ is None and "." in import_: + raise ValueError("Cannot use '.' in import_ or from_ without as_") + super().__init__(inputs=[], output=Value) + self.import_ = import_ + self.from_ = from_ + self.as_ = as_ + + def _tracer_transform(self, transform): + return Import(self.import_, self.from_, self.as_) + + def __eq__(self, other): + if isinstance(other, Import): + return self.import_ == other.import_ and self.from_ == other.from_ and self.as_ == other.as_ + return False + + +def import_(import_, as_=None, from_=None): + return Import(import_, from_, as_).output + + +class OperatorApplication(tracer.Application): + def __init__(self, operator, operands): + if not isinstance(operator, str): + raise TypeError(f"operator must be str, not {type(operator)}") + super().__init__(inputs=[operator] + list(operands), output=Value) + self.operator = operator + self.operands = operands + + def _tracer_transform(self, transform): + return OperatorApplication(self.operator, [transform(operand) for operand in self.operands]) + + def __eq__(self, other): + if isinstance(other, OperatorApplication): + return self.operator == other.operator and self.operands == other.operands + return False + + +def operator(operator, *operands): + return OperatorApplication(operator, operands).output + + +def add(a, b): + return operator("+", a, b) + + +def mul(a, b): + return operator("*", a, b) + + +def less(a, b): + return operator("<", a, b) + + +def less_equal(a, b): + return operator("<=", a, b) + + +def greater(a, b): + return operator(">", a, b) + + +def greater_equal(a, b): + return operator(">=", a, b) + + +def equal(a, b): + return operator("==", a, b) + + +def not_equal(a, b): + return operator("!=", a, b) + + +class Builtin(tracer.Application): + def __init__(self, name): + if not isinstance(name, str): + raise TypeError(f"name must be str, not {type(name)}") + super().__init__(inputs=[], output=Value) + self.name = name + + def _tracer_transform(self, transform): + return Builtin(self.name) + + def __eq__(self, other): + if isinstance(other, Builtin): + return self.name == other.name + return False + + +class Builtins: + def __getattr__(self, name): + return Builtin(name).output + + +builtins = Builtins() + + +class Assert(tracer.Application): + def __init__(self, xs, condition, message=None): + super().__init__(inputs=list(pytree.flatten(xs)) + [condition], output=lambda origin: pytree.map(lambda x: x._tracer_type(origin), xs)) + self.xs = xs + self.condition = condition + self.message = message + if message is not None and not isinstance(message, str): + raise TypeError(f"message must be str or None, not {type(message)}") + + def _tracer_transform(self, transform): + return Assert(pytree.map(transform, self.xs), transform(self.condition), self.message) + + def __eq__(self, other): + if isinstance(other, Assert): + return self.xs == other.xs and self.condition == other.condition and self.message == other.message + return False + + +def assert_(xs, condition, message=None): + return Assert(xs, condition, message).output + + +class Constant(tracer.Application): + def __init__(self, value): + super().__init__(inputs=[], output=Value) + self.value = value + + def _tracer_transform(self, transform): + return Constant(self.value) + + def __eq__(self, other): + if isinstance(other, Constant): + return self.value == other.value + return False + + +def constant(value): + return Constant(value).output + + +class Value(tracer.Tracer): + def __init__(self, origin): + super().__init__(origin=origin) + + @property + def _tracer_type(self): + return Value + + def __eq__(self, other): + if isinstance(other, Value): + return self.origin == other.origin + return False + + def __getattr__(self, key): + if key.startswith("__") and key.endswith("__"): + return object.__getattribute__(self, key) + else: + return getattr(self, key) + + def __getitem__(self, key): + return getitem(self, key) + + def __call__(self, *args, **kwargs): + return call(self, args, kwargs) + + +def function(func, args=None, kwargs=None): + if args is None and kwargs is None: + signature = inspect.signature(func) + args = [] + kwargs = {} + for param in signature.parameters.values(): + if param.kind in [inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.POSITIONAL_ONLY]: + args.append(tracer.signature.python.Value(origin=None)) + elif param.kind == inspect.Parameter.KEYWORD_ONLY: + kwargs[param.name] = tracer.signature.python.Value(origin=None) + else: + raise ValueError(f"Unsupported parameter kind: {param.kind}") + elif args is None: + args = [] + elif kwargs is None: + kwargs = {} + + input_tracers = list(args) + list(kwargs.values()) + for value in input_tracers: + if not isinstance(value, tracer.Tracer): + raise TypeError(f"All arguments must be Tracer instances, got {type(value)}") + + output_tracer = func(*args, **kwargs) + + graph = tracer.Graph(inputs=input_tracers, output=output_tracer) + return graph diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/visualize.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..87124cdee72fa26dbc09f811f3598397a1ed8c3b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/tracer/visualize.py @@ -0,0 +1,124 @@ +import einx._src.tracer as tracer +from einx._src.util import pytree +import numpy as np + + +def visualize(x): + from graphviz import Digraph + + dot = Digraph() + + pythonid_to_nodeid = {} + + next_node_id = 0 + + def new_node_id(obj=None): + nonlocal next_node_id + node_id = next_node_id + next_node_id += 1 + node_id = str(node_id) + + if obj is not None: + assert id(obj) not in pythonid_to_nodeid + pythonid_to_nodeid[id(obj)] = node_id + + return node_id + + op_kwargs = {"shape": "box", "style": "filled", "fillcolor": "#aa7777"} + value_kwargs = {"shape": "oval", "style": "filled", "fillcolor": "#7777aa"} + graph_kwargs = {"shape": "box", "style": "filled", "fillcolor": "#77aa77"} + + def _value_to_str(x): + if isinstance(x, int | float | bool | np.floating | np.integer): + return str(x) + elif isinstance(x, str): + return f'"{x}"' + elif x is None: + return "None" + elif isinstance(x, list): + return f"[{', '.join(map(_value_to_str, x))}]" + f" - {x}" + elif isinstance(x, tuple): + comma = "," if len(x) == 1 else "" + return f"({', '.join(map(_value_to_str, x))}{comma})" + f" - {x}" + elif isinstance(x, slice): + start = _value_to_str(x.start) if x.start is not None else "None" + stop = _value_to_str(x.stop) if x.stop is not None else "None" + step = _value_to_str(x.step) if x.step is not None else "None" + return f"slice({start}, {stop}, {step})" + f" - {x}" + elif isinstance(x, tracer.signature.classical.Tensor): + return f"Tensor({', '.join(map(_value_to_str, x.shape))})" + f" - {x}" + elif isinstance(x, tracer.signature.classical.ConvertibleTensor): + return f"ConvertibleTensor({', '.join(map(_value_to_str, x.shape)) if x.shape is not None else 'None'})" + f" - {x}" + elif isinstance(x, tracer.Tracer): + return "Tracer" + f" - {x}" + elif isinstance(x, tracer.Graph): + if x.name is None: + return "Graph" + f" - {x}" + else: + return f'Graph("{x.name}")' + f" - {x}" + else: + raise NotImplementedError(f"Unsupported type: {type(x)}") + + def _op_to_str(op): + return op.__class__.__name__ + + def _add_op(text, inputs, outputs): + op_id = new_node_id() + dot.node(op_id, text, **op_kwargs) + + for input in inputs: + input_id = _add_value(input) + dot.edge(input_id, op_id) + + for output in outputs: + output_id = new_node_id(output) + dot.node(output_id, _value_to_str(output), **value_kwargs) + dot.edge(op_id, output_id) + + def _add_value(x): + if isinstance(x, str | int | float | bool | np.floating | np.integer) or x is None: + node_id = new_node_id() + dot.node(node_id, _value_to_str(x), **value_kwargs) + return node_id + + if id(x) in pythonid_to_nodeid: + return pythonid_to_nodeid[id(x)] + + if isinstance(x, tracer.Tracer): + if x.origin is not None: + _add_op(_op_to_str(x.origin), x.origin.inputs, pytree.flatten(x.origin.output)) + return pythonid_to_nodeid[id(x)] + else: + node_id = new_node_id(x) + dot.node(node_id, _value_to_str(x), **value_kwargs) + return node_id + elif isinstance(x, list): + _add_op("create-list", x, [x]) + return pythonid_to_nodeid[id(x)] + elif isinstance(x, tuple): + _add_op("create-tuple", x, [x]) + return pythonid_to_nodeid[id(x)] + elif isinstance(x, slice): + _add_op("create-slice", [x.start, x.stop, x.step], [x]) + return pythonid_to_nodeid[id(x)] + elif isinstance(x, tracer.Graph): + _add_value(x.output) + graph_id = new_node_id(x) + dot.node(graph_id, _value_to_str(x), **graph_kwargs) + for input in x.inputs: + input_id = _add_value(input) + dot.edge(input_id, graph_id, style="dashed", color="blue") + + def _add_out_edge(output): + output_id = _add_value(output) + dot.edge(graph_id, output_id, style="dashed", color="red") + + pytree.map(_add_out_edge, x.output) + return graph_id + else: + raise NotImplementedError(f"Unsupported type: {type(x)}") + + output_id = _add_value(x) + dot.node(output_id, _value_to_str(x), shape="octagon", style="filled", fillcolor="#ffaa00") + + return dot diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/functools.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/functools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de30a7e754f7bf4eeea98b295d40e750942436b8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/functools.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/lru_cache.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/lru_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e57217036a658708220a55065b9eaa6baad8e24a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/lru_cache.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/pytree.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/pytree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e17016487fef8ddc7dc3a6d8944bda28bb1c992f Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/pytree.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/rwlock.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/rwlock.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f9b77a703546a942127cb54f62aeddbd0ff5870 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/rwlock.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/solver.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/solver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc3b527dc820e97f3b58e56302283409e9a4e080 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/__pycache__/solver.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/functools.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/functools.py new file mode 100644 index 0000000000000000000000000000000000000000..14bd55c37d2c88fdd1ad519be995cc77404f21fd --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/functools.py @@ -0,0 +1,45 @@ +import functools +import einx._src.tracer as tracer + + +def _get_name(op): + if isinstance(op, str): + return op + elif isinstance(op, functools.partial): + return _get_name(op.func) + elif hasattr(op, "__name__"): + return op.__name__ + elif isinstance(op, tracer.Tracer): + if isinstance(op.origin, tracer.signature.python.GetAttr): + obj = _get_name(op.origin.obj) + key = op.origin.key + if obj is None: + return key + else: + return f"{obj}.{key}" + elif isinstance(op.origin, tracer.signature.python.Import): + if op.origin.as_ is not None: + return op.origin.as_ + else: + return op.origin.import_ + else: + return None + else: + return None + + +def use_name_of(signature_op): + name = _get_name(signature_op) + + def inner(op): + if name is None: + return op + else: + + def inner(*args, **kwargs): + return op(*args, **kwargs) + + inner.__name__ = name + return inner + + return inner diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/lru_cache.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/lru_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..6a168d2c3b155512b59369537db0acacd4866fd2 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/lru_cache.py @@ -0,0 +1,110 @@ +import os +import functools +import threading +import inspect +from collections import defaultdict +import numpy as np +from functools import partial +import frozendict +import types + +_thread_local = threading.local() + +warn_on_retrace_num = int(os.environ.get("EINX_WARN_ON_RETRACE", 0)) +max_cache_size = int(os.environ.get("EINX_CACHE_SIZE", -1)) + + +def _freeze_value(x): + if isinstance(x, np.ndarray): + return _freeze_value(x.tolist()) + elif isinstance(x, list | tuple): + return tuple(_freeze_value(x) for x in x) + elif isinstance(x, dict): + return frozendict.frozendict({k: _freeze_value(v) for k, v in x.items()}) + elif isinstance(x, types.SimpleNamespace): + return _freeze_value(vars(x)) + elif isinstance(x, inspect.Parameter): + return _freeze_value((x.name, x.default, x.annotation, x.kind)) + else: + return x + + +def _freeze_args(func): + @functools.wraps(func) + def func_frozen(*args, **kwargs): + args = [_freeze_value(a) for a in args] + kwargs = {k: _freeze_value(v) for k, v in kwargs.items()} + return func(*args, **kwargs) + + return func_frozen + + +def _with_retrace_warning(func): + if warn_on_retrace_num > 0: + cache_failures = defaultdict(lambda: 0) + + @functools.wraps(func) + def func_with_warn(*args, **kwargs): + has_warned = False + if warn_on_retrace_num > 0: + if not hasattr(_thread_local, "warn"): + _thread_local.warn = True + + stack = inspect.stack() + # Exclude frames called from this file + last_index = 0 + for i, frame in enumerate(stack): + if frame.filename == __file__: + last_index = i + stack = stack[last_index + 1 :] + + if len(stack) > 0: + # Generate string description of call stack + trace = "" + for frame in reversed(stack): + trace += f'File "{frame.filename}", line {frame.lineno}, in {frame.function}\n' + if frame.code_context is not None: + trace += f" {frame.code_context[0].strip()}\n" + cache_failures[trace] += 1 + if _thread_local.warn and cache_failures[trace] == warn_on_retrace_num: + # Print warning + has_warned = True + print( + f"WARNING (einx): The following call stack has resulted in " + f"{warn_on_retrace_num} retraces of an einx function.\n" + f"A retrace happens when the function is called with " + "different signatures of input arguments.\n" + f"Call stack (most recent call last):\n" + f"{trace}" + ) + + # Don't warn in inner functions that also use lru_cache + if has_warned: + _thread_local.warn = False + result = func(*args, **kwargs) + _thread_local.warn = True + else: + result = func(*args, **kwargs) + return result + + return func_with_warn + else: + return func + + +# An LRU-cache that +# 1. allows using some mutable objects (np.ndarray, list and dict) as keys +# 2. warns if there are more than EINX_WARN_ON_RETRACE cache failures from the same call site +def lru_cache(func): + func = _with_retrace_warning(func) + + if max_cache_size > 0: + func = functools.lru_cache(maxsize=max_cache_size if max_cache_size > 0 else None)(func) + elif max_cache_size < 0: + if "cache" in vars(functools): + func = functools.cache(func) + else: + func = functools.lru_cache(maxsize=None)(func) + func = _freeze_args(func) + + return func diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/pytree.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/pytree.py new file mode 100644 index 0000000000000000000000000000000000000000..658a9cf414f5dce4f855da27df72b8fd57ad0586 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/pytree.py @@ -0,0 +1,54 @@ +_all = all +_map = map + + +def flatten(x, is_leaf=None): + if is_leaf is not None and is_leaf(x): + yield x + elif isinstance(x, list | tuple): + for x in x: + yield from flatten(x, is_leaf=is_leaf) + elif isinstance(x, dict): + for x in x.items(): + yield from flatten(x, is_leaf=is_leaf) + else: + yield x + + +def map(func, *trees, is_leaf=None, assert_same_structure=False): + if len(trees) == 0: + raise ValueError("At least one tree is required") + if is_leaf is not None and is_leaf(trees[0]): + same_structure = _all(is_leaf(x) for x in trees[1:]) + if assert_same_structure: + assert same_structure + return func(*trees) + elif isinstance(trees[0], list): + same_structure = _all(isinstance(x, list) for x in trees[1:]) and len(set(_map(len, trees))) == 1 + if assert_same_structure: + assert same_structure + elif not same_structure: + return func(*trees) + return [map(func, *x, is_leaf=is_leaf, assert_same_structure=assert_same_structure) for x in zip(*trees, strict=False)] + elif isinstance(trees[0], tuple): + same_structure = _all(isinstance(x, tuple) for x in trees[1:]) and len(set(_map(len, trees))) == 1 + if assert_same_structure: + assert same_structure + elif not same_structure: + return func(*trees) + return tuple(map(func, *x, is_leaf=is_leaf, assert_same_structure=assert_same_structure) for x in zip(*trees, strict=False)) + elif isinstance(trees[0], dict): + keys = trees[0].keys() + same_structure = _all(isinstance(x, dict) for x in trees[1:]) and _all(x.keys() == keys for x in trees[1:]) + if assert_same_structure: + assert same_structure + elif not same_structure: + return func(*trees) + return {k: map(func, *[x[k] for x in trees], is_leaf=is_leaf, assert_same_structure=assert_same_structure) for k in trees[0]} + else: + return func(*trees) + + +def all(pred, *trees, is_leaf=None): + bool_tree = map(pred, *trees, is_leaf=is_leaf) + return _all(flatten(bool_tree)) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/rwlock.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/rwlock.py new file mode 100644 index 0000000000000000000000000000000000000000..125a626164bc702740ba4325ba14fde1f3578533 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/rwlock.py @@ -0,0 +1,44 @@ +import threading +import contextlib + + +class RWLock: + def __init__(self): + self.write_lock = threading.RLock() + self.num_reading_lock = threading.RLock() + self.num_reading = 0 + + def read_acquire(self): + with self.num_reading_lock: + self.num_reading += 1 + if self.num_reading == 1: # First reader acquires write lock + self.write_lock.acquire() + + def read_release(self): + assert self.num_reading > 0 + with self.num_reading_lock: + self.num_reading -= 1 + if self.num_reading == 0: # Last reader releases write lock + self.write_lock.release() + + @contextlib.contextmanager + def read(self): + try: + self.read_acquire() + yield + finally: + self.read_release() + + def write_acquire(self): + self.write_lock.acquire() + + def write_release(self): + self.write_lock.release() + + @contextlib.contextmanager + def write(self): + try: + self.write_acquire() + yield + finally: + self.write_release() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/solver.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/solver.py new file mode 100644 index 0000000000000000000000000000000000000000..b36998cdb4f9c77b0194c216247cbc980d9310eb --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/_src/util/solver.py @@ -0,0 +1,288 @@ +import sympy +import math +from collections import defaultdict + + +class Expression: + def __init__(self): + pass + + def __add__(self, other): + return Sum([self, other]) + + def __radd__(self, other): + return Sum([other, self]) + + def __mul__(self, other): + return Product([self, other]) + + def __rmul__(self, other): + return Product([other, self]) + + +class Variable(Expression): + def __init__(self, id, name): + Expression.__init__(self) + self.id = id + self.name = name + + def __iter__(self): + yield self + + def __eq__(self, other): + return isinstance(other, Variable) and self.id == other.id + + def __hash__(self): + return hash(self.id) + + def __str__(self): + return f"{self.name}" + + def sympy(self): + return sympy.Symbol(self.id, integer=True, nonnegative=True) + + +class Constant(Expression): + def __init__(self, value): + Expression.__init__(self) + self.value = value + + def __iter__(self): + yield self + + def __eq__(self, other): + return isinstance(other, Constant) and self.value == other.value + + def __hash__(self): + return hash(self.value) + + def __str__(self): + return str(self.value) + + def sympy(self): + return self.value + + +class Sum(Expression): + @staticmethod + def maybe(children): + if len(children) == 0: + return Constant(0) + elif len(children) == 1: + return children[0] + elif all(isinstance(c, Constant) for c in children): + return Constant(sum(c.value for c in children)) + else: + return Sum(children) + + def __init__(self, children): + Expression.__init__(self) + self.children = [_to_expr(c) for c in children] + + def __iter__(self): + yield self + for child in self.children: + yield from child + + def __eq__(self, other): + return isinstance(other, Sum) and self.children == other.children + + def __hash__(self): + return hash(tuple(self.children)) + + def __str__(self): + return " + ".join(str(c) for c in self.children) + + def sympy(self): + return sum(c.sympy() for c in self.children) + + +class Product(Expression): + @staticmethod + def maybe(children): + if len(children) == 0: + return Constant(1) + elif len(children) == 1: + return children[0] + elif all(isinstance(c, Constant) for c in children): + return Constant(math.prod(c.value for c in children)) + else: + return Product(children) + + def __init__(self, children): + Expression.__init__(self) + self.children = [_to_expr(c) for c in children] + + def __iter__(self): + yield self + for child in self.children: + yield from child + + def __eq__(self, other): + return isinstance(other, Product) and self.children == other.children + + def __hash__(self): + return hash(tuple(self.children)) + + def __str__(self): + return " * ".join(str(c) for c in self.children) + + def sympy(self): + return math.prod([c.sympy() for c in self.children]) + + +def _to_expr(x): + if isinstance(x, int): + return Constant(x) + else: + if not isinstance(x, Expression): + raise TypeError(f"Expected Expression, got {type(x)}") + return x + + +class SolveException(Exception): + def __init__(self, message): + super().__init__(message) + + +class SolveExceptionNoSolution(SolveException): + def __init__(self, message="", contradicting_variables=None): + if contradicting_variables is None: + contradicting_variables = [] + message = message + f"\nContradicting variables: {', '.join([str(v) for v in contradicting_variables])}" + super().__init__(message) + self.contradicting_variables = contradicting_variables + if not all(isinstance(v, Variable) for v in contradicting_variables): + raise TypeError("Expected all contradicting variables to be of type Variable") + + +class SolveExceptionTooManySolutions(SolveException): + def __init__(self, message=None): + super().__init__(message) + self.message = message + + +def solve(equations, verbose=False): + equations = [(_to_expr(t1), _to_expr(t2)) for t1, t2 in equations] + equations = [(t1, t2) for t1, t2 in equations if t1 != t2] + equations = list(set(equations)) + variables = {v.id: v for equation in equations for term in equation for v in term if isinstance(v, Variable)} + + # ##### Find equivalence classes of variables to speed up sympy solver ##### + # Find constant definitions + constants = defaultdict(set) # id -> {constant value} + contradicting_variables = set() + for t1, t2 in equations: + if isinstance(t1, Variable) and isinstance(t2, Constant): + constants[t1.id].add(t2.value) + elif isinstance(t1, Constant) and isinstance(t2, Variable): + constants[t2.id].add(t1.value) + elif isinstance(t1, Constant) and isinstance(t2, Constant): + if t1.value != t2.value: + raise SolveExceptionNoSolution(f"Found contradictory input equation {t1.value} != {t2.value}", []) + contradicting_variables = {variables[variable_id] for variable_id, values in constants.items() if len(values) != 1} + if len(contradicting_variables) > 0: + raise SolveExceptionNoSolution("Found contradictory definitions for the same variable", contradicting_variables) + constants = {k: v.pop() for k, v in constants.items()} # id -> constant value + + # Find equivalence classes of variables + classes = {v: {v} for v in variables} # id -> set of equivalent ids + for t1, t2 in equations: + if isinstance(t1, Variable) and isinstance(t2, Variable): + assert t1.id in classes and t2.id in classes + set1 = classes[t1.id] + set2 = classes[t2.id] + for t_id in set2: + classes[t_id] = set1 + set1.add(t_id) + classes = list({id(s): s for s in classes.values()}.values()) + variableid_to_class = {v: c for c in classes for v in c} + + # For every class: Use constant if it exists, or create a new class variable + origvar_to_solvevar = {} # id -> Variable or Constant + contradicting_variables = set() + for equiv_class in classes: + if any(n in constants for n in equiv_class): + # Use constant + class_constants = {constants[n] for n in equiv_class if n in constants} + assert len(class_constants) > 0 + if len(class_constants) > 1: + contradicting_variables.update(variables[vid] for vid in equiv_class) + v = Constant(next(iter(class_constants))) + else: + # Create new variable for class + v = Variable(f"__EquivalenceClass-{id(equiv_class)}", f"Equivalent expressions { {variables[vid].name for vid in equiv_class} }") + for n in equiv_class: + assert n not in origvar_to_solvevar + origvar_to_solvevar[n] = v + if len(contradicting_variables) > 0: + raise SolveExceptionNoSolution("Found contradictory constants for same equivalence class", contradicting_variables) + + # Apply to equations + def replace(t): + if isinstance(t, Variable) and t.id in origvar_to_solvevar: + return origvar_to_solvevar[t.id] + elif isinstance(t, Constant): + return t + elif isinstance(t, Sum): + return Sum.maybe([replace(c) for c in t.children]) + elif isinstance(t, Product): + return Product.maybe([replace(c) for c in t.children]) + else: + raise AssertionError() + + equations2 = [] + contradicting_variables = set() + for t1o, t2o in equations: + t1 = replace(t1o) + t2 = replace(t2o) + if isinstance(t1, Constant) and isinstance(t2, Constant): + if t1.value != t2.value: + vars = [variables[vid] for to in [t1o, t2o] for v0 in to if isinstance(v0, Variable) for vid in variableid_to_class[v0.id]] + contradicting_variables.update(vars) + elif t1 != t2: + equations2.append((t1, t2)) + equations = equations2 + if len(contradicting_variables) > 0: + raise SolveExceptionNoSolution("Found contradictory values for same equivalence class", list(contradicting_variables)) + + if verbose: + print("Solving equations of equivalence classes:") + for t1, t2 in equations: + print(f" {t1} = {t2}") + + # ##### Solve remaining equations using sympy ##### + solutions = {} + if len(equations) > 0: + sympy_equations = [sympy.Eq(t1.sympy(), t2.sympy()) for t1, t2 in equations] + + if all(eq.is_Boolean and bool(eq) for eq in sympy_equations): + solutions = {} + else: + solutions = sympy.solve(sympy_equations, set=True, manual=True) + if solutions == []: + solutions = {} + elif isinstance(solutions, tuple) and len(solutions) == 2: + variables, solutions = solutions + if len(solutions) == 0: + raise SolveExceptionNoSolution("Sympy returned no solutions") + elif len(solutions) > 1: + raise SolveExceptionTooManySolutions("Sympy returned multiple possible solutions") + else: + solutions = next(iter(solutions)) + solutions = {str(k): int(v) for k, v in zip(variables, solutions, strict=False) if v.is_number} + else: + raise AssertionError("Sympy returned unexpected result") + + # Determine values for original variables in equivalence classes + orig_solutions = {} + for k, v in origvar_to_solvevar.items(): + if isinstance(v, Constant): + orig_solutions[k] = v.value + elif isinstance(v, Variable): + if v.id in solutions: + orig_solutions[k] = solutions[v.id] + else: + raise AssertionError() + + return orig_solutions diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/arrayapi.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/arrayapi.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ce03b954da1721aa87f3d142da9580c5d96736 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/arrayapi.py @@ -0,0 +1,2 @@ +from einx._src.frontend.impl.arrayapi import adapt_numpylike_reduce +from einx._src.frontend.impl.arrayapi import adapt_numpylike_elementwise diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/backend.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..e4195ad2d481d583752e78ba32ee0c4d4aec29e7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/backend.py @@ -0,0 +1,4 @@ +from einx._src.frontend.backend import registry + +get = registry.get +del registry diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/errors.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b4d238a6dabc1cb6c29e4d7bd89a1c979d6201 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/errors.py @@ -0,0 +1,9 @@ +from einx._src.frontend.errors import EinxError +from einx._src.frontend.errors import SyntaxError +from einx._src.frontend.errors import RankError +from einx._src.frontend.errors import AxisSizeError +from einx._src.frontend.errors import SemanticError +from einx._src.frontend.errors import OperationNotSupportedError +from einx._src.frontend.errors import ImportBackendError +from einx._src.frontend.errors import BackendResolutionError +from einx._src.frontend.errors import CallOperationError diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9631698d4f1b799100d52459f255d0d23b5e42b8 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/__init__.py @@ -0,0 +1 @@ +from . import functorchdim diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b3f0cf65d21998711a6702b7d23abbbbd6cfa9a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/__pycache__/functorchdim.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/__pycache__/functorchdim.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51caaa79e9d20e8acab57d13374255a1ec90f915 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/__pycache__/functorchdim.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/functorchdim.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/functorchdim.py new file mode 100644 index 0000000000000000000000000000000000000000..c1910ac937c5b6c37089ebf930ef508ac8590e63 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/experimental/functorchdim.py @@ -0,0 +1 @@ +from einx._src.frontend.impl.functorchdim import adapt diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/jax.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/jax.py new file mode 100644 index 0000000000000000000000000000000000000000..dfb32fd93b876174cf1edc80e9f7cf9c465edfde --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/jax.py @@ -0,0 +1,3 @@ +from einx._src.frontend.impl.jax import adapt_with_vmap +from einx._src.frontend.impl.jax import adapt_numpylike_reduce +from einx._src.frontend.impl.jax import adapt_numpylike_elementwise diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/mlx.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/mlx.py new file mode 100644 index 0000000000000000000000000000000000000000..78c7bc20de83d6ded39e41162cb6f7f4b963b966 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/mlx.py @@ -0,0 +1,3 @@ +from einx._src.frontend.impl.mlx import adapt_with_vmap +from einx._src.frontend.impl.mlx import adapt_numpylike_reduce +from einx._src.frontend.impl.mlx import adapt_numpylike_elementwise diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/nn.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/nn.py new file mode 100644 index 0000000000000000000000000000000000000000..16e933fd90a7e029ffae024c557d9868874dc957 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/nn.py @@ -0,0 +1 @@ +raise ImportError("The 'einx.nn' namespace has been removed. Please use version 0.3.0 of einx if you want to use the features in this namespace.") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/numpy.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..3b95b289f1eede714cbbcff2600f039a48683c42 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/numpy.py @@ -0,0 +1,2 @@ +from einx._src.frontend.impl.numpy import adapt_numpylike_reduce +from einx._src.frontend.impl.numpy import adapt_numpylike_elementwise diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/py.typed b/simulation/.venv-planner/lib/python3.12/site-packages/einx/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/tensorflow.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..e365f614595c269a9d5ffebc0d852907cda7b6c7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/tensorflow.py @@ -0,0 +1,2 @@ +from einx._src.frontend.impl.tensorflow import adapt_numpylike_reduce +from einx._src.frontend.impl.tensorflow import adapt_numpylike_elementwise diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/tinygrad.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/tinygrad.py new file mode 100644 index 0000000000000000000000000000000000000000..f62f9f2c7b4a67aade35e634e96aa4e5a0db23ac --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/tinygrad.py @@ -0,0 +1,2 @@ +from einx._src.frontend.impl.tinygrad import adapt_numpylike_reduce +from einx._src.frontend.impl.tinygrad import adapt_numpylike_elementwise diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/einx/torch.py b/simulation/.venv-planner/lib/python3.12/site-packages/einx/torch.py new file mode 100644 index 0000000000000000000000000000000000000000..49e179941bda27c32c34a67d4f8e89d107427b8d --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/einx/torch.py @@ -0,0 +1,3 @@ +from einx._src.frontend.impl.torch import adapt_with_vmap +from einx._src.frontend.impl.torch import adapt_numpylike_reduce +from einx._src.frontend.impl.torch import adapt_numpylike_elementwise diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/INSTALLER b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/METADATA b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..26bd3cd9d41778fe88ea670dc0bc4736dd5e3224 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/METADATA @@ -0,0 +1,496 @@ +Metadata-Version: 2.4 +Name: frozendict +Version: 2.4.7 +Summary: A simple immutable dictionary +Home-page: https://github.com/Marco-Sulla/python-frozendict +Author: Marco Sulla +Author-email: marcosullaroma@gmail.com +License: LGPL v3 +Project-URL: Bug Reports, https://github.com/Marco-Sulla/python-frozendict/issues +Project-URL: Source, https://github.com/Marco-Sulla/python-frozendict +Keywords: immutable hashable picklable frozendict dict dictionary map Mapping MappingProxyType developers stable utility +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3) +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.6 +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Utilities +Requires-Python: >=3.6 +Description-Content-Type: text/markdown +License-File: LICENSE.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: project-url +Dynamic: requires-python +Dynamic: summary + +# frozendict +### Table of Contents +* [Introduction](#introduction) +* [Install](#install) +* [API](#api) + * [frozendict API](#frozendict-api) + * [deepfreeze API](#deepfreeze-api) +* [Examples](#examples) + * [frozendict examples](#frozendict-examples) + * [deepfreeze examples](#deepfreeze-examples) +* [Building](#building) +* [Benchmarks](#benchmarks) + +# Introduction +Welcome, fellow programmer, to the house of `frozendict` and +[deepfreeze](#deepfreeze-api)! + +`frozendict` is a simple immutable dictionary. It's fast as `dict`, and +[sometimes faster](https://github.com/Marco-Sulla/python-frozendict#benchmarks)! + +Unlike other similar implementations, immutability is guaranteed: you can't +change the internal variables of the class, and they are all immutable +objects. Reinvoking `__init__` does not alter the object. + +The API is the same as `dict`, without methods that can change the +immutability. So it supports also `fromkeys`, unlike other implementations. +Furthermore, it can be `pickle`d, un`pickle`d and have a hash, if all values +are hashable. + +You can also add any `dict` to a `frozendict` using the `|` operator. The result is a new `frozendict`. + +# Install + +You can install `frozendict` by simply typing in a command line: + +```bash +pip install frozendict +``` + +The C Extension is optional by default from version 2.3.5. You can make it mandatory using: + +```bash +CIBUILDWHEEL=1 pip install frozendict +``` + +On the contrary, if you want the pure py implementation: + +```bash +FROZENDICT_PURE_PY=1 pip install frozendict +``` + +# API + +## frozendict API +The API is the same of `dict` of Python 3.10, without the methods and operands which alter the map. Additionally, `frozendict` supports these methods: + +### `__hash__()` + +If all the values of the `frozendict` are hashable, returns a hash, otherwise raises a TypeError. + +### `set(key, value)` + +It returns a new `frozendict`. If key is already in the original `frozendict`, the new one will have it with the new value associated. Otherwise, the new `frozendict` will contain the new (key, value) item. + +### `delete(key)` + +It returns a new `frozendict` without the item corresponding to the key. If the key is not present, a KeyError is raised. + +### `setdefault(key[, default])` + +If key is already in `frozendict`, the object itself is returned unchanged. Otherwise, the new `frozendict` will contain the new (key, default) item. The parameter default defaults to None. + +### `key([index])` + +It returns the key at the specified index (determined by the insertion order). If index is not passed, it defaults to 0. If the index is negative, the position will be the size of the `frozendict` + index + +### `value([index])` +Same as `key(index)`, but it returns the value at the given index. + +### `item([index])` +Same as `key(index)`, but it returns a tuple with (key, value) at the given index. + +## deepfreeze API + +The `frozendict` _module_ has also these static methods: + +### `frozendict.deepfreeze(o, custom_converters = None, custom_inverse_converters = None)` +Converts the object and all the objects nested in it, into their immutable +counterparts. + +The conversion map is in `getFreezeConversionMap()`. + +You can register a new conversion using `register()` You can also +pass a map of custom converters with `custom_converters` and a map +of custom inverse converters with `custom_inverse_converters`, +without using `register()`. + +By default, if the type is not registered and has a `__dict__` +attribute, it's converted to the `frozendict` of that `__dict__`. + +This function assumes that hashable == immutable (that is not +always true). + +This function uses recursion, with all the limits of recursions in +Python. + +Where is a good old tail call when you need it? + +### `frozendict.register(to_convert, converter, *, inverse = False)` + +Adds a `converter` for a type `to_convert`. `converter` +must be callable. The new converter will be used by `deepfreeze()` +and has precedence over any previous converter. + +If `to_covert` has already a converter, a FreezeWarning is raised. + +If `inverse` is True, the conversion is considered from an immutable +type to a mutable one. This make it possible to convert mutable +objects nested in the registered immutable one. + +### `frozendict.unregister(type, inverse = False)` +Unregister a type from custom conversion. If `inverse` is `True`, +the unregistered conversion is an inverse conversion +(see `register()`). + +# Examples + +## frozendict examples +```python +from frozendict import frozendict + +fd = frozendict(Guzzanti = "Corrado", Hicks = "Bill") + +print(fd) +# frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill'}) + +frozendict({"Guzzanti": "Corrado", "Hicks": "Bill"}) +# frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill'}) + +hash(fd) +# 5833699487320513741 + +fd_unhashable = frozendict({1: []}) +hash(fd_unhashable) +# TypeError: Not all values are hashable. + +frozendict({frozendict(nested = 4, key = 2): 42}) +# frozendict({frozendict({'nested': 4, 'key': 2}): 42}) + +fd | {1: 2} +# frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill', 1: 2}) + +fd.set(1, 2) +# frozendict.frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill', 1: 2}) + +fd.set("Guzzanti", "Sabina") +# frozendict.frozendict({'Guzzanti': 'Sabina', 'Hicks': 'Bill'}) + +fd.delete("Guzzanti") +# frozendict.frozendict({'Hicks': 'Bill'}) + +fd.setdefault("Guzzanti", "Sabina") +# frozendict.frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill'}) + +fd.setdefault(1, 2) +# frozendict.frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill', 1: 2}) + +fd.key() +# 'Guzzanti' + +fd.value(1) +# 'Bill' + +fd.item(-1) +# (1, 2) + +print(fd["Guzzanti"]) +# Corrado + +fd["Brignano"] +# KeyError: 'Brignano' + +len(fd) +# 2 + +"Guzzanti" in fd +# True + +"Guzzanti" not in fd +# False + +"Brignano" in fd +# False + +fd5 = frozendict(fd) +id_fd5 = id(fd5) +fd5 |= {1: 2} +fd5 +# frozendict.frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill', 1: 2}) +id(fd5) != id_fd5 +# True + +fd2 = fd.copy() +fd2 == fd +# True + +fd3 = frozendict(fd) +fd3 == fd +# True + +fd4 = frozendict({"Hicks": "Bill", "Guzzanti": "Corrado"}) + +print(fd4) +# frozendict({'Hicks': 'Bill', 'Guzzanti': 'Corrado'}) + +fd4 == fd +# True + +import pickle +fd_unpickled = pickle.loads(pickle.dumps(fd)) +print(fd_unpickled) +# frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill'}) +fd_unpickled == fd +# True + +frozendict(Guzzanti="Corrado", Hicks="Bill") +# frozendict({'Guzzanti': 'Corrado', 'Hicks': 'Bill'} + +fd.get("Guzzanti") +# 'Corrado' + +print(fd.get("Brignano")) +# None + +tuple(fd.keys()) +# ('Guzzanti', 'Hicks') + +tuple(fd.values()) +# ('Corrado', 'Bill') + +tuple(fd.items()) +# (('Guzzanti', 'Corrado'), ('Hicks', 'Bill')) + +frozendict.fromkeys(["Corrado", "Sabina"], "Guzzanti") +# frozendict({'Corrado': 'Guzzanti', 'Sabina': 'Guzzanti'}) + +iter(fd) +# + +fd["Guzzanti"] = "Caterina" +# TypeError: 'frozendict' object doesn't support item assignment +``` + +## deepfreeze examples +```python +import frozendict as cool + +from frozendict import frozendict +from array import array +from collections import OrderedDict +from types import MappingProxyType + +class A: + def __init__(self, x): + self.x = x + +a = A(3) + +o = {"x": [ + 5, + frozendict(y = {5, "b", memoryview(b"b")}), + array("B", (0, 1, 2)), + OrderedDict(a=bytearray(b"a")), + MappingProxyType({2: []}), + a +]} + +cool.deepfreeze(o) +# frozendict(x = ( +# 5, +# frozendict(y = frozenset({5, "b", memoryview(b"b")})), +# (0, 1, 2), +# frozendict(a = b'a'), +# MappingProxyType({2: ()}), +# frozendict(x = 3), +# )) + +``` + +# Building +You can build `frozendict` directly from the code, using + +``` +python3 setup.py bdist_wheel +``` + +The C Extension is optional by default from version 2.3.5. You can make it mandatory by passing the environment variable `CIBUILDWHEEL` with value `1` + +On the contrary, if you want the pure py implementation, you can pass the env var `FROZENDICT_PURE_PY` with value `1` + +# Benchmarks + +Some benchmarks between `dict` and `frozendict`[1]: + +``` +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(d)`; Size: 5; Keys: str; Type: dict; Time: 8.02e-08; Sigma: 4e-09 +Name: `constructor(d)`; Size: 5; Keys: str; Type: frozendict; Time: 8.81e-08; Sigma: 3e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(d)`; Size: 5; Keys: int; Type: dict; Time: 7.96e-08; Sigma: 5e-09 +Name: `constructor(d)`; Size: 5; Keys: int; Type: frozendict; Time: 8.97e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(d)`; Size: 1000; Keys: str; Type: dict; Time: 6.38e-06; Sigma: 9e-08 +Name: `constructor(d)`; Size: 1000; Keys: str; Type: frozendict; Time: 6.21e-06; Sigma: 2e-07 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(d)`; Size: 1000; Keys: int; Type: dict; Time: 3.49e-06; Sigma: 3e-07 +Name: `constructor(d)`; Size: 1000; Keys: int; Type: frozendict; Time: 3.48e-06; Sigma: 2e-07 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(kwargs)`; Size: 5; Keys: str; Type: dict; Time: 2.40e-07; Sigma: 1e-09 +Name: `constructor(kwargs)`; Size: 5; Keys: str; Type: frozendict; Time: 2.48e-07; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(kwargs)`; Size: 1000; Keys: str; Type: dict; Time: 4.80e-05; Sigma: 1e-06 +Name: `constructor(kwargs)`; Size: 1000; Keys: str; Type: frozendict; Time: 2.90e-05; Sigma: 7e-07 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(seq2)`; Size: 5; Keys: str; Type: dict; Time: 2.01e-07; Sigma: 9e-10 +Name: `constructor(seq2)`; Size: 5; Keys: str; Type: frozendict; Time: 2.50e-07; Sigma: 1e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(seq2)`; Size: 5; Keys: int; Type: dict; Time: 2.18e-07; Sigma: 2e-09 +Name: `constructor(seq2)`; Size: 5; Keys: int; Type: frozendict; Time: 2.73e-07; Sigma: 1e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(seq2)`; Size: 1000; Keys: str; Type: dict; Time: 4.29e-05; Sigma: 6e-07 +Name: `constructor(seq2)`; Size: 1000; Keys: str; Type: frozendict; Time: 4.33e-05; Sigma: 6e-07 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(seq2)`; Size: 1000; Keys: int; Type: dict; Time: 3.04e-05; Sigma: 4e-07 +Name: `constructor(seq2)`; Size: 1000; Keys: int; Type: frozendict; Time: 3.45e-05; Sigma: 4e-07 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(o)`; Size: 5; Keys: str; Type: dict; Time: 7.93e-08; Sigma: 3e-09 +Name: `constructor(o)`; Size: 5; Keys: str; Type: frozendict; Time: 2.41e-08; Sigma: 6e-10 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(o)`; Size: 5; Keys: int; Type: dict; Time: 7.94e-08; Sigma: 5e-09 +Name: `constructor(o)`; Size: 5; Keys: int; Type: frozendict; Time: 2.41e-08; Sigma: 6e-10 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(o)`; Size: 1000; Keys: str; Type: dict; Time: 6.18e-06; Sigma: 3e-07 +Name: `constructor(o)`; Size: 1000; Keys: str; Type: frozendict; Time: 2.41e-08; Sigma: 6e-10 +//////////////////////////////////////////////////////////////////////////////// +Name: `constructor(o)`; Size: 1000; Keys: int; Type: dict; Time: 3.47e-06; Sigma: 2e-07 +Name: `constructor(o)`; Size: 1000; Keys: int; Type: frozendict; Time: 2.41e-08; Sigma: 6e-10 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `o.copy()`; Size: 5; Keys: str; Type: dict; Time: 7.28e-08; Sigma: 2e-09 +Name: `o.copy()`; Size: 5; Keys: str; Type: frozendict; Time: 3.18e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o.copy()`; Size: 5; Keys: int; Type: dict; Time: 7.21e-08; Sigma: 4e-09 +Name: `o.copy()`; Size: 5; Keys: int; Type: frozendict; Time: 3.32e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o.copy()`; Size: 1000; Keys: str; Type: dict; Time: 6.16e-06; Sigma: 3e-07 +Name: `o.copy()`; Size: 1000; Keys: str; Type: frozendict; Time: 3.18e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o.copy()`; Size: 1000; Keys: int; Type: dict; Time: 3.46e-06; Sigma: 1e-07 +Name: `o.copy()`; Size: 1000; Keys: int; Type: frozendict; Time: 3.18e-08; Sigma: 2e-09 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `o == o`; Size: 5; Keys: str; Type: dict; Time: 7.23e-08; Sigma: 8e-10 +Name: `o == o`; Size: 5; Keys: str; Type: frozendict; Time: 2.44e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o == o`; Size: 5; Keys: int; Type: dict; Time: 7.30e-08; Sigma: 1e-09 +Name: `o == o`; Size: 5; Keys: int; Type: frozendict; Time: 2.44e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o == o`; Size: 1000; Keys: str; Type: dict; Time: 1.38e-05; Sigma: 1e-07 +Name: `o == o`; Size: 1000; Keys: str; Type: frozendict; Time: 2.44e-08; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `o == o`; Size: 1000; Keys: int; Type: dict; Time: 1.05e-05; Sigma: 7e-08 +Name: `o == o`; Size: 1000; Keys: int; Type: frozendict; Time: 2.44e-08; Sigma: 2e-09 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o`; Size: 5; Keys: str; Type: dict; Time: 7.33e-08; Sigma: 2e-09 +Name: `for x in o`; Size: 5; Keys: str; Type: frozendict; Time: 6.70e-08; Sigma: 1e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o`; Size: 5; Keys: int; Type: dict; Time: 7.33e-08; Sigma: 2e-09 +Name: `for x in o`; Size: 5; Keys: int; Type: frozendict; Time: 6.70e-08; Sigma: 1e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o`; Size: 1000; Keys: str; Type: dict; Time: 8.84e-06; Sigma: 5e-08 +Name: `for x in o`; Size: 1000; Keys: str; Type: frozendict; Time: 7.06e-06; Sigma: 6e-08 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o`; Size: 1000; Keys: int; Type: dict; Time: 8.67e-06; Sigma: 7e-08 +Name: `for x in o`; Size: 1000; Keys: int; Type: frozendict; Time: 6.94e-06; Sigma: 3e-08 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.values()`; Size: 5; Keys: str; Type: dict; Time: 7.28e-08; Sigma: 9e-10 +Name: `for x in o.values()`; Size: 5; Keys: str; Type: frozendict; Time: 6.48e-08; Sigma: 8e-10 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.values()`; Size: 5; Keys: int; Type: dict; Time: 7.25e-08; Sigma: 1e-09 +Name: `for x in o.values()`; Size: 5; Keys: int; Type: frozendict; Time: 6.45e-08; Sigma: 1e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.values()`; Size: 1000; Keys: str; Type: dict; Time: 9.06e-06; Sigma: 5e-07 +Name: `for x in o.values()`; Size: 1000; Keys: str; Type: frozendict; Time: 7.04e-06; Sigma: 4e-08 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.values()`; Size: 1000; Keys: int; Type: dict; Time: 9.53e-06; Sigma: 3e-08 +Name: `for x in o.values()`; Size: 1000; Keys: int; Type: frozendict; Time: 6.97e-06; Sigma: 3e-08 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.items()`; Size: 5; Keys: str; Type: dict; Time: 1.13e-07; Sigma: 3e-09 +Name: `for x in o.items()`; Size: 5; Keys: str; Type: frozendict; Time: 1.16e-07; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.items()`; Size: 5; Keys: int; Type: dict; Time: 1.14e-07; Sigma: 3e-09 +Name: `for x in o.items()`; Size: 5; Keys: int; Type: frozendict; Time: 1.17e-07; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.items()`; Size: 1000; Keys: str; Type: dict; Time: 1.53e-05; Sigma: 3e-07 +Name: `for x in o.items()`; Size: 1000; Keys: str; Type: frozendict; Time: 1.53e-05; Sigma: 4e-07 +//////////////////////////////////////////////////////////////////////////////// +Name: `for x in o.items()`; Size: 1000; Keys: int; Type: dict; Time: 1.53e-05; Sigma: 3e-07 +Name: `for x in o.items()`; Size: 1000; Keys: int; Type: frozendict; Time: 1.55e-05; Sigma: 4e-07 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.dumps(o)`; Size: 5; Keys: str; Type: dict; Time: 6.82e-07; Sigma: 2e-08 +Name: `pickle.dumps(o)`; Size: 5; Keys: str; Type: frozendict; Time: 2.86e-06; Sigma: 1e-07 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.dumps(o)`; Size: 5; Keys: int; Type: dict; Time: 4.77e-07; Sigma: 2e-08 +Name: `pickle.dumps(o)`; Size: 5; Keys: int; Type: frozendict; Time: 2.72e-06; Sigma: 8e-08 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.dumps(o)`; Size: 1000; Keys: str; Type: dict; Time: 1.24e-04; Sigma: 4e-06 +Name: `pickle.dumps(o)`; Size: 1000; Keys: str; Type: frozendict; Time: 1.92e-04; Sigma: 5e-06 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.dumps(o)`; Size: 1000; Keys: int; Type: dict; Time: 2.81e-05; Sigma: 6e-07 +Name: `pickle.dumps(o)`; Size: 1000; Keys: int; Type: frozendict; Time: 7.37e-05; Sigma: 1e-06 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.loads(dump)`; Size: 5; Keys: str; Type: dict; Time: 9.08e-07; Sigma: 6e-09 +Name: `pickle.loads(dump)`; Size: 5; Keys: str; Type: frozendict; Time: 1.79e-06; Sigma: 9e-08 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.loads(dump)`; Size: 5; Keys: int; Type: dict; Time: 4.46e-07; Sigma: 6e-09 +Name: `pickle.loads(dump)`; Size: 5; Keys: int; Type: frozendict; Time: 1.32e-06; Sigma: 7e-08 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.loads(dump)`; Size: 1000; Keys: str; Type: dict; Time: 1.57e-04; Sigma: 8e-06 +Name: `pickle.loads(dump)`; Size: 1000; Keys: str; Type: frozendict; Time: 1.69e-04; Sigma: 7e-06 +//////////////////////////////////////////////////////////////////////////////// +Name: `pickle.loads(dump)`; Size: 1000; Keys: int; Type: dict; Time: 5.97e-05; Sigma: 5e-06 +Name: `pickle.loads(dump)`; Size: 1000; Keys: int; Type: frozendict; Time: 6.68e-05; Sigma: 2e-06 +################################################################################ +//////////////////////////////////////////////////////////////////////////////// +Name: `class.fromkeys()`; Size: 5; Keys: str; Type: dict; Time: 1.88e-07; Sigma: 1e-09 +Name: `class.fromkeys()`; Size: 5; Keys: str; Type: frozendict; Time: 2.22e-07; Sigma: 7e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `class.fromkeys()`; Size: 5; Keys: int; Type: dict; Time: 2.08e-07; Sigma: 6e-09 +Name: `class.fromkeys()`; Size: 5; Keys: int; Type: frozendict; Time: 2.44e-07; Sigma: 2e-09 +//////////////////////////////////////////////////////////////////////////////// +Name: `class.fromkeys()`; Size: 1000; Keys: str; Type: dict; Time: 4.05e-05; Sigma: 4e-06 +Name: `class.fromkeys()`; Size: 1000; Keys: str; Type: frozendict; Time: 3.84e-05; Sigma: 5e-07 +//////////////////////////////////////////////////////////////////////////////// +Name: `class.fromkeys()`; Size: 1000; Keys: int; Type: dict; Time: 2.93e-05; Sigma: 7e-07 +Name: `class.fromkeys()`; Size: 1000; Keys: int; Type: frozendict; Time: 3.08e-05; Sigma: 2e-06 +################################################################################ +``` + +[1] Benchmarks done under Linux 64 bit, Python 3.10.2, using the C Extension. diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/RECORD b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..45fa062b87b6b8bc508452a38be5210948b411c4 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/RECORD @@ -0,0 +1,21 @@ +frozendict-2.4.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +frozendict-2.4.7.dist-info/METADATA,sha256=D95cS34PIQofCL9byKAkcGLrfd9cPWA03xdMW4NzqFU,23571 +frozendict-2.4.7.dist-info/RECORD,, +frozendict-2.4.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +frozendict-2.4.7.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +frozendict-2.4.7.dist-info/licenses/LICENSE.txt,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652 +frozendict-2.4.7.dist-info/top_level.txt,sha256=H0x_yOfp00xK1WR_JMHct-wr-7Ht9uC9iQR2aHNL_uw,11 +frozendict/__init__.py,sha256=N464Qu1PA-bafz8DetBx4sSsayDQuytu3_emp_Q2q-w,1533 +frozendict/__init__.pyi,sha256=yjX57g8jPjs-sNYf1ipFeEQ1GW8VYy1fgQXRWFeCa_w,3748 +frozendict/__pycache__/__init__.cpython-312.pyc,, +frozendict/__pycache__/_frozendict_py.cpython-312.pyc,, +frozendict/__pycache__/cool.cpython-312.pyc,, +frozendict/__pycache__/core.cpython-312.pyc,, +frozendict/__pycache__/monkeypatch.cpython-312.pyc,, +frozendict/__pycache__/version.cpython-312.pyc,, +frozendict/_frozendict_py.py,sha256=0VtTC37NPZS5LmGeyPvYNCXBGAhVyNQjuv70xDIdsyc,6518 +frozendict/cool.py,sha256=z0IA4nzRYrVVFjCeXO53BBTn9CgU0vVKEzKcj4nVi20,8602 +frozendict/core.py,sha256=ZHj6y3awRhHRJpgD7qCFjhY7U_jjvjUdOUVWn1kpZ5Y,218 +frozendict/monkeypatch.py,sha256=T0pM5-dAasRrzCDL_mgtMkksXtW2Awlw4_3xgWO_VH0,6021 +frozendict/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +frozendict/version.py,sha256=ogkQ0N4sJsJf51jXeMctGisJvzlbX_NP7bsIFPjRajs,18 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/REQUESTED b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/WHEEL b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/licenses/LICENSE.txt b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..0a041280bd00a9d068f503b8ee7ce35214bd24a1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/licenses/LICENSE.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/top_level.txt b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..302328f60e50663123555344652eff53a3ced359 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict-2.4.7.dist-info/top_level.txt @@ -0,0 +1 @@ +frozendict diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9b2c1923cf504d497aab3c7b36d21c3b09dc314e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__init__.py @@ -0,0 +1,61 @@ +r""" +Provides frozendict, a simple immutable dictionary. +""" + +try: # pragma: no cover + from ._frozendict import * + c_ext = True + # noinspection PyUnresolvedReferences + del _frozendict +except ImportError: + from ._frozendict_py import * + c_ext = False + +from . import cool +from . import monkeypatch +from .cool import * +from .version import version as __version__ + + +def _getFrozendictJsonEncoder(BaseJsonEncoder = None): + if BaseJsonEncoder is None: # pragma: no cover + from json.encoder import JSONEncoder + + BaseJsonEncoder = JSONEncoder + + class FrozendictJsonEncoderInternal(BaseJsonEncoder): + def default(self, obj): + if isinstance(obj, frozendict): # pragma: no cover + # TODO create a C serializer + return dict(obj) + + return BaseJsonEncoder.default( + self, + obj + ) # pragma: no cover + + return FrozendictJsonEncoderInternal + + +FrozendictJsonEncoder = _getFrozendictJsonEncoder() +monkeypatch.patchOrUnpatchAll(patch = True, warn = False) + + +from collections.abc import Mapping + +# noinspection PyUnresolvedReferences +Mapping.register(frozendict) +del Mapping + + +if c_ext: # pragma: no cover + __all__ = (frozendict.__name__, ) +else: + __all__ = _frozendict_py.__all__ + del _frozendict_py + +# TODO deprecated, to remove in future versions +FrozenOrderedDict = frozendict + +__all__ += cool.__all__ +__all__ += (FrozendictJsonEncoder.__name__, "FrozenOrderedDict") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__init__.pyi b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0f0217ea311becd1d1135dc27f5e86cd5e3d8e0e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__init__.pyi @@ -0,0 +1,123 @@ +from __future__ import annotations + +from typing import ( + TypeVar, + overload, + Optional, + Union, + Any, + Dict, + Callable, +) + +from collections.abc import Hashable + +try: + from typing import Mapping, Iterable, Iterator, Tuple, Type +except ImportError: + from collections.abc import Mapping, Iterable, Iterator + Tuple = tuple + Type = type + +K = TypeVar("K") +V = TypeVar("V", covariant=True) +K2 = TypeVar("K2") +V2 = TypeVar("V2", covariant=True) +SelfT = TypeVar("SelfT", bound=frozendict[K, V]) + +# noinspection PyPep8Naming +class frozendict(Mapping[K, V]): + @overload + def __new__(cls: Type[SelfT]) -> SelfT: ... + @overload + def __new__(cls: Type[SelfT], **kwargs: V) -> frozendict[str, V]: ... + @overload + def __new__(cls: Type[SelfT], mapping: Mapping[K, V]) -> SelfT: ... + @overload + def __new__(cls: Type[SelfT], iterable: Iterable[Tuple[K, V]]) -> SelfT: ... + + def __getitem__(self: SelfT, key: K) -> V: ... + def __len__(self: SelfT) -> int: ... + def __iter__(self: SelfT) -> Iterator[K]: ... + def __hash__(self: SelfT) -> int: ... + def __reversed__(self: SelfT) -> Iterator[K]: ... + def copy(self: SelfT) -> SelfT: ... + def __copy__(self: SelfT) -> SelfT: ... + def __deepcopy__(self: SelfT) -> SelfT: ... + def delete(self: SelfT, key: K) -> SelfT: ... + @overload + def key(self: SelfT, index: int) -> K: ... + @overload + def key(self: SelfT) -> K: ... + @overload + def value(self: SelfT, index: int) -> V: ... + @overload + def value(self: SelfT) -> V: ... + @overload + def item(self: SelfT, index: int) -> Tuple[K, V]: ... + @overload + def item(self: SelfT) -> Tuple[K, V]: ... + @overload + def __or__(self: SelfT, other: Mapping[K, V]) -> SelfT: ... + @overload + def __or__(self: SelfT, other: Mapping[K2, V]) -> frozendict[Union[K, K2], V]: ... + @overload + def __or__(self: SelfT, other: Mapping[K, V2]) -> frozendict[K, Union[V, V2]]: ... + @overload + def __or__(self: SelfT, other: Mapping[K2, V2]) -> frozendict[Union[K, K2], Union[V, V2]]: ... + @overload + def set(self: SelfT, key: K, value: V) -> SelfT: ... + @overload + def set(self: SelfT, key: K2, value: V) -> frozendict[Union[K, K2], V]: ... + @overload + def set(self: SelfT, key: K, value: V2) -> frozendict[K, Union[V, V2]]: ... + @overload + def set(self: SelfT, key: K2, value: V2) -> frozendict[Union[K, K2], Union[V, V2]]: ... + @overload + def setdefault(self: SelfT, key: K) -> SelfT: ... + @overload + def setdefault(self: SelfT, key: K2) -> SelfT: ... + @overload + def setdefault(self: SelfT, key: K, default: V) -> SelfT: ... + @overload + def setdefault(self: SelfT, key: K2, default: V) -> frozendict[Union[K, K2], V]: ... + @overload + def setdefault(self: SelfT, key: K, default: V2) -> frozendict[K, Union[V, V2]]: ... + @overload + def setdefault(self: SelfT, key: K2, default: V2) -> frozendict[Union[K, K2], Union[V, V2]]: ... + + @classmethod + def fromkeys( + cls: Type[SelfT], + seq: Iterable[K], + value: Optional[V] = None + ) -> SelfT: ... + + +FrozenOrderedDict = frozendict +c_ext: bool + +class FreezeError(Exception): pass + + +class FreezeWarning(UserWarning): pass + +# PyCharm complains about returning Hashable, because +# it's not subscriptable +def deepfreeze( + o: Any, + custom_converters: Optional[Dict[Any, Callable[[Any], Hashable]]] = None, + custom_inverse_converters: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: ... + +def register( + to_convert: Any, + converter: Callable[[Any], Any], + *, + inverse: bool = False +) -> None: ... + +def unregister( + type: Any, + inverse: bool = False +) -> None: ... diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..530bd985d37b6d54cbc1a3daf64f93d7e1dad06f Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/_frozendict_py.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/_frozendict_py.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5feef600fda27b43cd9b78230857d7633d924ee Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/_frozendict_py.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/cool.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/cool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9d7f6365e15f306a112631c549a2d416a52c298 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/cool.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/core.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b8fb1ee5195156978cf406b26cede579db7c1eb Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/core.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/monkeypatch.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/monkeypatch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d7fb000eb14aeb4a2492a0569134f1d1b6bea1a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/monkeypatch.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/version.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22b967846e73cdde1a8be0908f1ecd8eb0772e54 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/__pycache__/version.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/_frozendict_py.py b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/_frozendict_py.py new file mode 100644 index 0000000000000000000000000000000000000000..6bd321a0bf4cf3de8af59e3722d0e124a6cde66f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/_frozendict_py.py @@ -0,0 +1,254 @@ +from copy import deepcopy + + +def immutable(self, *_args, **_kwargs): + r""" + Function for not implemented method since the object is immutable + """ + + raise AttributeError( + f"'{self.__class__.__name__}' object is read-only" + ) + + +_empty_frozendict = None +_module_name = "frozendict" + + +# noinspection PyPep8Naming +class frozendict(dict): + r""" + A simple immutable dictionary. + + The API is the same as `dict`, without methods that can change the + immutability. In addition, it supports __hash__(). + """ + + __slots__ = ( + "_hash", + ) + + @classmethod + def fromkeys(cls, *args, **kwargs): + r""" + Identical to dict.fromkeys(). + """ + + return cls(dict.fromkeys(*args, **kwargs)) + + # noinspection PyMethodParameters + def __new__(e4b37cdf_d78a_4632_bade_6f0579d8efac, *args, **kwargs): + cls = e4b37cdf_d78a_4632_bade_6f0579d8efac + + has_kwargs = bool(kwargs) + continue_creation = True + self = None + + # check if there's only an argument and it's of the same class + if len(args) == 1 and not has_kwargs: + it = args[0] + + # no isinstance, to avoid subclassing problems + if it.__class__ == frozendict and cls == frozendict: + self = it + continue_creation = False + + if continue_creation: + self = dict.__new__(cls, *args, **kwargs) + + dict.__init__(self, *args, **kwargs) + + # empty singleton - start + + if self.__class__ == frozendict and not len(self): + global _empty_frozendict + + if _empty_frozendict is None: + _empty_frozendict = self + else: + self = _empty_frozendict + continue_creation = False + + # empty singleton - end + + if continue_creation: + object.__setattr__(self, "_hash", -1) + + return self + + # noinspection PyMissingConstructor + def __init__(self, *args, **kwargs): + pass + + def __hash__(self, *args, **kwargs): + r""" + Calculates the hash if all values are hashable, otherwise + raises a TypeError. + """ + + if self._hash != -1: + _hash = self._hash + else: + fs = frozenset(self.items()) + _hash = hash(fs) + + object.__setattr__(self, "_hash", _hash) + + return _hash + + def __repr__(self, *args, **kwargs): + r""" + Identical to dict.__repr__(). + """ + + body = super().__repr__(*args, **kwargs) + klass = self.__class__ + + if klass == frozendict: + name = f"{_module_name}.{klass.__name__}" + else: + name = klass.__name__ + + return f"{name}({body})" + + def copy(self): + r""" + Return the object itself, as it's an immutable. + """ + + klass = self.__class__ + + if klass == frozendict: + return self + + return klass(self) + + def __copy__(self, *args, **kwargs): + r""" + See copy(). + """ + + return self.copy() + + def __deepcopy__(self, memo, *args, **kwargs): + r""" + As for tuples, if hashable, see copy(); otherwise, it returns a + deepcopy. + """ + + klass = self.__class__ + return_copy = klass == frozendict + + if return_copy: + try: + hash(self) + except TypeError: + return_copy = False + + if return_copy: + return self.copy() + + tmp = deepcopy(dict(self)) + + return klass(tmp) + + def __reduce__(self, *args, **kwargs): + r""" + Support for `pickle`. + """ + + return (self.__class__, (dict(self),)) + + def set(self, key, val): + new_self = dict(self) + new_self[key] = val + + return self.__class__(new_self) + + def setdefault(self, key, default=None): + if key in self: + return self + + new_self = dict(self) + + new_self[key] = default + + return self.__class__(new_self) + + def delete(self, key): + new_self = dict(self) + del new_self[key] + + if new_self: + return self.__class__(new_self) + + return self.__class__() + + def _get_by_index(self, collection, index): + try: + return collection[index] + except IndexError: + maxindex = len(collection) - 1 + name = self.__class__.__name__ + raise IndexError( + f"{name} index {index} out of range {maxindex}" + ) from None + + def key(self, index=0): + collection = tuple(self.keys()) + + return self._get_by_index(collection, index) + + def value(self, index=0): + collection = tuple(self.values()) + + return self._get_by_index(collection, index) + + def item(self, index=0): + collection = tuple(self.items()) + + return self._get_by_index(collection, index) + + def __setitem__(self, key, val, *args, **kwargs): + raise TypeError( + f"'{self.__class__.__name__}' object doesn't support item " + "assignment" + ) + + def __delitem__(self, key, *args, **kwargs): + raise TypeError( + f"'{self.__class__.__name__}' object doesn't support item " + "deletion" + ) + + +def frozendict_or(self, other, *_args, **_kwargs): + res = {} + res.update(self) + res.update(other) + + return self.__class__(res) + + +frozendict.__or__ = frozendict_or +frozendict.__ior__ = frozendict_or + +try: + # noinspection PyStatementEffect + frozendict.__reversed__ +except AttributeError: # pragma: no cover + def frozendict_reversed(self, *_args, **_kwargs): + return reversed(tuple(self)) + + + frozendict.__reversed__ = frozendict_reversed + +frozendict.clear = immutable +frozendict.pop = immutable +frozendict.popitem = immutable +frozendict.update = immutable +frozendict.__delattr__ = immutable +frozendict.__setattr__ = immutable +frozendict.__module__ = _module_name + +__all__ = (frozendict.__name__,) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/cool.py b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/cool.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc6e75ff74488f8614dae526f5c71c3fa824837 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/cool.py @@ -0,0 +1,328 @@ +from collections.abc import MutableMapping, MutableSequence, MutableSet +from enum import Enum +from types import MappingProxyType + +from array import array +from frozendict import frozendict + +# fix for python 3.9- + +# coverage does not work here! +if not issubclass(array, MutableSequence): # pragma: no cover + # noinspection PyUnresolvedReferences + MutableSequence.register(array) + + +def isIterableNotString(o): + from collections import abc + + return ( + isinstance(o, abc.Iterable) and + not isinstance(o, memoryview) and + not hasattr(o, "isalpha") + ) + + +def getItems(o): + from collections import abc + + if not isinstance(o, abc.Iterable): + raise TypeError("object must be an iterable") + + if isinstance(o, abc.Mapping): + return dict.items + + return enumerate + + +def nil(x): + return x + + +_freeze_conversion_map = frozendict({ + MutableMapping: frozendict, + bytearray: bytes, + MutableSequence: tuple, + MutableSet: frozenset, + Enum: nil, +}) + +_freeze_conversion_map_custom = {} + + +class FreezeError(Exception): + pass + + +class FreezeWarning(UserWarning): + pass + + +def register(to_convert, converter, *, inverse = False): + r""" + Adds a `converter` for a type `to_convert`. `converter` + must be callable. The new converter will be used by `deepfreeze()` + and has precedence over any previous converter. + + If `to_covert` has already a converter, a FreezeWarning is raised. + + If `inverse` is True, the conversion is considered from an immutable + type to a mutable one. This make it possible to convert mutable + objects nested in the registered immutable one. + """ + + if not issubclass(type(to_convert), type): + raise ValueError( + f"`to_convert` parameter must be a type, {to_convert} found" + ) + + try: + converter.__call__ + except AttributeError: + raise ValueError( + f"`converter` parameter must be a callable, {converter}" + + "found" + ) + + if inverse: + freeze_conversion_map = getFreezeConversionInverseMap() + else: + freeze_conversion_map = getFreezeConversionMap() + + if to_convert in freeze_conversion_map: + import warnings + + warnings.warn( + f"{to_convert.__name__} is already in the conversion map", + FreezeWarning + ) + + if inverse: + freeze_conversion_map = _freeze_conversion_inverse_map_custom + else: + freeze_conversion_map = _freeze_conversion_map_custom + + freeze_conversion_map[to_convert] = converter + + +def unregister(type, inverse = False): + r""" + Unregister a type from custom conversion. If `inverse` is `True`, + the unregistered conversion is an inverse conversion + (see `register()`). + """ + + if inverse: + freeze_conversion_map = _freeze_conversion_inverse_map_custom + else: + freeze_conversion_map = _freeze_conversion_map_custom + + try: + del freeze_conversion_map[type] + except KeyError: + raise FreezeError(f"{type.__name__} is not registered") + + +def getFreezeConversionMap(): + return _freeze_conversion_map | _freeze_conversion_map_custom + + +_freeze_conversion_inverse_map = frozendict({ + frozendict: dict, + MappingProxyType: dict, + tuple: list, +}) + +_freeze_conversion_inverse_map_custom = {} + + +def getFreezeConversionInverseMap(): + return ( + _freeze_conversion_inverse_map | + _freeze_conversion_inverse_map_custom + ) + + +_freeze_types = ( + [x for x in _freeze_conversion_map] + + [x for x in _freeze_conversion_inverse_map] +) + + +def getFreezeTypes(): + return (tuple( + _freeze_types + + [x for x in _freeze_conversion_map_custom] + + [x for x in _freeze_conversion_inverse_map_custom] + )) + + +_freeze_types_plain = (MutableSet, bytearray, array) + + +def deepfreeze( + o, + custom_converters = None, + custom_inverse_converters = None +): + r""" + Converts the object and all the objects nested in it in its + immutable counterparts. + + The conversion map is in getFreezeConversionMap(). + + You can register a new conversion using `register()` You can also + pass a map of custom converters with `custom_converters` and a map + of custom inverse converters with `custom_inverse_converters`, + without using `register()`. + + By default, if the type is not registered and has a `__dict__` + attribute, it's converted to the `frozendict` of that `__dict__`. + + This function assumes that hashable == immutable (that is not + always true). + + This function uses recursion, with all the limits of recursions in + Python. + + Where is a good old tail call when you need it? + """ + + from frozendict import frozendict + + if custom_converters is None: + custom_converters = frozendict() + + if custom_inverse_converters is None: + custom_inverse_converters = frozendict() + + for type_i, converter in custom_converters.items(): + if not issubclass(type(type_i), type): + raise ValueError( + f"{type_i} in `custom_converters` parameter is not a " + + "type" + ) + + try: + converter.__call__ + except AttributeError: + raise ValueError( + f"converter for {type_i} in `custom_converters` " + + "parameter is not a callable" + ) + + for type_i, converter in custom_inverse_converters.items(): + if not issubclass(type(type_i), type): + raise ValueError( + f"{type_i} in `custom_inverse_converters` parameter " + + "is not a type" + ) + + try: + converter.__call__ + except AttributeError: + raise ValueError( + f"converter for {type_i} in " + + "`custom_inverse_converters`parameter is not a callable" + ) + + type_o = type(o) + + freeze_types = tuple(custom_converters.keys()) + getFreezeTypes() + + base_type_o = None + + for freeze_type in freeze_types: + if isinstance(o, freeze_type): + base_type_o = freeze_type + break + + if base_type_o is None: + # this is before hash check because all object in Python are + # hashable by default, if not explicitly suppressed + try: + o.__dict__ + except AttributeError: + pass + else: + return frozendict(o.__dict__) + + try: + hash(o) + except TypeError: + pass + else: + # without a converter, we can only hope that + # hashable == immutable + return o + + supported_types = ", ".join((x.__name__ for x in freeze_types)) + + err = ( + f"type {type_o} is not hashable or is not equal or a " + + f"subclass of the supported types: {supported_types}" + ) + + raise TypeError(err) + + freeze_conversion_map = getFreezeConversionMap() + + freeze_conversion_map = freeze_conversion_map | custom_converters + + if base_type_o in _freeze_types_plain: + return freeze_conversion_map[base_type_o](o) + + if not isIterableNotString(o): + return freeze_conversion_map[base_type_o](o) + + freeze_conversion_inverse_map = getFreezeConversionInverseMap() + + freeze_conversion_inverse_map = ( + freeze_conversion_inverse_map | + custom_inverse_converters + ) + + frozen_type = base_type_o in freeze_conversion_inverse_map + + if frozen_type: + o = freeze_conversion_inverse_map[base_type_o](o) + + from copy import copy + + o_copy = copy(o) + + for k, v in getItems(o_copy)(o_copy): + o_copy[k] = deepfreeze( + v, + custom_converters = custom_converters, + custom_inverse_converters = custom_inverse_converters + ) + + try: + freeze = freeze_conversion_map[base_type_o] + except KeyError: + if frozen_type: + freeze = type_o + else: # pragma: no cover + raise + + return freeze(o_copy) + + +__all__ = ( + deepfreeze.__name__, + register.__name__, + unregister.__name__, + getFreezeConversionMap.__name__, + getFreezeConversionInverseMap.__name__, + FreezeError.__name__, + FreezeWarning.__name__, +) + +del MappingProxyType +del array +del frozendict +del MutableMapping +del MutableSequence +del MutableSet +del Enum diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/core.py b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/core.py new file mode 100644 index 0000000000000000000000000000000000000000..298d8fa7e2ad5822afb25391aa0862f719dfd649 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/core.py @@ -0,0 +1,6 @@ +# this provides compatibility for older pickles +# created on a python-only implementation that +# specifically mention frozendict.core.frozendict + +# noinspection PyUnresolvedReferences +from frozendict import frozendict diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/monkeypatch.py b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/monkeypatch.py new file mode 100644 index 0000000000000000000000000000000000000000..53d278fbf38882cc6092a8315ca6cf06ebda6f6b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/monkeypatch.py @@ -0,0 +1,208 @@ +_OldJsonEncoder = None +_oldOrjsonDumps = None +_oldMutableMappingSubclasshook = None + + +class MonkeypatchWarning(UserWarning): + pass + + +def checkCExtension(*, warn, warn_c = False): + import frozendict as cool + + res = cool.c_ext + + if warn and res == warn_c: + if warn_c: # pragma: no cover + msg = "C Extension version, monkeypatch will be not applied" + else: + msg = "Pure Python version, monkeypatch will be not applied" + + import warnings + + warnings.warn(msg, MonkeypatchWarning) + + return res + + +def patchOrUnpatchJson(*, patch, warn = True): # pragma: no cover + if not checkCExtension(warn = warn): + return + + from importlib import import_module + self = import_module(__name__) + import frozendict as cool + import json + + OldJsonEncoder = self._OldJsonEncoder + + # noinspection PyUnresolvedReferences, PyProtectedMember + FrozendictJsonEncoder = cool._getFrozendictJsonEncoder( + OldJsonEncoder + ) + + if patch: + DefaultJsonEncoder = FrozendictJsonEncoder + else: + DefaultJsonEncoder = OldJsonEncoder + + if DefaultJsonEncoder is None: + default_json_encoder = None + else: + default_json_encoder = DefaultJsonEncoder( + skipkeys = False, + ensure_ascii = True, + check_circular = True, + allow_nan = True, + indent = None, + separators = None, + default = None, + ) + + if patch: + if OldJsonEncoder is None: + self._OldJsonEncoder = json.encoder.JSONEncoder + else: + if OldJsonEncoder is None: + raise ValueError( + "Old json encoder is None " + + "(maybe you already unpatched json?)" + ) + + self._OldJsonEncoder = None + + cool.FrozendictJsonEncoder = FrozendictJsonEncoder + + json.JSONEncoder = DefaultJsonEncoder + json.encoder.JSONEncoder = DefaultJsonEncoder + json._default_encoder = default_json_encoder + + +def patchOrUnpatchOrjson(*, patch, warn = True): # pragma: no cover + if not checkCExtension(warn = warn): + return + + from importlib import import_module + self = import_module(__name__) + # noinspection PyUnresolvedReferences + import orjson + + if self._oldOrjsonDumps is None: + if not patch: + raise ValueError( + "Old orjson encoder is None " + + "(maybe you already unpatched orjson?)" + ) + + oldOrjsonDumps = orjson.dumps + else: + oldOrjsonDumps = self._oldOrjsonDumps + + if patch: + from frozendict import frozendict + + def frozendictOrjsonDumps(obj, *args, **kwargs): + if isinstance(obj, frozendict): + obj = dict(obj) + + return oldOrjsonDumps(obj, *args, **kwargs) + + defaultOrjsonDumps = frozendictOrjsonDumps + newOldOrjsonDumps = oldOrjsonDumps + else: + defaultOrjsonDumps = oldOrjsonDumps + newOldOrjsonDumps = None + + self._oldOrjsonDumps = newOldOrjsonDumps + orjson.dumps = defaultOrjsonDumps + orjson.orjson.dumps = defaultOrjsonDumps + + +def patchOrUnpatchMutableMappingSubclasshook( + *, + patch, + warn = True +): # pragma: no cover + warn_c = True + + if checkCExtension(warn = warn, warn_c = warn_c): + return + + from importlib import import_module + self = import_module(__name__) + from collections.abc import MutableMapping + from frozendict import frozendict + + if self._oldMutableMappingSubclasshook is None: + if not patch: + raise ValueError( + "Old MutableMapping subclasshook is None " + + "(maybe you already unpatched MutableMapping?)" + ) + + oldMutableMappingHook = MutableMapping.__subclasshook__ + else: + oldMutableMappingHook = self._oldMutableMappingSubclasshook + + if patch: + # noinspection PyDecorator + @classmethod + def frozendictMutableMappingSubclasshook( + klass, + subclass, + *args, + **kwargs + ): + if klass == MutableMapping: + if issubclass(subclass, frozendict): + return False + + # noinspection PyArgumentList + return oldMutableMappingHook( + subclass, + *args, + **kwargs + ) + + return NotImplemented + + defaultMutableMappingHook = frozendictMutableMappingSubclasshook + newOldMutableMappingHook = oldMutableMappingHook + else: + defaultMutableMappingHook = oldMutableMappingHook + newOldMutableMappingHook = None + + self._oldMutableMappingSubclasshook = newOldMutableMappingHook + MutableMapping.__subclasshook__ = defaultMutableMappingHook + + try: + # noinspection PyUnresolvedReferences, PyProtectedMember + MutableMapping._abc_caches_clear() + except AttributeError: + # noinspection PyUnresolvedReferences, PyProtectedMember + MutableMapping._abc_cache.discard(frozendict) + # noinspection PyUnresolvedReferences, PyProtectedMember + MutableMapping._abc_negative_cache.discard(frozendict) + + +def patchOrUnpatchAll(*, patch, warn = True, raise_orjson = False): + patchOrUnpatchJson(patch = patch, warn = warn) + + try: + import orjson + except ImportError: # pragma: no cover + if raise_orjson: + raise + else: # pragma: no cover + patchOrUnpatchOrjson(patch = patch, warn = warn) + + patchOrUnpatchMutableMappingSubclasshook(patch = patch, warn = warn) + + +__all__ = ( + patchOrUnpatchJson.__name__, + patchOrUnpatchOrjson.__name__, + patchOrUnpatchMutableMappingSubclasshook.__name__, + patchOrUnpatchAll.__name__, + MonkeypatchWarning.__name__, +) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/py.typed b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/version.py b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/version.py new file mode 100644 index 0000000000000000000000000000000000000000..23902f55bbb8a8e65d1332f8fdb8d853265e8b50 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/frozendict/version.py @@ -0,0 +1 @@ +version = "2.4.7" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/CHANGELOG.md b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..e5b509080993748baa53308b06bf655908fa1e7a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/CHANGELOG.md @@ -0,0 +1,639 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). + +## [unreleased] - YYYY-MM-DD + +### Added + +- + +### Changed + +- + +### Removed + +- + +### Fixed + +- + +-- + +## [2.6.5] - 2026-05-27 + +### Changed + +- Use fs.pipe() for S3/GCS checkpoint uploads in _atomic_save ([#21595](https://github.com/Lightning-AI/pytorch-lightning/pull/21595) + +## [2.6.2] - 2026-03-19 + +### Fixed + +- Fixed FSDP mixed precision (`bf16-mixed`, `16-mixed`) initializing model parameters in half precision instead of fp32 ([#21586](https://github.com/Lightning-AI/pytorch-lightning/pull/21586)) + +- Fixed `device_mesh` type hint in `FSDPStrategy` to accept a 2-element tuple via the CLI ([#21581](https://github.com/Lightning-AI/pytorch-lightning/pull/21581)) + +--- + +## [2.6.1] - 2026-01-30 + +### Added + +- Exposed `weights_only` argument for loading checkpoints in `Fabric.load()` and `Fabric.load_raw()` ([#21470](https://github.com/Lightning-AI/pytorch-lightning/pull/21470)) + +### Fixed + +- Fixed `DistributedSamplerWrapper` not forwarding `set_epoch` to the underlying sampler ([#21454](https://github.com/Lightning-AI/pytorch-lightning/pull/21454)) +- Fixed DDP notebook CUDA fork check to allow passive initialization when CUDA is not actively used ([#21402](https://github.com/Lightning-AI/pytorch-lightning/pull/21402)) + + +## [2.6.0] - 2025-11-28 + +### Added + +- Added kwargs-filtering for `Fabric.call` to support different callback method signatures ([#21258](https://github.com/Lightning-AI/pytorch-lightning/pull/21258)) + +### Changed + +- Expose `weights_only` argument for `Trainer.{fit,validate,test,predict}` and let `torch` handle default value ([#21072](https://github.com/Lightning-AI/pytorch-lightning/pull/21072)) +- Set `_DeviceDtypeModuleMixin._device` from torch's default device function ([#21164](https://github.com/Lightning-AI/pytorch-lightning/pull/21164)) + +### Fixed + +- Fixed issue in detecting MPIEnvironment with partial mpi4py installation ([#21353](https://github.com/Lightning-AI/pytorch-lightning/pull/21353)) +- Learning rate scheduler is stepped at the end of epoch when `on_train_batch_start` returns -1 ([#21296](https://github.com/Lightning-AI/pytorch-lightning/issues/21296)). +- Fixed FSDP mixed precision semantics and added user warning ([#21361](https://github.com/Lightning-AI/pytorch-lightning/pull/21361)) + + +## [2.5.5] - 2025-09-05 + +### Changed + +- Include `exclude_frozen_parameters` to `DeepSpeedStrategy` ([#21060](https://github.com/Lightning-AI/pytorch-lightning/pull/21060)) +- Let `_get_default_process_group_backend_for_device` support more hardware platforms ( + [#21057](https://github.com/Lightning-AI/pytorch-lightning/pull/21057), [#21093](https://github.com/Lightning-AI/pytorch-lightning/pull/21093)) + +### Fixed + +- Fixed with adding a missing device id for pytorch 2.8 ([#21105](https://github.com/Lightning-AI/pytorch-lightning/pull/21105)) +- Respecting `verbose=False` in `seed_everything` when no seed is provided ([#21161](https://github.com/Lightning-AI/pytorch-lightning/pull/21161)) + + +## [2.5.4] - 2025-08-29 + +### Changed + +- Added support for NVIDIA H200 GPUs in `get_available_flops` ([#21119](https://github.com/Lightning-AI/pytorch-lightning/pull/21119)) + + + +## [2.5.3] - 2025-08-13 + +### Changed + +- Enable "auto" for `devices` and `accelerator` as CLI arguments ([#20913](https://github.com/Lightning-AI/pytorch-lightning/pull/20913)) +- Raise ValueError when seed is `out-of-bounds` or `cannot be cast to int` ([#21029](https://github.com/Lightning-AI/pytorch-lightning/pull/21029)) + +### Fixed + +- Fixed XLA strategy to add support for `global_ordinal`, `local_ordinal`, `world_size` which came instead of deprecated methods ([#20852](https://github.com/Lightning-AI/pytorch-lightning/issues/20852)) +- Fixed remove extra `name` parameter in accelerator registry decorator ([#20975](https://github.com/Lightning-AI/pytorch-lightning/pull/20975)) + + +## [2.5.2] - 2025-3-20 + +### Changed + +- Ensure correct device is used for autocast when mps is selected as Fabric accelerator ([#20876](https://github.com/Lightning-AI/pytorch-lightning/pull/20876)) + +### Fixed + +- Fix: `TransformerEnginePrecision` conversion for layers with `bias=False` ([#20805](https://github.com/Lightning-AI/pytorch-lightning/pull/20805)) + + +## [2.5.1] - 2025-03-18 + +### Changed + +- Added logging support for list of dicts without collapsing to a single key ([#19957](https://github.com/Lightning-AI/pytorch-lightning/pull/19957)) + +### Removed + +- Removed legacy support for `lightning run model`; use `fabric run` instead ([#20588](https://github.com/Lightning-AI/pytorch-lightning/pull/20588)) + + +## [2.5.0] - 2024-12-19 + +### Added + +- Added `step` parameter to `TensorBoardLogger.log_hyperparams` to visualize changes during training ([#20176](https://github.com/Lightning-AI/pytorch-lightning/pull/20176)) +- Added timeout to DeepSpeedStrategy ([#20474](https://github.com/Lightning-AI/pytorch-lightning/pull/20474)) +- Added FP8 + FSDP2 + torch.compile examples for Fabric ([#20440](https://github.com/Lightning-AI/pytorch-lightning/pull/20440)) +- Added RTX 4080 super to chips dictionary ([#20285](https://github.com/Lightning-AI/pytorch-lightning/pull/20285)) +- Added device property to lazy load functionality ([#20183](https://github.com/Lightning-AI/pytorch-lightning/pull/20183)) +- Added `ddp_find_unused_parameters_true` alias in Fabric's DDPStrategy ([#20125](https://github.com/Lightning-AI/pytorch-lightning/pull/20125)) + +### Changed + +- Changed seeding NumPy using `np.random.SeedSequence()` in `pl_worker_init_function()` to robustly seed NumPy-dependent dataloader workers ([#20369](https://github.com/Lightning-AI/pytorch-lightning/pull/20369)) +- Bumped PyTorch to version `2.5` ([#20351](https://github.com/Lightning-AI/pytorch-lightning/pull/20351)) +- Update BitsAndBytes version ([#20313](https://github.com/Lightning-AI/pytorch-lightning/pull/20313)) + +### Fixed + +- Fixed use of `convert_module` in FSDP to avoid using more memory than necessary during initialization ([#20323](https://github.com/Lightning-AI/pytorch-lightning/pull/20323)) + +## [2.4.0] - 2024-08-06 + +### Added + +- Made saving non-distributed checkpoints fully atomic ([#20011](https://github.com/Lightning-AI/pytorch-lightning/pull/20011)) +- Added a flag `verbose` to the `seed_everything()` function ([#20108](https://github.com/Lightning-AI/pytorch-lightning/pull/20108)) +- Added support for PyTorch 2.4 ([#20028](https://github.com/Lightning-AI/pytorch-lightning/pull/20028)) +- Added support for Python 3.12 ([20078](https://github.com/Lightning-AI/pytorch-lightning/pull/20078)) + +### Changed + +- Changed the implementation of how seeds are chosen for dataloader workers when using `seed_everything(..., workers=True)` ([#20055](https://github.com/Lightning-AI/pytorch-lightning/pull/20055)) +- NumPy is no longer a required dependency ([#20090](https://github.com/Lightning-AI/pytorch-lightning/issues/20090)) + +### Removed + +- Removed support for PyTorch 2.1 ([#20009](https://github.com/Lightning-AI/pytorch-lightning/pull/20009)) +- Removed support for Python 3.8 ([#20071](https://github.com/Lightning-AI/pytorch-lightning/pull/20071)) + +### Fixed + +- Fixed an attribute error when loading a checkpoint into a quantized model using the `_lazy_load()` function ([#20121](https://github.com/Lightning-AI/pytorch-lightning/pull/20121)) +- Fixed `_optimizer_to_device` logic for special 'step' key in optimizer state causing performance regression ([#20019](https://github.com/Lightning-AI/pytorch-lightning/pull/20019)) + + +## [2.3.0] - 2024-06-13 + +### Added + +- Added sanitization for classes before logging them as hyperparameters ([#19771](https://github.com/Lightning-AI/pytorch-lightning/pull/19771)) +- Enabled consolidating distributed checkpoints through `fabric consolidate` in the new CLI ([#19560](https://github.com/Lightning-AI/pytorch-lightning/pull/19560)) +- Added the ability to explicitly mark forward methods in Fabric via `_FabricModule.mark_forward_method()` ([#19690](https://github.com/Lightning-AI/pytorch-lightning/pull/19690)) +- Added support for PyTorch 2.3 ([#19708](https://github.com/Lightning-AI/pytorch-lightning/pull/19708)) +- Added `ModelParallelStrategy` to support 2D parallelism ([#19846](https://github.com/Lightning-AI/pytorch-lightning/pull/19846), [#19852](https://github.com/Lightning-AI/pytorch-lightning/pull/19852), [#19870](https://github.com/Lightning-AI/pytorch-lightning/pull/19870), [#19872](https://github.com/Lightning-AI/pytorch-lightning/pull/19872)) +- Added a call to `torch.distributed.destroy_process_group` in atexit handler if process group needs destruction ([#19931](https://github.com/Lightning-AI/pytorch-lightning/pull/19931)) +- Added support for configuring hybrid-sharding by passing a tuple for the `FSDPStrategy(device_mesh=...)` argument ([#19504](https://github.com/Lightning-AI/pytorch-lightning/pull/19504)) + +### Changed + +- Renamed `lightning run model` to `fabric run` ([#19442](https://github.com/Lightning-AI/pytorch-lightning/pull/19442), [#19527](https://github.com/Lightning-AI/pytorch-lightning/pull/19527)) +- The `Fabric.rank_zero_first` context manager now uses a barrier without timeout to avoid long-running tasks to be interrupted ([#19448](https://github.com/Lightning-AI/pytorch-lightning/pull/19448)) +- Fabric now raises an error if you forget to call `fabric.backward()` when it is needed by the strategy or precision selection ([#19447](https://github.com/Lightning-AI/pytorch-lightning/pull/19447), [#19493](https://github.com/Lightning-AI/pytorch-lightning/pull/19493)) +- `_BackwardSyncControl` can now control what to do when gradient accumulation is disabled ([#19577](https://github.com/Lightning-AI/pytorch-lightning/pull/19577)) + +### Removed + +- Removed support for PyTorch 1.13 ([#19706](https://github.com/Lightning-AI/pytorch-lightning/pull/19706)) + +### Fixed + +- Fixed a matrix shape mismatch issue when running a model loaded from a quantized checkpoint (bitsandbytes) ([#19886](https://github.com/Lightning-AI/pytorch-lightning/pull/19886)) + + +## [2.2.2] - 2024-04-11 + +### Fixed + +- Fixed an issue causing a TypeError when using `torch.compile` as a decorator ([#19627](https://github.com/Lightning-AI/pytorch-lightning/pull/19627)) +- Fixed issue where some model methods couldn't be monkeypatched after being Fabric wrapped ([#19705](https://github.com/Lightning-AI/pytorch-lightning/pull/19705)) +- Fixed an issue causing weights to be reset in `Fabric.setup()` when using FSDP ([#19755](https://github.com/Lightning-AI/pytorch-lightning/pull/19755)) + + +## [2.2.1] - 2024-03-04 + +### Fixed + +- Fixed an issue with CSVLogger trying to append to file from a previous run when the version is set manually ([#19446](https://github.com/Lightning-AI/pytorch-lightning/pull/19446)) + + +## [2.2.0] - 2024-02-08 + +### Added + +- Added `lightning_fabric.utilities.ThroughputMonitor` and `lightning_fabric.utilities.Throughput` to track throughput and log it ([#18848](https://github.com/Lightning-AI/pytorch-lightning/pull/18848)) +- Added `lightning_fabric.utilities.AttributeDict` for convenient dict-attribute access to represent state in script ([#18943](https://github.com/Lightning-AI/pytorch-lightning/pull/18943)) +- Added support for meta-device initialization and materialization of 4-bit Bitsandbytes layers ([#19150](https://github.com/Lightning-AI/pytorch-lightning/pull/19150)) +- Added `TransformerEnginePrecision(fallback_compute_dtype=)` to control the dtype of operations that don't support fp8 ([#19082](https://github.com/Lightning-AI/pytorch-lightning/pull/19082)) +- Added support for clipping gradients by value with FSDP ([#19236](https://github.com/Lightning-AI/pytorch-lightning/pull/19236)) +- Added a utility function and CLI to consolidate FSDP sharded checkpoints into a single file ([#19213](https://github.com/Lightning-AI/pytorch-lightning/pull/19213)) +- Added support for re-compiling the model inside `Fabric.setup()` over the FSDP/DDP wrappers ([#19280](https://github.com/Lightning-AI/pytorch-lightning/pull/19280)) + +### Changed + +- `seed_everything()` without passing in a seed no longer randomly selects a seed, and now defaults to `0` ([#18846](https://github.com/Lightning-AI/pytorch-lightning/pull/18846)) +- Changed the `TransformerEnginePrecision(dtype=)` argument to `weights_dtype` and made it required ([#19082](https://github.com/Lightning-AI/pytorch-lightning/pull/19082)) +- The columns in the `metrics.csv` file produced by `CSVLogger` are now sorted alphabetically ([#19159](https://github.com/Lightning-AI/pytorch-lightning/pull/19159)) + +### Removed + +- Removed support for PyTorch 1.12 ([#19300](https://github.com/Lightning-AI/pytorch-lightning/pull/19300)) + +### Fixed + +- Fixed parsing of v100s GPUs in `get_available_flops` ([#18952](https://github.com/Lightning-AI/pytorch-lightning/pull/18952)) +- Fixed issue where the `precision="transformer-engine"` argument would not replace layers by default ([#19082](https://github.com/Lightning-AI/pytorch-lightning/pull/19082)) +- Fixed the input validation logic in `FSDPStrategy` to accept a `device_mesh` ([#19392](https://github.com/Lightning-AI/pytorch-lightning/pull/19392)) + + +## [2.1.4] - 2024-01-31 + +### Fixed + +- Fixed an issue preventing Fabric to run on CPU when the system's CUDA driver is outdated or broken ([#19234](https://github.com/Lightning-AI/pytorch-lightning/pull/19234)) +- Fixed typo in kwarg in SpikeDetection ([#19282](https://github.com/Lightning-AI/pytorch-lightning/pull/19282)) + + +## [2.1.3] - 2023-12-21 + +### Fixed + +- Avoid moving the model to device if `move_to_device=False` is passed ([#19152](https://github.com/Lightning-AI/pytorch-lightning/pull/19152)) +- Fixed broadcast at initialization in `MPIEnvironment` ([#19074](https://github.com/Lightning-AI/pytorch-lightning/pull/19074)) + + +## [2.1.2] - 2023-11-15 + +### Fixed + +- Fixed precision default from environment ([#18928](https://github.com/Lightning-AI/pytorch-lightning/pull/18928)) + + +## [2.1.1] - 2023-11-06 + +### Changed + +- Calling a method other than `forward` that invokes submodules is now an error when the model is wrapped (e.g., with DDP) ([#18819](https://github.com/Lightning-AI/pytorch-lightning/pull/18819)) + +### Fixed + +- Fixed false-positive warnings about method calls on the Fabric-wrapped module ([#18819](https://github.com/Lightning-AI/pytorch-lightning/pull/18819)) +- Refined the FSDP saving logic and error messaging when path exists ([#18884](https://github.com/Lightning-AI/pytorch-lightning/pull/18884)) +- Fixed layer conversion under `Fabric.init_module()` context manager when using the `BitsandbytesPrecision` plugin ([#18914](https://github.com/Lightning-AI/pytorch-lightning/pull/18914)) + + +## [2.1.0] - 2023-10-11 + +### Added + +- Added support for the TPU-v4 architecture ([#17227](https://github.com/Lightning-AI/pytorch-lightning/pull/17227)) +- Added support for XLA's new PJRT runtime ([#17352](https://github.com/Lightning-AI/pytorch-lightning/pull/17352)) +- Added support for Fully Sharded Data Parallel (FSDP) training with XLA ([#18126](https://github.com/Lightning-AI/pytorch-lightning/pull/18126), [#18424](https://github.com/Lightning-AI/pytorch-lightning/pull/18424), [#18430](https://github.com/Lightning-AI/pytorch-lightning/pull/18430)) +- Check for invalid TPU device inputs ([#17227](https://github.com/Lightning-AI/pytorch-lightning/pull/17227)) +- Added `XLAStrategy(sync_module_states=bool)` to control whether to broadcast the parameters to all devices ([#17522](https://github.com/Lightning-AI/pytorch-lightning/pull/17522)) +- Added support for joint setup of model and optimizer with FSDP ([#17305](https://github.com/Lightning-AI/pytorch-lightning/pull/17305)) +- Added support for handling multiple parameter groups in optimizers set up with FSDP ([#17305](https://github.com/Lightning-AI/pytorch-lightning/pull/17305)) +- Added support for saving and loading sharded model and optimizer state with `FSDPStrategy` ([#17323](https://github.com/Lightning-AI/pytorch-lightning/pull/17323)) +- Added a warning when calling methods on `_FabricModule` that bypass the strategy-specific wrappers ([#17424](https://github.com/Lightning-AI/pytorch-lightning/pull/17424)) +- Added `Fabric.init_tensor()` context manager to instantiate tensors efficiently directly on device and dtype ([#17488](https://github.com/Lightning-AI/pytorch-lightning/pull/17488)) +- Added `Fabric.init_module()` context manager to instantiate large models efficiently directly on device, dtype, and with sharding support ([#17462](https://github.com/Lightning-AI/pytorch-lightning/pull/17462)) + * Creates the model parameters in the desired dtype (`torch.float32`, `torch.float64`, `torch.float16`, or `torch.bfloat16`) depending on the 'true' precision choice in `Fabric(precision='32-true'|'64-true'|'16-true'|'bf16-true')` + * Handles initialization for FSDP models before wrapping and the Zero stage 3 initialization for DeepSpeed before sharding +- Added support for empty weight initialization with `Fabric.init_module(empty_init=True)` for checkpoint loading ([#17627](https://github.com/Lightning-AI/pytorch-lightning/pull/17627)) +- Added support for meta-device initialization with `Fabric.init_module(empty_init=True)` in FSDP ([#18122](https://github.com/Lightning-AI/pytorch-lightning/pull/18122)) +- Added `lightning_fabric.plugins.Precision.module_init_context()` and `lightning_fabric.strategies.Strategy.module_init_context()` context managers to control model and tensor instantiation ([#17462](https://github.com/Lightning-AI/pytorch-lightning/pull/17462)) +- `lightning_fabric.strategies.Strategy.tensor_init_context()` context manager to instantiate tensors efficiently directly on device and dtype ([#17607](https://github.com/Lightning-AI/pytorch-lightning/pull/17607)) +- Run the DDP wrapper in a CUDA stream ([#17334](https://github.com/Lightning-AI/pytorch-lightning/pull/17334)) +- Added support for true half-precision as `Fabric(precision="16-true"|"bf16-true")` ([#17287](https://github.com/Lightning-AI/pytorch-lightning/pull/17287)) +- Added support for mixed 8-bit precision as `Fabric(precision="transformer-engine")` using [Nvidia's Transformer Engine](https://docs.nvidia.com/deeplearning/transformer-engine) ([#17597](https://github.com/Lightning-AI/pytorch-lightning/pull/17597)) +- Added support for linear layer quantization with `Fabric(plugins=BitsandbytesPrecision())` using [bitsandbytes](https://github.com/TimDettmers/bitsandbytes) ([#18655](https://github.com/Lightning-AI/pytorch-lightning/pull/18655)) +- Added error messaging for missed `.launch()` when it is required ([#17570](https://github.com/Lightning-AI/pytorch-lightning/pull/17570)) +- Added support for saving checkpoints with either full state-dict or sharded state dict via `FSDPStrategy(state_dict_type="full"|"sharded")` ([#17526](https://github.com/Lightning-AI/pytorch-lightning/pull/17526)) +- Added support for loading a full-state checkpoint file into a sharded model ([#17623](https://github.com/Lightning-AI/pytorch-lightning/pull/17623)) +- Added support for calling hooks on a LightningModule via `Fabric.call` ([#17874](https://github.com/Lightning-AI/pytorch-lightning/pull/17874)) +- Added the parameter `Fabric.load(..., strict=True|False)` to enable non-strict loading of partial checkpoint state ([#17645](https://github.com/Lightning-AI/pytorch-lightning/pull/17645)) +- Added the parameter `Fabric.save(..., filter=...)` to enable saving a partial checkpoint state ([#17845](https://github.com/Lightning-AI/pytorch-lightning/pull/17845)) +- Added support for loading optimizer states from a full-state checkpoint file ([#17747](https://github.com/Lightning-AI/pytorch-lightning/pull/17747)) +- Automatically call `xla_model.mark_step()` before saving checkpoints with XLA ([#17882](https://github.com/Lightning-AI/pytorch-lightning/pull/17882)) +- Automatically call `xla_model.mark_step()` after `optimizer.step()` with XLA ([#17883](https://github.com/Lightning-AI/pytorch-lightning/pull/17883)) +- Added support for all half-precision modes in FSDP precision plugin ([#17807](https://github.com/Lightning-AI/pytorch-lightning/pull/17807)) +- Added `FSDPStrategy(activation_checkpointing_policy=...)` to customize the layer policy for automatic activation checkpointing (requires torch>=2.1) ([#18045](https://github.com/Lightning-AI/pytorch-lightning/pull/18045)) +- Added a callback for spike-detection ([#18014](https://github.com/Lightning-AI/pytorch-lightning/pull/18014)) +- Added the ability to set the `torch.distributed.fsdp.ShardingStrategy` via string in `FSDPStrategy` ([#18087](https://github.com/Lightning-AI/pytorch-lightning/pull/18087)) +- Improved error messages when attempting to load a DeepSpeed checkpoint at an invalid path ([#17795](https://github.com/Lightning-AI/pytorch-lightning/pull/17795)) +- Added `Fabric.load_raw()` for loading raw PyTorch state dict checkpoints for model or optimizer objects ([#18049](https://github.com/Lightning-AI/pytorch-lightning/pull/18049)) +- Allowed accessing rank information in the main process before processes are launched when using the `XLAStrategy` ([#18194](https://github.com/Lightning-AI/pytorch-lightning/pull/18194)) +- Added automatic process cleanup to avoid zombie child processes and stalls when exceptions are raised ([#18218](https://github.com/Lightning-AI/pytorch-lightning/pull/18218)) +- Added validation of user input for `devices` and `num_nodes` when running with `SLURM` or `TorchElastic` ([#18292](https://github.com/Lightning-AI/pytorch-lightning/pull/18292)) +- Improved the error messaging and instructions when handling custom batch samplers in distributed settings ([#18402](https://github.com/Lightning-AI/pytorch-lightning/pull/18402)) +- Added support for saving and loading stateful objects other than modules and optimizers ([#18513](https://github.com/Lightning-AI/pytorch-lightning/pull/18513)) +- Enabled the default process group configuration for FSDP's hybrid sharding ([#18583](https://github.com/Lightning-AI/pytorch-lightning/pull/18583)) +- Added `lightning_fabric.utilities.suggested_max_num_workers` to assist with setting a good value in distributed settings ([#18591](https://github.com/Lightning-AI/pytorch-lightning/pull/18591)) +- Added `lightning_fabric.utilities.is_shared_filesystem` utility function to automatically check whether the filesystem is shared between machines ([#18586](https://github.com/Lightning-AI/pytorch-lightning/pull/18586)) +- Removed support for PyTorch 1.11 ([#18691](https://github.com/Lightning-AI/pytorch-lightning/pull/18691)) +- Added support for passing the argument `.load_state_dict(..., assign=True|False)` on Fabric-wrapped modules in PyTorch 2.1 or newer ([#18690](https://github.com/Lightning-AI/pytorch-lightning/pull/18690)) + +### Changed + +- Allow using iterable-style datasets with TPUs ([#17331](https://github.com/Lightning-AI/pytorch-lightning/pull/17331)) +- Increased the minimum XLA requirement to 1.13 ([#17368](https://github.com/Lightning-AI/pytorch-lightning/pull/17368)) +- Fabric argument validation now only raises an error if conflicting settings are set through the CLI ([#17679](https://github.com/Lightning-AI/pytorch-lightning/pull/17679)) +- DataLoader re-instantiation is now only performed when a distributed sampler is required ([#18191](https://github.com/Lightning-AI/pytorch-lightning/pull/18191)) +- Improved the formatting of emitted warnings ([#18288](https://github.com/Lightning-AI/pytorch-lightning/pull/18288)) +- Broadcast and reduction of tensors with XLA-based strategies now preserve the input's device ([#18275](https://github.com/Lightning-AI/pytorch-lightning/pull/18275)) +- Due to lack of reliability, Fabric now only runs on one GPU instead of all GPUs in a Jupyter notebook if `devices="auto"` (default) ([#18291](https://github.com/Lightning-AI/pytorch-lightning/pull/18291)) +- Enabled launching via `torchrun` in a SLURM environment; the `TorchElasticEnvironment` now gets chosen over the `SLURMEnvironment` if both are detected ([#18618](https://github.com/Lightning-AI/pytorch-lightning/pull/18618)) +- If not set by the user, Lightning will set `OMP_NUM_THREADS` to `num_cpus / num_processes` when launching subprocesses (e.g. when DDP is used) to avoid system overload for CPU-intensive tasks ([#18677](https://github.com/Lightning-AI/pytorch-lightning/pull/18677)) + +### Deprecated + +- Deprecated the `DDPStrategy.is_distributed` property. This strategy is distributed by definition ([#17381](https://github.com/Lightning-AI/pytorch-lightning/pull/17381)) +- Deprecated the `SingleTPUStrategy` (`strategy="single_tpu"`) in favor of `SingleDeviceXLAStrategy` (`strategy="single_xla"`) ([#17383](https://github.com/Lightning-AI/pytorch-lightning/pull/17383)) +- Deprecated the `TPUAccelerator` in favor of `XLAAccelerator` ([#17383](https://github.com/Lightning-AI/pytorch-lightning/pull/17383)) +- Deprecated the `TPUPrecision` in favor of `XLAPrecision` ([#17383](https://github.com/Lightning-AI/pytorch-lightning/pull/17383)) +- Deprecated the `TPUBf16Precision` in favor of `XLABf16Precision` ([#17383](https://github.com/Lightning-AI/pytorch-lightning/pull/17383)) + +### Removed + +- Removed automatic sharding support with `Fabric.run` or using `fabric.launch(fn)`. This only impacts FSDP and DeepSpeed strategy users. Please instantiate your module under the newly added `fabric.init_module` context manager ([#17832](https://github.com/Lightning-AI/pytorch-lightning/pull/17832)) +- Removed the unsupported `checkpoint_io` argument from the `FSDPStrategy` ([#18192](https://github.com/Lightning-AI/pytorch-lightning/pull/18192)) + +### Fixed + +- Fixed issue where running on TPUs would select the wrong device index ([#17227](https://github.com/Lightning-AI/pytorch-lightning/pull/17227)) +- Removed the need to call `.launch()` when using the DP-strategy (`strategy="dp"`) ([#17931](https://github.com/Lightning-AI/pytorch-lightning/pull/17931)) +- Fixed FSDP re-applying activation checkpointing when the user had manually applied it already ([#18006](https://github.com/Lightning-AI/pytorch-lightning/pull/18006)) +- Fixed FSDP re-wrapping the module root when the user had manually wrapped the model ([#18054](https://github.com/Lightning-AI/pytorch-lightning/pull/18054)) +- Fixed issue where unexpected exceptions would leave the default torch dtype modified when using true precision settings ([#18500](https://github.com/Lightning-AI/pytorch-lightning/pull/18500)) +- Fixed redundant input-type casting in FSDP precision ([#18630](https://github.com/Lightning-AI/pytorch-lightning/pull/18630)) +- Fixed an issue with `find_usable_cuda_devices(0)` incorrectly returning a list of devices ([#18722](https://github.com/Lightning-AI/pytorch-lightning/pull/18722)) +- Fixed redundant file writes in `CSVLogger` ([#18567](https://github.com/Lightning-AI/pytorch-lightning/pull/18567)) + + +## [2.0.9] - 2023-09-14 + +### Fixed + +- Fixed an issue causing the `_FabricOptimizer.state` to remain outdated after loading with `load_state_dict` ([#18488](https://github.com/Lightning-AI/pytorch-lightning/pull/18488)) + + +## [2.0.8] - 2023-08-29 + +### Changed + +- On XLA, avoid setting the global rank before processes have been launched as this will initialize the PJRT computation client in the main process ([#16966](https://github.com/Lightning-AI/pytorch-lightning/pull/16966)) + +### Fixed + +- Fixed model parameters getting shared between processes when running with `strategy="ddp_spawn"` and `accelerator="cpu"`; this has a necessary memory impact, as parameters are replicated for each process now ([#18238](https://github.com/Lightning-AI/pytorch-lightning/pull/18238)) +- Removed false positive warning when using `fabric.no_backward_sync` with XLA strategies ([#17761](https://github.com/Lightning-AI/pytorch-lightning/pull/17761)) +- Fixed issue where Fabric would not initialize the global rank, world size, and rank-zero-only rank after initialization and before launch ([#16966](https://github.com/Lightning-AI/pytorch-lightning/pull/16966)) +- Fixed FSDP full-precision `param_dtype` training (`16-mixed`, `bf16-mixed` and `32-true` configurations) to avoid FSDP assertion errors with PyTorch < 2.0 ([#18278](https://github.com/Lightning-AI/pytorch-lightning/pull/18278)) + + + +## [2.0.7] - 2023-08-14 + +### Changed + +- Disabled the auto-detection of the Kubeflow environment ([#18137](https://github.com/Lightning-AI/pytorch-lightning/pull/18137)) + +### Fixed + +- Fixed issue where DDP subprocesses that used Hydra would set hydra's working directory to current directory ([#18145](https://github.com/Lightning-AI/pytorch-lightning/pull/18145)) +- Fixed an issue that would prevent the user to set the multiprocessing start method after importing lightning ([#18177](https://github.com/Lightning-AI/pytorch-lightning/pull/18177)) +- Fixed an issue with `Fabric.all_reduce()` not performing an inplace operation for all backends consistently ([#18235](https://github.com/Lightning-AI/pytorch-lightning/pull/18235)) + + +## [2.0.6] - 2023-07-20 + +### Fixed + +- Fixed `TensorBoardLogger.log_graph` not unwrapping the `_FabricModule` ([#17844](https://github.com/Lightning-AI/pytorch-lightning/pull/17844)) + + +## [2.0.5] - 2023-07-07 + +### Added + +- Added validation against misconfigured device selection when using the DeepSpeed strategy ([#17952](https://github.com/Lightning-AI/pytorch-lightning/pull/17952)) + +### Changed + +- Avoid info message when loading 0 entry point callbacks ([#17990](https://github.com/Lightning-AI/pytorch-lightning/pull/17990)) + +### Fixed + +- Fixed the emission of a false-positive warning when calling a method on the Fabric-wrapped module that accepts no arguments ([#17875](https://github.com/Lightning-AI/pytorch-lightning/pull/17875)) +- Fixed check for FSDP's flat parameters in all parameter groups ([#17914](https://github.com/Lightning-AI/pytorch-lightning/pull/17914)) +- Fixed automatic step tracking in Fabric's CSVLogger ([#17942](https://github.com/Lightning-AI/pytorch-lightning/pull/17942)) +- Fixed an issue causing the `torch.set_float32_matmul_precision` info message to show multiple times ([#17960](https://github.com/Lightning-AI/pytorch-lightning/pull/17960)) +- Fixed loading model state when `Fabric.load()` is called after `Fabric.setup()` ([#17997](https://github.com/Lightning-AI/pytorch-lightning/pull/17997)) + + +## [2.0.4] - 2023-06-22 + +### Fixed + +- Fixed validation of parameters of `plugins.precision.MixedPrecision` ([#17687](https://github.com/Lightning-AI/pytorch-lightning/pull/17687)) +- Fixed an issue with hpu imports leading to performance degradation ([#17788](https://github.com/Lightning-AI/pytorch-lightning/pull/17788)) + + +- Fixed computing the next version folder in `CSVLogger` ([#17139](https://github.com/Lightning-AI/pytorch-lightning/pull/17139), [#17139](https://github.com/Lightning-AI/pytorch-lightning/pull/17986)) + + +## [2.0.3] - 2023-06-07 + +- Added support for `Callback` registration through entry points ([#17756](https://github.com/Lightning-AI/pytorch-lightning/pull/17756)) + +### Changed + +- Made type hints public ([#17100](https://github.com/Lightning-AI/pytorch-lightning/pull/17100)) +- Support compiling a module after it was set up by Fabric ([#17529](https://github.com/Lightning-AI/pytorch-lightning/pull/17529)) + +### Fixed + +- Fixed computing the next version folder in `CSVLogger` ([#17139](https://github.com/Lightning-AI/pytorch-lightning/pull/17139)) +- Fixed inconsistent settings for FSDP Precision ([#17670](https://github.com/Lightning-AI/pytorch-lightning/issues/17670)) + + +## [2.0.2] - 2023-04-24 + +### Changed + +- Enabled precision autocast for LightningModule step methods in Fabric ([#17439](https://github.com/Lightning-AI/pytorch-lightning/pull/17439)) + +### Fixed + +- Fixed an issue with `LightningModule.*_step` methods bypassing the DDP/FSDP wrapper ([#17424](https://github.com/Lightning-AI/pytorch-lightning/pull/17424)) +- Fixed device handling in `Fabric.setup()` when the model has no parameters ([#17441](https://github.com/Lightning-AI/pytorch-lightning/pull/17441)) + + +## [2.0.1] - 2023-03-30 + +### Changed + +- Generalized `Optimizer` validation to accommodate both FSDP 1.x and 2.x ([#16733](https://github.com/Lightning-AI/pytorch-lightning/pull/16733)) + + +## [2.0.0] - 2023-03-15 + +### Added + +- Added `Fabric.all_reduce` ([#16459](https://github.com/Lightning-AI/pytorch-lightning/pull/16459)) +- Added support for saving and loading DeepSpeed checkpoints through `Fabric.save/load()` ([#16452](https://github.com/Lightning-AI/pytorch-lightning/pull/16452)) +- Added support for automatically calling `set_epoch` on the `dataloader.batch_sampler.sampler` ([#16841](https://github.com/Lightning-AI/pytorch-lightning/pull/16841)) +- Added support for writing logs to remote file systems with the `CSVLogger` ([#16880](https://github.com/Lightning-AI/pytorch-lightning/pull/16880)) +- Added support for frozen dataclasses in the optimizer state ([#16656](https://github.com/Lightning-AI/pytorch-lightning/pull/16656)) +- Added `lightning_fabric.is_wrapped` to check whether a module, optimizer, or dataloader was already wrapped by Fabric ([#16953](https://github.com/Lightning-AI/pytorch-lightning/pull/16953)) + +### Changed + +- Fabric now chooses `accelerator="auto", strategy="auto", devices="auto"` as defaults ([#16842](https://github.com/Lightning-AI/pytorch-lightning/pull/16842)) +- Checkpoint saving and loading redesign ([#16434](https://github.com/Lightning-AI/pytorch-lightning/pull/16434)) + * Changed the method signatrue of `Fabric.save` and `Fabric.load` + * Changed the method signature of `Strategy.save_checkpoint` and `Fabric.load_checkpoint` + * `Fabric.save` accepts a state that can contain model and optimizer references + * `Fabric.load` can now load state in-place onto models and optimizers + * `Fabric.load` returns a dictionary of objects that weren't loaded into the state + * `Strategy.save_checkpoint` and `Fabric.load_checkpoint` are now responsible for accessing the state of the model and optimizers +- `DataParallelStrategy.get_module_state_dict()` and `DDPStrategy.get_module_state_dict()` now correctly extracts the state dict without keys prefixed with 'module' ([#16487](https://github.com/Lightning-AI/pytorch-lightning/pull/16487)) +- "Native" suffix removal ([#16490](https://github.com/Lightning-AI/pytorch-lightning/pull/16490)) + * `strategy="fsdp_full_shard_offload"` is now `strategy="fsdp_cpu_offload"` + * `lightning_fabric.plugins.precision.native_amp` is now `lightning_fabric.plugins.precision.amp` +- Enabled all shorthand strategy names that can be supported in the CLI ([#16485](https://github.com/Lightning-AI/pytorch-lightning/pull/16485)) +- Renamed `strategy='tpu_spawn'` to `strategy='xla'` and `strategy='tpu_spawn_debug'` to `strategy='xla_debug'` ([#16781](https://github.com/Lightning-AI/pytorch-lightning/pull/16781)) +- Changed arguments for precision settings (from [64|32|16|bf16] to ["64-true"|"32-true"|"16-mixed"|"bf16-mixed"]) ([#16767](https://github.com/Lightning-AI/pytorch-lightning/pull/16767)) +- The selection `Fabric(strategy="ddp_spawn", ...)` no longer falls back to "ddp" when a cluster environment gets detected ([#16780](https://github.com/Lightning-AI/pytorch-lightning/pull/16780)) +- Renamed `setup_dataloaders(replace_sampler=...)` to `setup_dataloaders(use_distributed_sampler=...)` ([#16829](https://github.com/Lightning-AI/pytorch-lightning/pull/16829)) + +### Removed + +- Removed support for PyTorch 1.10 ([#16492](https://github.com/Lightning-AI/pytorch-lightning/pull/16492)) +- Removed support for Python 3.7 ([#16579](https://github.com/Lightning-AI/pytorch-lightning/pull/16579)) + +### Fixed + +- Fixed issue where the wrapped dataloader `iter()` would be called twice ([#16841](https://github.com/Lightning-AI/pytorch-lightning/pull/16841)) + +- Improved the error message for installing tensorboard or tensorboardx ([#17053](https://github.com/Lightning-AI/pytorch-lightning/pull/17053)) + + +## [1.9.4] - 2023-03-01 + +### Added + +- Added `Fabric(strategy="auto")` support ([#16916](https://github.com/Lightning-AI/pytorch-lightning/pull/16916)) + +### Fixed + +- Fixed edge cases in parsing device ids using NVML ([#16795](https://github.com/Lightning-AI/pytorch-lightning/pull/16795)) +- Fixed DDP spawn hang on TPU Pods ([#16844](https://github.com/Lightning-AI/pytorch-lightning/pull/16844)) +- Fixed an error when passing `find_usable_cuda_devices(num_devices=-1)` ([#16866](https://github.com/Lightning-AI/pytorch-lightning/pull/16866)) + + +## [1.9.3] - 2023-02-21 + +### Fixed + +- Fixed an issue causing a wrong environment plugin to be selected when `accelerator=tpu` and `devices > 1` ([#16806](https://github.com/Lightning-AI/pytorch-lightning/pull/16806)) +- Fixed parsing of defaults for `--accelerator` and `--precision` in Fabric CLI when `accelerator` and `precision` are set to non-default values in the code ([#16818](https://github.com/Lightning-AI/pytorch-lightning/pull/16818)) + + +## [1.9.2] - 2023-02-15 + +### Fixed + +- Fixed an attribute error and improved input validation for invalid strategy types being passed to Trainer ([#16693](https://github.com/Lightning-AI/pytorch-lightning/pull/16693)) + + +## [1.9.1] - 2023-02-10 + +### Fixed + +- Fixed error handling for `accelerator="mps"` and `ddp` strategy pairing ([#16455](https://github.com/Lightning-AI/pytorch-lightning/pull/16455)) +- Fixed strict availability check for `torch_xla` requirement ([#16476](https://github.com/Lightning-AI/pytorch-lightning/pull/16476)) +- Fixed an issue where PL would wrap DataLoaders with XLA's MpDeviceLoader more than once ([#16571](https://github.com/Lightning-AI/pytorch-lightning/pull/16571)) +- Fixed the batch_sampler reference for DataLoaders wrapped with XLA's MpDeviceLoader ([#16571](https://github.com/Lightning-AI/pytorch-lightning/pull/16571)) +- Fixed an import error when `torch.distributed` is not available ([#16658](https://github.com/Lightning-AI/pytorch-lightning/pull/16658)) + + +## [1.9.0] - 2023-01-17 + +### Added + +- Added `Fabric.launch()` to programmatically launch processes (e.g. in Jupyter notebook) ([#14992](https://github.com/Lightning-AI/pytorch-lightning/pull/14992)) +- Added the option to launch Fabric scripts from the CLI, without the need to wrap the code into the `run` method ([#14992](https://github.com/Lightning-AI/pytorch-lightning/pull/14992)) +- Added `Fabric.setup_module()` and `Fabric.setup_optimizers()` to support strategies that need to set up the model before an optimizer can be created ([#15185](https://github.com/Lightning-AI/pytorch-lightning/pull/15185)) +- Added support for Fully Sharded Data Parallel (FSDP) training in Lightning Lite ([#14967](https://github.com/Lightning-AI/pytorch-lightning/pull/14967)) +- Added `lightning_fabric.accelerators.find_usable_cuda_devices` utility function ([#16147](https://github.com/Lightning-AI/pytorch-lightning/pull/16147)) +- Added basic support for LightningModules ([#16048](https://github.com/Lightning-AI/pytorch-lightning/pull/16048)) +- Added support for managing callbacks via `Fabric(callbacks=...)` and emitting events through `Fabric.call()` ([#16074](https://github.com/Lightning-AI/pytorch-lightning/pull/16074)) +- Added Logger support ([#16121](https://github.com/Lightning-AI/pytorch-lightning/pull/16121)) + * Added `Fabric(loggers=...)` to support different Logger frameworks in Fabric + * Added `Fabric.log` for logging scalars using multiple loggers + * Added `Fabric.log_dict` for logging a dictionary of multiple metrics at once + * Added `Fabric.loggers` and `Fabric.logger` attributes to access the individual logger instances + * Added support for calling `self.log` and `self.log_dict` in a LightningModule when using Fabric + * Added access to `self.logger` and `self.loggers` in a LightningModule when using Fabric +- Added `lightning_fabric.loggers.TensorBoardLogger` ([#16121](https://github.com/Lightning-AI/pytorch-lightning/pull/16121)) +- Added `lightning_fabric.loggers.CSVLogger` ([#16346](https://github.com/Lightning-AI/pytorch-lightning/pull/16346)) +- Added support for a consistent `.zero_grad(set_to_none=...)` on the wrapped optimizer regardless of which strategy is used ([#16275](https://github.com/Lightning-AI/pytorch-lightning/pull/16275)) + +### Changed + +- Renamed the class `LightningLite` to `Fabric` ([#15932](https://github.com/Lightning-AI/pytorch-lightning/pull/15932), [#15938](https://github.com/Lightning-AI/pytorch-lightning/pull/15938)) +- The `Fabric.run()` method is no longer abstract ([#14992](https://github.com/Lightning-AI/pytorch-lightning/pull/14992)) +- The `XLAStrategy` now inherits from `ParallelStrategy` instead of `DDPSpawnStrategy` ([#15838](https://github.com/Lightning-AI/pytorch-lightning/pull/15838)) +- Merged the implementation of `DDPSpawnStrategy` into `DDPStrategy` and removed `DDPSpawnStrategy` ([#14952](https://github.com/Lightning-AI/pytorch-lightning/pull/14952)) +- The dataloader wrapper returned from `.setup_dataloaders()` now calls `.set_epoch()` on the distributed sampler if one is used ([#16101](https://github.com/Lightning-AI/pytorch-lightning/pull/16101)) +- Renamed `Strategy.reduce` to `Strategy.all_reduce` in all strategies ([#16370](https://github.com/Lightning-AI/pytorch-lightning/pull/16370)) +- When using multiple devices, the strategy now defaults to "ddp" instead of "ddp_spawn" when none is set ([#16388](https://github.com/Lightning-AI/pytorch-lightning/pull/16388)) + +### Removed + +- Removed support for FairScale's sharded training (`strategy='ddp_sharded'|'ddp_sharded_spawn'`). Use Fully-Sharded Data Parallel instead (`strategy='fsdp'`) ([#16329](https://github.com/Lightning-AI/pytorch-lightning/pull/16329)) + +### Fixed + +- Restored sampling parity between PyTorch and Fabric dataloaders when using the `DistributedSampler` ([#16101](https://github.com/Lightning-AI/pytorch-lightning/pull/16101)) +- Fixes an issue where the error message wouldn't tell the user the real value that was passed through the CLI ([#16334](https://github.com/Lightning-AI/pytorch-lightning/pull/16334)) + + +## [1.8.6] - 2022-12-21 + +- minor cleaning + + +## [1.8.5] - 2022-12-15 + +- minor cleaning + + +## [1.8.4] - 2022-12-08 + +### Fixed + +- Fixed `shuffle=False` having no effect when using DDP/DistributedSampler ([#15931](https://github.com/Lightning-AI/pytorch-lightning/pull/15931)) + + +## [1.8.3] - 2022-11-22 + +### Changed + +- Temporarily removed support for Hydra multi-run ([#15737](https://github.com/Lightning-AI/pytorch-lightning/pull/15737)) + + +## [1.8.2] - 2022-11-17 + +### Fixed + +- Fixed the automatic fallback from `LightningLite(strategy="ddp_spawn", ...)` to `LightningLite(strategy="ddp", ...)` when on an LSF cluster ([#15103](https://github.com/Lightning-AI/pytorch-lightning/pull/15103)) + + +## [1.8.1] - 2022-11-10 + +### Fixed + +- Fix an issue with the SLURM `srun` detection causing permission errors ([#15485](https://github.com/Lightning-AI/pytorch-lightning/pull/15485)) +- Fixed the import of `lightning_lite` causing a warning 'Redirects are currently not supported in Windows or MacOs' ([#15610](https://github.com/Lightning-AI/pytorch-lightning/pull/15610)) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__about__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__about__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d222eed108fa5059731d9084b4d192a4d64c20a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__about__.py @@ -0,0 +1,19 @@ +import time + +__author__ = "Lightning AI et al." +__author_email__ = "developer@lightning.ai" +__license__ = "Apache-2.0" +__copyright__ = f"Copyright (c) 2022-{time.strftime('%Y')}, {__author__}." +__homepage__ = "https://github.com/Lightning-AI/lightning" +__docs_url__ = "https://lightning.ai/docs/pytorch/stable/" +__docs__ = "" + +__all__ = [ + "__author__", + "__author_email__", + "__copyright__", + "__docs__", + "__docs_url__", + "__homepage__", + "__license__", +] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed9784429f4286a2308986d669f91dd6cbf8263 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__init__.py @@ -0,0 +1,47 @@ +"""Root package info.""" + +import logging +import os +import sys + +from lightning_utilities.core.imports import package_available + +if os.path.isfile(os.path.join(os.path.dirname(__file__), "__about__.py")): + from lightning_fabric.__about__ import * # noqa: F403 +if os.path.isfile(os.path.join(os.path.dirname(__file__), "__version__.py")): + from lightning_fabric.__version__ import version as __version__ +elif package_available("lightning"): + from lightning_fabric import __version__ # noqa: F401 + +_root_logger = logging.getLogger() +_logger = logging.getLogger(__name__) +_logger.setLevel(logging.INFO) + +if not _root_logger.hasHandlers(): + _logger.addHandler(logging.StreamHandler()) + _logger.propagate = False + + +# Setting this variable will force `torch.cuda.is_available()` and `torch.cuda.device_count()` +# to use an NVML-based implementation that doesn't poison forks. +# https://github.com/pytorch/pytorch/issues/83973 +os.environ["PYTORCH_NVML_BASED_CUDA_CHECK"] = "1" + +# see https://github.com/pytorch/pytorch/issues/139990 +if sys.platform == "win32": + os.environ["USE_LIBUV"] = "0" + + +from lightning_fabric.fabric import Fabric # noqa: E402 +from lightning_fabric.utilities.seed import seed_everything # noqa: E402 +from lightning_fabric.utilities.warnings import disable_possible_user_warnings # noqa: E402 +from lightning_fabric.wrappers import is_wrapped # noqa: E402 + +# this import needs to go last as it will patch other modules +import lightning_fabric._graveyard # noqa: E402, F401 # isort: skip + +__all__ = ["Fabric", "seed_everything", "is_wrapped"] + + +if os.environ.get("POSSIBLE_USER_WARNINGS", "").lower() in ("0", "off"): + disable_possible_user_warnings() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__about__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__about__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2081780f282860f4567a7fb73e9dbb7870f52cc8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__about__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fa4b69efdd116211adc682247fa3d35eb113d8e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__setup__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__setup__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e79a35fb2db012f2db7bd49267281decc919b9e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__setup__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__version__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__version__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..377032ccd80d7fcc24866f3e7ae8a0a682216c6b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/__version__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/cli.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed2993f23663d343af4b6422186f15f38388ca51 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/cli.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/connector.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/connector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27e1299d87aa3106cb879ea86685645fb9d949a2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/connector.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/fabric.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/fabric.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57e2e35c820e87e72a01b568bb160de1913034e8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/fabric.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/wrappers.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..372fe13812c53c26b68145db9fa96946f63dc9a2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__pycache__/wrappers.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__setup__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__setup__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec358c94dd19ea35a14e90b643604ae98fefdfc2 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__setup__.py @@ -0,0 +1,118 @@ +import glob +import os +from importlib.util import module_from_spec, spec_from_file_location +from pathlib import Path +from types import ModuleType +from typing import Any + +from packaging.requirements import Requirement +from setuptools import find_packages + +_PROJECT_ROOT = "." +_SOURCE_ROOT = os.path.join(_PROJECT_ROOT, "src") +_PACKAGE_ROOT = os.path.join(_SOURCE_ROOT, "lightning_fabric") +_PATH_REQUIREMENTS = os.path.join("requirements", "fabric") +_FREEZE_REQUIREMENTS = os.environ.get("FREEZE_REQUIREMENTS", "0").lower() in ("1", "true") + + +def _load_py_module(name: str, location: str) -> ModuleType: + spec = spec_from_file_location(name, location) + assert spec, f"Failed to load module {name} from {location}" + py = module_from_spec(spec) + assert spec.loader, f"ModuleSpec.loader is None for {name} from {location}" + spec.loader.exec_module(py) + return py + + +def _load_assistant() -> ModuleType: + location = os.path.join(_PROJECT_ROOT, ".actions", "assistant.py") + return _load_py_module("assistant", location) + + +def _prepare_extras() -> dict[str, Any]: + assistant = _load_assistant() + # https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras + # Define package extras. These are only installed if you specify them. + # From remote, use like `pip install "lightning-fabric[dev, docs]"` + # From local copy of repo, use like `PACKAGE_NAME=fabric pip install ".[dev, docs]"` + common_args = {"path_dir": _PATH_REQUIREMENTS, "unfreeze": "none" if _FREEZE_REQUIREMENTS else "all"} + req_files = [Path(p) for p in glob.glob(os.path.join(_PATH_REQUIREMENTS, "*.txt"))] + extras = { + p.stem: assistant.load_requirements(file_name=p.name, **common_args) + for p in req_files + if p.name not in ("docs.txt", "base.txt") + } + for req_str in extras["strategies"]: + # Strip comments before parsing + req_str_clean = req_str.split("#")[0].strip() + if not req_str_clean: # Skip empty lines + continue + req = Requirement(req_str_clean) + extras[req.name.lower().replace("-", "_")] = [req_str] + extras["all"] = extras["extra"] + extras["strategies"] + extras["examples"] + extras["dev"] = extras["all"] + extras["test"] + return extras + + +def _setup_args() -> dict[str, Any]: + assistant = _load_assistant() + about = _load_py_module("about", os.path.join(_PACKAGE_ROOT, "__about__.py")) + version = _load_py_module("version", os.path.join(_PACKAGE_ROOT, "__version__.py")) + long_description = assistant.load_readme_description( + _PACKAGE_ROOT, homepage=about.__homepage__, version=version.version + ) + + return { + "name": "lightning-fabric", + "version": version.version, + "description": about.__docs__, + "author": about.__author__, + "author_email": about.__author_email__, + "url": about.__homepage__, + "download_url": "https://github.com/Lightning-AI/lightning", + "license": about.__license__, + "packages": find_packages(where="src", include=["lightning_fabric", "lightning_fabric.*"]), + "package_dir": {"": "src"}, + "long_description": long_description, + "long_description_content_type": "text/markdown", + "include_package_data": True, + "zip_safe": False, + "keywords": ["deep learning", "pytorch", "AI"], + "python_requires": ">=3.10", + "setup_requires": ["wheel"], + "install_requires": assistant.load_requirements( + _PATH_REQUIREMENTS, unfreeze="none" if _FREEZE_REQUIREMENTS else "all" + ), + "entry_points": { + "console_scripts": [ + "fabric = lightning_fabric.cli:_main", + ], + }, + "extras_require": _prepare_extras(), + "project_urls": { + "Bug Tracker": "https://github.com/Lightning-AI/pytorch-lightning/issues", + "Documentation": "https://pytorch-lightning.rtfd.io/en/latest/", + "Source Code": "https://github.com/Lightning-AI/lightning", + }, + "classifiers": [ + "Environment :: Console", + "Natural Language :: English", + # How mature is this project? Common values are + # 3 - Alpha, 4 - Beta, 5 - Production/Stable + "Development Status :: 4 - Beta", + # Indicate who your project is intended for + "Intended Audience :: Developers", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "Topic :: Scientific/Engineering :: Information Analysis", + # Pick your license as you wish + # 'License :: OSI Approved :: BSD License', + "Operating System :: OS Independent", + # Specify the Python versions you support here. In particular, ensure + # that you indicate whether you support Python 2, Python 3 or both. + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + ], + } diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__version__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..862b5f95d88457732e2c19500c6aa71f9141df02 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/__version__.py @@ -0,0 +1,9 @@ +import os + +_PACKAGE_ROOT = os.path.dirname(__file__) +_VERSION_PATH = os.path.join(os.path.dirname(_PACKAGE_ROOT), "version.info") +if not os.path.exists(_VERSION_PATH): + # relevant for `bdist_wheel` + _VERSION_PATH = os.path.join(_PACKAGE_ROOT, "version.info") +with open(_VERSION_PATH, encoding="utf-8") as fopen: + version = fopen.readlines()[0].strip() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff1011e32f89eeebf27adbb3bae4a39b98333029 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/__init__.py @@ -0,0 +1,14 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import lightning_fabric._graveyard.tpu # noqa: F401 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51c9b4744186fbc22195830cd4016628a950f8d8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/__pycache__/tpu.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/__pycache__/tpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..132e2ebe6c6ee55a3df3be5e6c445fe674ea5d5e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/__pycache__/tpu.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/tpu.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/tpu.py new file mode 100644 index 0000000000000000000000000000000000000000..7d92a88218d375ba83e0f3ebf9d0a3fda2d83728 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/_graveyard/tpu.py @@ -0,0 +1,121 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import sys +from typing import Any + +import lightning_fabric as fabric +from lightning_fabric.accelerators import XLAAccelerator +from lightning_fabric.plugins.precision import XLAPrecision +from lightning_fabric.strategies import _StrategyRegistry +from lightning_fabric.strategies.single_xla import SingleDeviceXLAStrategy +from lightning_fabric.utilities.rank_zero import rank_zero_deprecation + + +def _patch_sys_modules() -> None: + self = sys.modules[__name__] + sys.modules["lightning_fabric.strategies.single_tpu"] = self + sys.modules["lightning_fabric.accelerators.tpu"] = self + sys.modules["lightning_fabric.plugins.precision.tpu"] = self + sys.modules["lightning_fabric.plugins.precision.tpu_bf16"] = self + sys.modules["lightning_fabric.plugins.precision.xlabf16"] = self + + +class SingleTPUStrategy(SingleDeviceXLAStrategy): + """Legacy class. + + Use :class:`~lightning_fabric.strategies.single_xla.SingleDeviceXLAStrategy` instead. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + rank_zero_deprecation("The 'single_tpu' strategy is deprecated. Use 'single_xla' instead.") + super().__init__(*args, **kwargs) + + @classmethod + def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: + if "single_tpu" not in strategy_registry: + strategy_registry.register("single_tpu", cls, description="Legacy class. Use `single_xla` instead.") + + +class TPUAccelerator(XLAAccelerator): + """Legacy class. + + Use :class:`~lightning_fabric.accelerators.xla.XLAAccelerator` instead. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + rank_zero_deprecation( + "The `TPUAccelerator` class is deprecated. Use `lightning_fabric.accelerators.XLAAccelerator` instead." + ) + super().__init__(*args, **kwargs) + + +class TPUPrecision(XLAPrecision): + """Legacy class. + + Use :class:`~lightning_fabric.plugins.precision.xla.XLAPrecision` instead. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + rank_zero_deprecation( + "The `TPUPrecision` class is deprecated. Use `lightning_fabric.plugins.precision.XLAPrecision` instead." + ) + super().__init__(precision="32-true") + + +class XLABf16Precision(XLAPrecision): + """Legacy class. + + Use :class:`~lightning_fabric.plugins.precision.xla.XLAPrecision` instead. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + rank_zero_deprecation( + "The `XLABf16Precision` class is deprecated. Use `lightning_fabric.plugins.precision.XLAPrecision` instead." + ) + super().__init__(precision="bf16-true") + + +class TPUBf16Precision(XLABf16Precision): + """Legacy class. + + Use :class:`~lightning_fabric.plugins.precision.xla.XLAPrecision` instead. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + rank_zero_deprecation( + "The `TPUBf16Precision` class is deprecated. Use `lightning_fabric.plugins.precision.XLAPrecision` instead." + ) + super().__init__(*args, **kwargs) + + +def _patch_classes() -> None: + setattr(fabric.strategies, "SingleTPUStrategy", SingleTPUStrategy) + setattr(fabric.accelerators, "TPUAccelerator", TPUAccelerator) + setattr(fabric.plugins, "TPUPrecision", TPUPrecision) + setattr(fabric.plugins.precision, "TPUPrecision", TPUPrecision) + setattr(fabric.plugins, "TPUBf16Precision", TPUBf16Precision) + setattr(fabric.plugins.precision, "TPUBf16Precision", TPUBf16Precision) + setattr(fabric.plugins, "XLABf16Precision", XLABf16Precision) + setattr(fabric.plugins.precision, "XLABf16Precision", XLABf16Precision) + + +_patch_sys_modules() +_patch_classes() + +SingleTPUStrategy.register_strategies(fabric.strategies.STRATEGY_REGISTRY) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ccb577fcc5427f90b1c553a33bcc9b003033c130 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__init__.py @@ -0,0 +1,24 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import sys + +from lightning_fabric.accelerators.accelerator import Accelerator +from lightning_fabric.accelerators.cpu import CPUAccelerator # noqa: F401 +from lightning_fabric.accelerators.cuda import CUDAAccelerator, find_usable_cuda_devices # noqa: F401 +from lightning_fabric.accelerators.mps import MPSAccelerator # noqa: F401 +from lightning_fabric.accelerators.registry import _AcceleratorRegistry +from lightning_fabric.accelerators.xla import XLAAccelerator # noqa: F401 +from lightning_fabric.utilities.registry import _register_classes + +ACCELERATOR_REGISTRY = _AcceleratorRegistry() +_register_classes(ACCELERATOR_REGISTRY, "register_accelerators", sys.modules[__name__], Accelerator) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4defb89413045a12efb1c6dfc00005559fce15e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/accelerator.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/accelerator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d49d83e1dec975a4d4ace53a270b683a57ff7e6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/accelerator.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/cpu.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/cpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a43d628e99ab9424a3600a2186490d80aa05b3d0 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/cpu.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/cuda.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/cuda.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0da6a1834a2f9d1aa0f04eba13b238e31ad27a0a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/cuda.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/mps.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/mps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49faf8821b5be37e8826695609d167119fd22777 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/mps.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/registry.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c6dbb57cc29403307af523480da526f5f1c476c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/registry.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/xla.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/xla.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59205e007365feb4f20dda8d80ce3d9fa12cbeff Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/__pycache__/xla.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/accelerator.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/accelerator.py new file mode 100644 index 0000000000000000000000000000000000000000..cbecd32e328e9aaa604a43972df1cf880532d3ab --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/accelerator.py @@ -0,0 +1,67 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from abc import ABC, abstractmethod +from typing import Any + +import torch + +from lightning_fabric.accelerators.registry import _AcceleratorRegistry + + +class Accelerator(ABC): + """The Accelerator base class. + + An Accelerator is meant to deal with one type of hardware. + + .. warning:: Writing your own accelerator is an :ref:`experimental ` feature. + + """ + + @abstractmethod + def setup_device(self, device: torch.device) -> None: + """Create and prepare the device for the current process.""" + + @abstractmethod + def teardown(self) -> None: + """Clean up any state created by the accelerator.""" + + @staticmethod + @abstractmethod + def parse_devices(devices: Any) -> Any: + """Accelerator device parsing logic.""" + + @staticmethod + @abstractmethod + def get_parallel_devices(devices: Any) -> Any: + """Gets parallel devices for the Accelerator.""" + + @staticmethod + @abstractmethod + def auto_device_count() -> int: + """Get the device count when set to auto.""" + + @staticmethod + @abstractmethod + def is_available() -> bool: + """Detect if the hardware is available.""" + + @staticmethod + @abstractmethod + def name() -> str: + """The name of the accelerator.""" + + @classmethod + def register_accelerators(cls, accelerator_registry: _AcceleratorRegistry) -> None: + """Register the accelerator with the registry.""" + pass diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/cpu.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..12fb9d846d0d0dc5bf6ca32cb8310e9ccb752312 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/cpu.py @@ -0,0 +1,101 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Union + +import torch +from typing_extensions import override + +from lightning_fabric.accelerators.accelerator import Accelerator +from lightning_fabric.accelerators.registry import _AcceleratorRegistry + + +class CPUAccelerator(Accelerator): + """Accelerator for CPU devices.""" + + @override + def setup_device(self, device: torch.device) -> None: + """ + Raises: + ValueError: + If the selected device is not CPU. + """ + if device.type != "cpu": + raise ValueError(f"Device should be CPU, got {device} instead.") + + @override + def teardown(self) -> None: + pass + + @staticmethod + @override + def parse_devices(devices: Union[int, str]) -> int: + """Accelerator device parsing logic.""" + return _parse_cpu_cores(devices) + + @staticmethod + @override + def get_parallel_devices(devices: Union[int, str]) -> list[torch.device]: + """Gets parallel devices for the Accelerator.""" + devices = _parse_cpu_cores(devices) + return [torch.device("cpu")] * devices + + @staticmethod + @override + def auto_device_count() -> int: + """Get the devices when set to auto.""" + return 1 + + @staticmethod + @override + def is_available() -> bool: + """CPU is always available for execution.""" + return True + + @staticmethod + @override + def name() -> str: + return "cpu" + + @classmethod + @override + def register_accelerators(cls, accelerator_registry: _AcceleratorRegistry) -> None: + accelerator_registry.register( + cls.name(), + cls, + description=cls.__name__, + ) + + +def _parse_cpu_cores(cpu_cores: Union[int, str]) -> int: + """Parses the cpu_cores given in the format as accepted by the ``devices`` argument in the + :class:`~pytorch_lightning.trainer.trainer.Trainer`. + + Args: + cpu_cores: An int > 0 or a string that can be converted to an int > 0. + + Returns: + An int representing the number of processes + + Raises: + MisconfigurationException: + If cpu_cores is not an int > 0 + + """ + if isinstance(cpu_cores, str) and cpu_cores.strip().isdigit(): + cpu_cores = int(cpu_cores) + + if not isinstance(cpu_cores, int) or cpu_cores <= 0: + raise TypeError("`devices` selected with `CPUAccelerator` should be an int > 0.") + + return cpu_cores diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/cuda.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..eb667388deb2dbb880714cde7fa91c36980e69fe --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/cuda.py @@ -0,0 +1,186 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from functools import lru_cache +from typing import Optional, Union + +import torch +from typing_extensions import override + +from lightning_fabric.accelerators.accelerator import Accelerator +from lightning_fabric.accelerators.registry import _AcceleratorRegistry +from lightning_fabric.utilities.rank_zero import rank_zero_info + + +class CUDAAccelerator(Accelerator): + """Accelerator for NVIDIA CUDA devices.""" + + @override + def setup_device(self, device: torch.device) -> None: + """ + Raises: + ValueError: + If the selected device is not of type CUDA. + """ + if device.type != "cuda": + raise ValueError(f"Device should be CUDA, got {device} instead.") + _check_cuda_matmul_precision(device) + torch.cuda.set_device(device) + + @override + def teardown(self) -> None: + _clear_cuda_memory() + + @staticmethod + @override + def parse_devices(devices: Union[int, str, list[int]]) -> Optional[list[int]]: + """Accelerator device parsing logic.""" + from lightning_fabric.utilities.device_parser import _parse_gpu_ids + + return _parse_gpu_ids(devices, include_cuda=True) + + @staticmethod + @override + def get_parallel_devices(devices: list[int]) -> list[torch.device]: + """Gets parallel devices for the Accelerator.""" + return [torch.device("cuda", i) for i in devices] + + @staticmethod + @override + def auto_device_count() -> int: + """Get the devices when set to auto.""" + return num_cuda_devices() + + @staticmethod + @override + def is_available() -> bool: + return num_cuda_devices() > 0 + + @staticmethod + @override + def name() -> str: + return "cuda" + + @classmethod + @override + def register_accelerators(cls, accelerator_registry: _AcceleratorRegistry) -> None: + accelerator_registry.register( + cls.name(), + cls, + description=cls.__name__, + ) + + +def find_usable_cuda_devices(num_devices: int = -1) -> list[int]: + """Returns a list of all available and usable CUDA GPU devices. + + A GPU is considered usable if we can successfully move a tensor to the device, and this is what this function + tests for each GPU on the system until the target number of usable devices is found. + + A subset of GPUs on the system might be used by other processes, and if the GPU is configured to operate in + 'exclusive' mode (configurable by the admin), then only one process is allowed to occupy it. + + Args: + num_devices: The number of devices you want to request. By default, this function will return as many as there + are usable CUDA GPU devices available. + + Warning: + If multiple processes call this function at the same time, there can be race conditions in the case where + both processes determine that the device is unoccupied, leading into one of them crashing later on. + + """ + if num_devices == 0: + return [] + visible_devices = _get_all_visible_cuda_devices() + if not visible_devices: + raise ValueError( + f"You requested to find {num_devices} devices but there are no visible CUDA devices on this machine." + ) + if num_devices > len(visible_devices): + raise ValueError( + f"You requested to find {num_devices} devices but this machine only has {len(visible_devices)} GPUs." + ) + + available_devices = [] + unavailable_devices = [] + + for gpu_idx in visible_devices: + try: + torch.tensor(0, device=torch.device("cuda", gpu_idx)) + except RuntimeError: + unavailable_devices.append(gpu_idx) + continue + + available_devices.append(gpu_idx) + if len(available_devices) == num_devices: + # exit early if we found the right number of GPUs + break + + if num_devices != -1 and len(available_devices) != num_devices: + raise RuntimeError( + f"You requested to find {num_devices} devices but only {len(available_devices)} are currently available." + f" The devices {unavailable_devices} are occupied by other processes and can't be used at the moment." + ) + return available_devices + + +def _get_all_visible_cuda_devices() -> list[int]: + """Returns a list of all visible CUDA GPU devices. + + Devices masked by the environment variabale ``CUDA_VISIBLE_DEVICES`` won't be returned here. For example, assume you + have 8 physical GPUs. If ``CUDA_VISIBLE_DEVICES="1,3,6"``, then this function will return the list ``[0, 1, 2]`` + because these are the three visible GPUs after applying the mask ``CUDA_VISIBLE_DEVICES``. + + """ + return list(range(num_cuda_devices())) + + +def num_cuda_devices() -> int: + """Returns the number of available CUDA devices.""" + return torch.cuda.device_count() + + +def is_cuda_available() -> bool: + """Returns a bool indicating if CUDA is currently available.""" + # We set `PYTORCH_NVML_BASED_CUDA_CHECK=1` in lightning_fabric.__init__.py + return torch.cuda.is_available() + + +def _is_ampere_or_later(device: Optional[torch.device] = None) -> bool: + major, _ = torch.cuda.get_device_capability(device) + return major >= 8 # Ampere and later leverage tensor cores, where this setting becomes useful + + +@lru_cache(1) # show the warning only ever once +def _check_cuda_matmul_precision(device: torch.device) -> None: + if not torch.cuda.is_available() or not _is_ampere_or_later(device): + return + # check that the user hasn't changed the precision already, this works for both `allow_tf32 = True` and + # `set_float32_matmul_precision` + if torch.get_float32_matmul_precision() == "highest": # default + rank_zero_info( + f"You are using a CUDA device ({torch.cuda.get_device_name(device)!r}) that has Tensor Cores. To properly" + " utilize them, you should set `torch.set_float32_matmul_precision('medium' | 'high')` which will trade-off" + " precision for performance. For more details, read https://pytorch.org/docs/stable/generated/" + "torch.set_float32_matmul_precision.html#torch.set_float32_matmul_precision" + ) + # note: no need change `torch.backends.cudnn.allow_tf32` as it's enabled by default: + # https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices + + +def _clear_cuda_memory() -> None: + # strangely, the attribute function be undefined when torch.compile is used + if hasattr(torch._C, "_cuda_clearCublasWorkspaces"): + # https://github.com/pytorch/pytorch/issues/95668 + torch._C._cuda_clearCublasWorkspaces() + torch.cuda.empty_cache() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/mps.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/mps.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c513d27a507c1aeb9b6293b1f6cb2e45552244 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/mps.py @@ -0,0 +1,97 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import platform +from functools import lru_cache +from typing import Optional, Union + +import torch +from typing_extensions import override + +from lightning_fabric.accelerators.accelerator import Accelerator +from lightning_fabric.accelerators.registry import _AcceleratorRegistry + + +class MPSAccelerator(Accelerator): + """Accelerator for Metal Apple Silicon GPU devices. + + .. warning:: Use of this accelerator beyond import and instantiation is experimental. + + """ + + @override + def setup_device(self, device: torch.device) -> None: + """ + Raises: + ValueError: + If the selected device is not MPS. + """ + if device.type != "mps": + raise ValueError(f"Device should be MPS, got {device} instead.") + + @override + def teardown(self) -> None: + pass + + @staticmethod + @override + def parse_devices(devices: Union[int, str, list[int]]) -> Optional[list[int]]: + """Accelerator device parsing logic.""" + from lightning_fabric.utilities.device_parser import _parse_gpu_ids + + return _parse_gpu_ids(devices, include_mps=True) + + @staticmethod + @override + def get_parallel_devices(devices: Union[int, str, list[int]]) -> list[torch.device]: + """Gets parallel devices for the Accelerator.""" + parsed_devices = MPSAccelerator.parse_devices(devices) + assert parsed_devices is not None + return [torch.device("mps", i) for i in range(len(parsed_devices))] + + @staticmethod + @override + def auto_device_count() -> int: + """Get the devices when set to auto.""" + return 1 + + @staticmethod + @override + @lru_cache(1) + def is_available() -> bool: + """MPS is only available on a machine with the ARM-based Apple Silicon processors.""" + mps_disabled = os.getenv("DISABLE_MPS", "0") == "1" + return not mps_disabled and torch.backends.mps.is_available() and platform.processor() in ("arm", "arm64") + + @staticmethod + @override + def name() -> str: + return "mps" + + @classmethod + @override + def register_accelerators(cls, accelerator_registry: _AcceleratorRegistry) -> None: + accelerator_registry.register( + cls.name(), + cls, + description=cls.__name__, + ) + + +def _get_all_available_mps_gpus() -> list[int]: + """ + Returns: + A list of all available MPS GPUs + """ + return [0] if MPSAccelerator.is_available() else [] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/registry.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..4e65c429f31fca73f40c8b59d503ae0cb21f2961 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/registry.py @@ -0,0 +1,129 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Callable, Optional + +from typing_extensions import override + +from lightning_fabric.utilities.exceptions import MisconfigurationException +from lightning_fabric.utilities.registry import _register_classes + + +class _AcceleratorRegistry(dict): + """This class is a Registry that stores information about the Accelerators. + + The Accelerators are mapped to strings. These strings are names that identify + an accelerator, e.g., "gpu". It also returns Optional description and + parameters to initialize the Accelerator, which were defined during the + registration. + + The motivation for having a AcceleratorRegistry is to make it convenient + for the Users to try different accelerators by passing mapped aliases + to the accelerator flag to the Trainer. + + Example:: + + @AcceleratorRegistry.register("sota", description="Custom sota accelerator", a=1, b=True) + class SOTAAccelerator(Accelerator): + def __init__(self, a, b): + ... + + or + + AcceleratorRegistry.register("sota", SOTAAccelerator, description="Custom sota accelerator", a=1, b=True) + + """ + + def register( + self, + name: str, + accelerator: Optional[Callable] = None, + description: str = "", + override: bool = False, + **init_params: Any, + ) -> Callable: + """Registers a accelerator mapped to a name and with required metadata. + + Args: + name : the name that identifies a accelerator, e.g. "gpu" + accelerator : accelerator class + description : accelerator description + override : overrides the registered accelerator, if True + init_params: parameters to initialize the accelerator + + """ + if not (name is None or isinstance(name, str)): + raise TypeError(f"`name` must be a str, found {name}") + + if name in self and not override: + raise MisconfigurationException(f"'{name}' is already present in the registry. HINT: Use `override=True`.") + + data: dict[str, Any] = {} + + data["description"] = description + data["init_params"] = init_params + + def do_register(accelerator: Callable) -> Callable: + data["accelerator"] = accelerator + data["accelerator_name"] = name + self[name] = data + return accelerator + + if accelerator is not None: + return do_register(accelerator) + + return do_register + + @override + def get(self, name: str, default: Optional[Any] = None) -> Any: + """Calls the registered accelerator with the required parameters and returns the accelerator object. + + Args: + name (str): the name that identifies a accelerator, e.g. "gpu" + + """ + if name in self: + data = self[name] + return data["accelerator"](**data["init_params"]) + + if default is not None: + return default + + err_msg = "'{}' not found in registry. Available names: {}" + available_names = self.available_accelerators() + raise KeyError(err_msg.format(name, available_names)) + + def remove(self, name: str) -> None: + """Removes the registered accelerator by name.""" + self.pop(name) + + def available_accelerators(self) -> set[str]: + """Returns a set of registered accelerators.""" + return set(self.keys()) + + def __str__(self) -> str: + return "Registered Accelerators: {}".format(", ".join(self.available_accelerators())) + + +def call_register_accelerators(registry: _AcceleratorRegistry, base_module: str) -> None: # pragma: no-cover + """Legacy. + + Do not use. + + """ + import importlib + + module = importlib.import_module(base_module) + from lightning_fabric.accelerators.accelerator import Accelerator + + _register_classes(registry, "register_accelerators", module, Accelerator) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/xla.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/xla.py new file mode 100644 index 0000000000000000000000000000000000000000..5f632e219796d6646a5df19a8c931b70cc0ea643 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/accelerators/xla.py @@ -0,0 +1,179 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import functools +from typing import Any, Union + +import torch +from lightning_utilities.core.imports import RequirementCache +from typing_extensions import override + +from lightning_fabric.accelerators.accelerator import Accelerator +from lightning_fabric.accelerators.registry import _AcceleratorRegistry +from lightning_fabric.utilities.device_parser import _check_data_type + + +class XLAAccelerator(Accelerator): + """Accelerator for XLA devices, normally TPUs. + + .. warning:: Use of this accelerator beyond import and instantiation is experimental. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + if not _XLA_AVAILABLE: + raise ModuleNotFoundError(str(_XLA_AVAILABLE)) + if not _using_pjrt(): + raise RuntimeError("The XLA XRT runtime is not supported anymore.") + super().__init__(*args, **kwargs) + + @override + def setup_device(self, device: torch.device) -> None: + pass + + @override + def teardown(self) -> None: + pass + + @staticmethod + @override + def parse_devices(devices: Union[int, str, list[int]]) -> Union[int, list[int]]: + """Accelerator device parsing logic.""" + return _parse_tpu_devices(devices) + + @staticmethod + @override + def get_parallel_devices(devices: Union[int, list[int]]) -> list[torch.device]: + """Gets parallel devices for the Accelerator.""" + devices = _parse_tpu_devices(devices) + if isinstance(devices, int): + return [torch.device("xla", i) for i in range(devices)] + # list of devices is not supported, just a specific index, fine to access [0] + return [torch.device("xla", devices[0])] + # we cannot create `xla_device` here because processes have not been spawned yet (this is called in the + # accelerator connector init). However, there doesn't seem to be a problem with instantiating `torch.device`. + # it will be replaced with `xla_device` (also a torch.device`, but with extra logic) in the strategy + + @staticmethod + @override + # XLA's multiprocessing will pop the TPU_NUM_DEVICES key, so we need to cache it + # https://github.com/pytorch/xla/blob/v2.0.0/torch_xla/distributed/xla_multiprocessing.py#L280 + @functools.lru_cache(maxsize=1) + def auto_device_count() -> int: + """Get the devices when set to auto.""" + if not _XLA_AVAILABLE: + return 0 + if _XLA_GREATER_EQUAL_2_1: + from torch_xla._internal import tpu + + return tpu.num_available_devices() + from torch_xla.experimental import tpu + + device_count_on_version = {2: 8, 3: 8, 4: 4} + return device_count_on_version.get(tpu.version(), 8) + + @staticmethod + @override + @functools.lru_cache(maxsize=1) + def is_available() -> bool: + try: + return XLAAccelerator.auto_device_count() > 0 + except (ValueError, AssertionError, OSError): + # XLA may raise these exceptions if it's not properly configured. This needs to be avoided for the cases + # when `torch_xla` is imported but not used + return False + + @staticmethod + @override + def name() -> str: + return "tpu" + + @classmethod + @override + def register_accelerators(cls, accelerator_registry: _AcceleratorRegistry) -> None: + accelerator_registry.register( + cls.name(), + cls, + description=cls.__name__, + ) + + +# PJRT support requires this minimum version +_XLA_AVAILABLE = RequirementCache("torch_xla>=1.13", "torch_xla") +_XLA_GREATER_EQUAL_2_1 = RequirementCache("torch_xla>=2.1") +_XLA_GREATER_EQUAL_2_5 = RequirementCache("torch_xla>=2.5") + + +def _using_pjrt() -> bool: + # `using_pjrt` is removed in torch_xla 2.5 + if _XLA_GREATER_EQUAL_2_5: + from torch_xla import runtime as xr + + return xr.device_type() is not None + # delete me when torch_xla 2.2 is the min supported version, where XRT support has been dropped. + if _XLA_GREATER_EQUAL_2_1: + from torch_xla import runtime as xr + + return xr.using_pjrt() + + from torch_xla.experimental import pjrt + + return pjrt.using_pjrt() + + +def _parse_tpu_devices(devices: Union[int, str, list[int]]) -> Union[int, list[int]]: + """Parses the TPU devices given in the format as accepted by the + :class:`~pytorch_lightning.trainer.trainer.Trainer` and :class:`~lightning_fabric.Fabric`. + + Args: + devices: An int of 1 or string '1' indicates that 1 core with multi-processing should be used + An int 8 or string '8' indicates that all 8 cores with multi-processing should be used + A single element list of int or string can be used to indicate the specific TPU core to use. + + Returns: + A list of tpu cores to be used. + + """ + _check_data_type(devices) + if isinstance(devices, str): + devices = _parse_tpu_devices_str(devices) + _check_tpu_devices_valid(devices) + return devices + + +def _check_tpu_devices_valid(devices: object) -> None: + device_count = XLAAccelerator.auto_device_count() + if ( + # support number of devices + isinstance(devices, int) + and devices in {1, device_count} + # support picking a specific device + or isinstance(devices, (list, tuple)) + and len(devices) == 1 + and 0 <= devices[0] <= device_count - 1 + ): + return + raise ValueError( + f"`devices` can only be 'auto', 1, {device_count} or [<0-{device_count - 1}>] for TPUs. Got {devices!r}" + ) + + +def _parse_tpu_devices_str(devices: str) -> Union[int, list[int]]: + devices = devices.strip() + try: + return int(devices) + except ValueError: + try: + return [int(x.strip()) for x in devices.split(",") if len(x) > 0] + except ValueError: + raise ValueError(f"Could not parse the selected TPU devices: {devices!r}") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/cli.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..89254279ba6a3cf0e3391662145b3fc8f37bed2e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/cli.py @@ -0,0 +1,245 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import logging +import os +import re +from argparse import Namespace +from typing import Any, Optional + +import torch +from lightning_utilities.core.imports import RequirementCache +from typing_extensions import get_args + +from lightning_fabric.accelerators import CPUAccelerator, CUDAAccelerator, MPSAccelerator +from lightning_fabric.plugins.precision.precision import _PRECISION_INPUT_STR, _PRECISION_INPUT_STR_ALIAS +from lightning_fabric.strategies import STRATEGY_REGISTRY +from lightning_fabric.utilities.consolidate_checkpoint import _process_cli_args +from lightning_fabric.utilities.device_parser import _parse_gpu_ids, _select_auto_accelerator +from lightning_fabric.utilities.distributed import _suggested_max_num_threads +from lightning_fabric.utilities.load import _load_distributed_checkpoint + +_log = logging.getLogger(__name__) + +_CLICK_AVAILABLE = RequirementCache("click") +_LIGHTNING_SDK_AVAILABLE = RequirementCache("lightning_sdk") + +_SUPPORTED_ACCELERATORS = ("cpu", "gpu", "cuda", "mps", "tpu", "auto") + + +def _get_supported_strategies() -> list[str]: + """Returns strategy choices from the registry, with the ones removed that are incompatible to be launched from the + CLI or ones that require further configuration by the user.""" + available_strategies = STRATEGY_REGISTRY.available_strategies() + excluded = r".*(spawn|fork|notebook|xla|tpu|offload).*" + return [strategy for strategy in available_strategies if not re.match(excluded, strategy)] + + +if _CLICK_AVAILABLE: + import click + + @click.group() + def _main() -> None: + pass + + @_main.command( + "run", + context_settings={ + "ignore_unknown_options": True, + }, + ) + @click.argument( + "script", + type=click.Path(exists=True), + ) + @click.option( + "--accelerator", + type=click.Choice(_SUPPORTED_ACCELERATORS), + default=None, + help="The hardware accelerator to run on.", + ) + @click.option( + "--strategy", + type=click.Choice(_get_supported_strategies()), + default=None, + help="Strategy for how to run across multiple devices.", + ) + @click.option( + "--devices", + type=str, + default="1", + help=( + "Number of devices to run on (``int``), which devices to run on (``list`` or ``str``), or ``'auto'``." + " The value applies per node." + ), + ) + @click.option( + "--num-nodes", + "--num_nodes", + type=int, + default=1, + help="Number of machines (nodes) for distributed execution.", + ) + @click.option( + "--node-rank", + "--node_rank", + type=int, + default=0, + help=( + "The index of the machine (node) this command gets started on. Must be a number in the range" + " 0, ..., num_nodes - 1." + ), + ) + @click.option( + "--main-address", + "--main_address", + type=str, + default="127.0.0.1", + help="The hostname or IP address of the main machine (usually the one with node_rank = 0).", + ) + @click.option( + "--main-port", + "--main_port", + type=int, + default=29400, + help="The main port to connect to the main machine.", + ) + @click.option( + "--precision", + type=click.Choice(get_args(_PRECISION_INPUT_STR) + get_args(_PRECISION_INPUT_STR_ALIAS)), + default=None, + help=( + "Double precision (``64-true`` or ``64``), full precision (``32-true`` or ``32``), " + "half precision (``16-mixed`` or ``16``) or bfloat16 precision (``bf16-mixed`` or ``bf16``)" + ), + ) + @click.argument("script_args", nargs=-1, type=click.UNPROCESSED) + def _run(**kwargs: Any) -> None: + """Run a Lightning Fabric script. + + SCRIPT is the path to the Python script with the code to run. The script must contain a Fabric object. + + SCRIPT_ARGS are the remaining arguments that you can pass to the script itself and are expected to be parsed + there. + + """ + script_args = list(kwargs.pop("script_args", [])) + main(args=Namespace(**kwargs), script_args=script_args) + + @_main.command( + "consolidate", + context_settings={ + "ignore_unknown_options": True, + }, + ) + @click.argument( + "checkpoint_folder", + type=click.Path(exists=True), + ) + @click.option( + "--output_file", + type=click.Path(exists=True), + default=None, + help=( + "Path to the file where the converted checkpoint should be saved. The file should not already exist." + " If no path is provided, the file will be saved next to the input checkpoint folder with the same name" + " and a '.consolidated' suffix." + ), + ) + def _consolidate(checkpoint_folder: str, output_file: Optional[str]) -> None: + """Convert a distributed/sharded checkpoint into a single file that can be loaded with `torch.load()`. + + Only supports FSDP sharded checkpoints at the moment. + + """ + args = Namespace(checkpoint_folder=checkpoint_folder, output_file=output_file) + config = _process_cli_args(args) + checkpoint = _load_distributed_checkpoint(config.checkpoint_folder) + torch.save(checkpoint, config.output_file) + + +def _set_env_variables(args: Namespace) -> None: + """Set the environment variables for the new processes. + + The Fabric connector will parse the arguments set here. + + """ + os.environ["LT_CLI_USED"] = "1" + if args.accelerator is not None: + os.environ["LT_ACCELERATOR"] = str(args.accelerator) + if args.strategy is not None: + os.environ["LT_STRATEGY"] = str(args.strategy) + os.environ["LT_DEVICES"] = str(args.devices) + os.environ["LT_NUM_NODES"] = str(args.num_nodes) + if args.precision is not None: + os.environ["LT_PRECISION"] = str(args.precision) + + +def _get_num_processes(accelerator: str, devices: str) -> int: + """Parse the `devices` argument to determine how many processes need to be launched on the current machine.""" + + if accelerator == "auto" or accelerator is None: + accelerator = _select_auto_accelerator() + if devices == "auto": + if accelerator == "cuda" or accelerator == "mps" or accelerator == "cpu": + devices = "1" + else: + raise ValueError(f"Cannot default to '1' device for accelerator='{accelerator}'") + if accelerator == "gpu": + parsed_devices = _parse_gpu_ids(devices, include_cuda=True, include_mps=True) + elif accelerator == "cuda": + parsed_devices = CUDAAccelerator.parse_devices(devices) + elif accelerator == "mps": + parsed_devices = MPSAccelerator.parse_devices(devices) + elif accelerator == "tpu": + raise ValueError("Launching processes for TPU through the CLI is not supported.") + else: + return CPUAccelerator.parse_devices(devices) + return len(parsed_devices) if parsed_devices is not None else 0 + + +def _torchrun_launch(args: Namespace, script_args: list[str]) -> None: + """This will invoke `torchrun` programmatically to launch the given script in new processes.""" + import torch.distributed.run as torchrun + + num_processes = 1 if args.strategy == "dp" else _get_num_processes(args.accelerator, args.devices) + + torchrun_args = [ + f"--nproc_per_node={num_processes}", + f"--nnodes={args.num_nodes}", + f"--node_rank={args.node_rank}", + f"--master_addr={args.main_address}", + f"--master_port={args.main_port}", + args.script, + ] + torchrun_args.extend(script_args) + + # set a good default number of threads for OMP to avoid warnings being emitted to the user + os.environ.setdefault("OMP_NUM_THREADS", str(_suggested_max_num_threads())) + torchrun.main(torchrun_args) + + +def main(args: Namespace, script_args: Optional[list[str]] = None) -> None: + _set_env_variables(args) + _torchrun_launch(args, script_args or []) + + +if __name__ == "__main__": + if not _CLICK_AVAILABLE: # pragma: no cover + _log.error( + "To use the Lightning Fabric CLI, you must have `click` installed." + " Install it by running `pip install -U click`." + ) + raise SystemExit(1) + + _run() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/connector.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/connector.py new file mode 100644 index 0000000000000000000000000000000000000000..94d6433fc4cffd7dc3ef13755c7feb0df4ab4596 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/connector.py @@ -0,0 +1,580 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +from collections import Counter +from collections.abc import Iterable +from typing import Any, Optional, Union, cast + +import torch +from typing_extensions import get_args + +from lightning_fabric.accelerators import ACCELERATOR_REGISTRY +from lightning_fabric.accelerators.accelerator import Accelerator +from lightning_fabric.accelerators.cuda import CUDAAccelerator +from lightning_fabric.accelerators.mps import MPSAccelerator +from lightning_fabric.accelerators.xla import XLAAccelerator +from lightning_fabric.plugins import ( + BitsandbytesPrecision, + CheckpointIO, + DeepSpeedPrecision, + HalfPrecision, + MixedPrecision, + Precision, + TransformerEnginePrecision, + XLAPrecision, +) +from lightning_fabric.plugins.environments import ( + ClusterEnvironment, + LightningEnvironment, + LSFEnvironment, + MPIEnvironment, + SLURMEnvironment, + TorchElasticEnvironment, +) +from lightning_fabric.plugins.precision.double import DoublePrecision +from lightning_fabric.plugins.precision.fsdp import FSDPPrecision +from lightning_fabric.plugins.precision.precision import ( + _PRECISION_INPUT, + _PRECISION_INPUT_INT, + _PRECISION_INPUT_STR, + _PRECISION_INPUT_STR_ALIAS, + _PRECISION_INPUT_STR_ALIAS_CONVERSION, +) +from lightning_fabric.strategies import ( + STRATEGY_REGISTRY, + DeepSpeedStrategy, + ParallelStrategy, + SingleDeviceStrategy, + SingleDeviceXLAStrategy, + Strategy, + XLAFSDPStrategy, + XLAStrategy, +) +from lightning_fabric.strategies.ddp import _DDP_FORK_ALIASES +from lightning_fabric.strategies.fsdp import _FSDP_ALIASES, FSDPStrategy +from lightning_fabric.strategies.model_parallel import ModelParallelStrategy +from lightning_fabric.utilities import rank_zero_info, rank_zero_warn +from lightning_fabric.utilities.device_parser import _determine_root_gpu_device +from lightning_fabric.utilities.imports import _IS_INTERACTIVE + +_PLUGIN_INPUT = Union[Precision, ClusterEnvironment, CheckpointIO] + + +class _Connector: + """The Connector parses several Fabric arguments and instantiates the Strategy including its owned components. + + A. accelerator flag could be: + 1. accelerator class + 2. accelerator str + 3. accelerator auto + + B. strategy flag could be: + 1. strategy class + 2. strategy str registered with STRATEGY_REGISTRY + 3. strategy str in _strategy_type enum which listed in each strategy as + backend (registered these too, and _strategy_type could be deprecated) + + C. plugins flag could be: + 1. precision class (should be removed, and precision flag should allow user pass classes) + 2. checkpoint_io class + 3. cluster_environment class + + priorities which to take when: + A. Class > str + B. Strategy > Accelerator/precision/plugins + + """ + + def __init__( + self, + accelerator: Union[str, Accelerator] = "auto", + strategy: Union[str, Strategy] = "auto", + devices: Union[list[int], str, int] = "auto", + num_nodes: int = 1, + precision: Optional[_PRECISION_INPUT] = None, + plugins: Optional[Union[_PLUGIN_INPUT, Iterable[_PLUGIN_INPUT]]] = None, + ) -> None: + # These arguments can be set through environment variables set by the CLI + accelerator = self._argument_from_env("accelerator", accelerator, default="auto") + strategy = self._argument_from_env("strategy", strategy, default="auto") + devices = self._argument_from_env("devices", devices, default="auto") + num_nodes = int(self._argument_from_env("num_nodes", num_nodes, default=1)) + precision = self._argument_from_env("precision", precision, default=None) + + # 1. Parsing flags + # Get registered strategies, built-in accelerators and precision plugins + self._registered_strategies = STRATEGY_REGISTRY.available_strategies() + self._registered_accelerators = ACCELERATOR_REGISTRY.available_accelerators() + + # Raise an exception if there are conflicts between flags + # Set each valid flag to `self._x_flag` after validation + # For devices: Assign gpus, etc. to the accelerator flag and devices flag + self._strategy_flag: Union[Strategy, str] = "auto" + self._accelerator_flag: Union[Accelerator, str] = "auto" + self._precision_input: _PRECISION_INPUT_STR = "32-true" + self._precision_instance: Optional[Precision] = None + self._cluster_environment_flag: Optional[Union[ClusterEnvironment, str]] = None + self._parallel_devices: list[Union[int, torch.device, str]] = [] + self.checkpoint_io: Optional[CheckpointIO] = None + + self._check_config_and_set_final_flags( + strategy=strategy, + accelerator=accelerator, + precision=precision, + plugins=plugins, + ) + self._check_device_config_and_set_final_flags(devices=devices, num_nodes=num_nodes) + + # 2. Instantiate Accelerator + # handle `auto`, `None` and `gpu` + if self._accelerator_flag == "auto": + self._accelerator_flag = self._choose_auto_accelerator() + elif self._accelerator_flag == "gpu": + self._accelerator_flag = self._choose_gpu_accelerator_backend() + + self._set_parallel_devices_and_init_accelerator() + + # 3. Instantiate ClusterEnvironment + self.cluster_environment: ClusterEnvironment = self._choose_and_init_cluster_environment() + + # 4. Instantiate Strategy - Part 1 + if self._strategy_flag == "auto": + self._strategy_flag = self._choose_strategy() + # In specific cases, ignore user selection and fall back to a different strategy + self._check_strategy_and_fallback() + self._init_strategy() + + # 5. Instantiate Precision Plugin + self.precision = self._check_and_init_precision() + + # 6. Instantiate Strategy - Part 2 + self._lazy_init_strategy() + + def _check_config_and_set_final_flags( + self, + strategy: Union[str, Strategy], + accelerator: Union[str, Accelerator], + precision: Optional[_PRECISION_INPUT], + plugins: Optional[Union[_PLUGIN_INPUT, Iterable[_PLUGIN_INPUT]]], + ) -> None: + """This method checks: + + 1. strategy: whether the strategy name is valid, and sets the internal flags if it is. + 2. accelerator: if the value of the accelerator argument is a type of accelerator (instance or string), + set self._accelerator_flag accordingly. + 3. precision: The final value of the precision flag may be determined either by the precision argument or + by a plugin instance. + 4. plugins: The list of plugins may contain a Precision plugin, CheckpointIO, ClusterEnvironment and others. + Additionally, other flags such as `precision` can populate the list with the + corresponding plugin instances. + + """ + if plugins is not None: + plugins = [plugins] if not isinstance(plugins, Iterable) else plugins + + if isinstance(strategy, str): + strategy = strategy.lower() + + self._strategy_flag = strategy + + if strategy != "auto" and strategy not in self._registered_strategies and not isinstance(strategy, Strategy): + raise ValueError( + f"You selected an invalid strategy name: `strategy={strategy!r}`." + " It must be either a string or an instance of `lightning_fabric.strategies.Strategy`." + " Example choices: auto, ddp, ddp_spawn, deepspeed, dp, ..." + " Find a complete list of options in our documentation at https://lightning.ai" + ) + + if ( + accelerator not in self._registered_accelerators + and accelerator not in ("auto", "gpu") + and not isinstance(accelerator, Accelerator) + ): + raise ValueError( + f"You selected an invalid accelerator name: `accelerator={accelerator!r}`." + f" Available names are: auto, {', '.join(self._registered_accelerators)}." + ) + + # MPS accelerator is incompatible with DDP family of strategies. It supports single-device operation only. + is_ddp_str = isinstance(strategy, str) and "ddp" in strategy + is_dp_str = isinstance(strategy, str) and "dp" in strategy + is_deepspeed_str = isinstance(strategy, str) and "deepspeed" in strategy + is_parallel_strategy = isinstance(strategy, ParallelStrategy) or is_ddp_str or is_dp_str or is_deepspeed_str + is_mps_accelerator = MPSAccelerator.is_available() and ( + accelerator in ("mps", "auto", "gpu", None) or isinstance(accelerator, MPSAccelerator) + ) + if is_mps_accelerator and is_parallel_strategy: + raise ValueError( + f"You set `strategy={strategy}` but strategies from the DDP family are not supported on the" + f" MPS accelerator. Either explicitly set `accelerator='cpu'` or change the strategy." + ) + + self._accelerator_flag = accelerator + + precision_input = _convert_precision_to_unified_args(precision) + + if plugins: + plugins_flags_types: dict[str, int] = Counter() + for plugin in plugins: + if isinstance(plugin, Precision): + self._precision_instance = plugin + plugins_flags_types[Precision.__name__] += 1 + elif isinstance(plugin, CheckpointIO): + self.checkpoint_io = plugin + plugins_flags_types[CheckpointIO.__name__] += 1 + elif isinstance(plugin, ClusterEnvironment): + self._cluster_environment_flag = plugin + plugins_flags_types[ClusterEnvironment.__name__] += 1 + else: + raise TypeError( + f"Found invalid type for plugin {plugin}. Expected one of: Precision, " + "CheckpointIO, ClusterEnvironment." + ) + + duplicated_plugin_key = [k for k, v in plugins_flags_types.items() if v > 1] + if duplicated_plugin_key: + raise ValueError( + f"Received multiple values for {', '.join(duplicated_plugin_key)} flags in `plugins`." + " Expected one value for each type at most." + ) + + if plugins_flags_types.get(Precision.__name__) and precision_input is not None: + raise ValueError( + f"Received both `precision={precision_input}` and `plugins={self._precision_instance}`. Choose one." + ) + + self._precision_input = "32-true" if precision_input is None else precision_input + + # handle the case when the user passes in a strategy instance which has an accelerator, precision, + # checkpoint io or cluster env set up + # TODO: improve the error messages below + if isinstance(self._strategy_flag, Strategy): + if self._strategy_flag._accelerator: + if self._accelerator_flag != "auto": + raise ValueError("accelerator set through both strategy class and accelerator flag, choose one") + self._accelerator_flag = self._strategy_flag._accelerator + if self._strategy_flag._precision: + # [RFC] handle precision plugin set up conflict? + if self._precision_instance: + raise ValueError("precision set through both strategy class and plugins, choose one") + self._precision_instance = self._strategy_flag._precision + if self._strategy_flag._checkpoint_io: + if self.checkpoint_io: + raise ValueError("checkpoint_io set through both strategy class and plugins, choose one") + self.checkpoint_io = self._strategy_flag._checkpoint_io + if getattr(self._strategy_flag, "cluster_environment", None): + if self._cluster_environment_flag: + raise ValueError("cluster_environment set through both strategy class and plugins, choose one") + self._cluster_environment_flag = getattr(self._strategy_flag, "cluster_environment") + + if hasattr(self._strategy_flag, "parallel_devices") and self._strategy_flag.parallel_devices: + if self._strategy_flag.parallel_devices[0].type == "cpu": + if self._accelerator_flag and self._accelerator_flag not in ("auto", "cpu"): + raise ValueError( + f"CPU parallel_devices set through {self._strategy_flag.__class__.__name__} class," + f" but accelerator set to {self._accelerator_flag}, please choose one device type" + ) + self._accelerator_flag = "cpu" + if self._strategy_flag.parallel_devices[0].type == "cuda": + if self._accelerator_flag and self._accelerator_flag not in ("auto", "cuda", "gpu"): + raise ValueError( + f"GPU parallel_devices set through {self._strategy_flag.__class__.__name__} class," + f" but accelerator set to {self._accelerator_flag}, please choose one device type" + ) + self._accelerator_flag = "cuda" + self._parallel_devices = self._strategy_flag.parallel_devices + + def _check_device_config_and_set_final_flags(self, devices: Union[list[int], str, int], num_nodes: int) -> None: + if not isinstance(num_nodes, int) or num_nodes < 1: + raise ValueError(f"`num_nodes` must be a positive integer, but got {num_nodes}.") + + self._num_nodes_flag = num_nodes + self._devices_flag = devices + + if self._devices_flag in ([], 0, "0"): + accelerator_name = ( + self._accelerator_flag.__class__.__qualname__ + if isinstance(self._accelerator_flag, Accelerator) + else self._accelerator_flag + ) + raise ValueError( + f"`Fabric(devices={self._devices_flag!r})` value is not a valid input" + f" using {accelerator_name} accelerator." + ) + + @staticmethod + def _choose_auto_accelerator() -> str: + """Choose the accelerator type (str) based on availability when ``accelerator='auto'``.""" + if XLAAccelerator.is_available(): + return "tpu" + if MPSAccelerator.is_available(): + return "mps" + if CUDAAccelerator.is_available(): + return "cuda" + return "cpu" + + @staticmethod + def _choose_gpu_accelerator_backend() -> str: + if MPSAccelerator.is_available(): + return "mps" + if CUDAAccelerator.is_available(): + return "cuda" + raise RuntimeError("No supported gpu backend found!") + + def _set_parallel_devices_and_init_accelerator(self) -> None: + if isinstance(self._accelerator_flag, Accelerator): + self.accelerator: Accelerator = self._accelerator_flag + else: + assert self._accelerator_flag is not None + self.accelerator = ACCELERATOR_REGISTRY.get(self._accelerator_flag) + accelerator_cls = self.accelerator.__class__ + + if not accelerator_cls.is_available(): + available_accelerator = [ + acc_str + for acc_str in self._registered_accelerators + if ACCELERATOR_REGISTRY[acc_str]["accelerator"].is_available() + ] + raise RuntimeError( + f"`{accelerator_cls.__qualname__}` can not run on your system" + " since the accelerator is not available. The following accelerator(s)" + " is available and can be passed into `accelerator` argument of" + f" `Fabric`: {available_accelerator}." + ) + + self._set_devices_flag_if_auto_passed() + + self._devices_flag = accelerator_cls.parse_devices(self._devices_flag) + if not self._parallel_devices: + self._parallel_devices = accelerator_cls.get_parallel_devices(self._devices_flag) + + def _set_devices_flag_if_auto_passed(self) -> None: + if self._devices_flag != "auto": + return + if ( + _IS_INTERACTIVE + and isinstance(self.accelerator, CUDAAccelerator) + and self.accelerator.auto_device_count() > 1 + ): + self._devices_flag = 1 + rank_zero_info( + f"Fabric will use only 1 of {self.accelerator.auto_device_count()} GPUs because it is running inside" + " an interactive / notebook environment. You may try to set `Fabric(devices=" + f"{self.accelerator.auto_device_count()})` but please note that multi-GPU inside interactive /" + " notebook environments is considered experimental and unstable. Your mileage may vary." + ) + else: + self._devices_flag = self.accelerator.auto_device_count() + + def _choose_and_init_cluster_environment(self) -> ClusterEnvironment: + if isinstance(self._cluster_environment_flag, ClusterEnvironment): + return self._cluster_environment_flag + for env_type in ( + # TorchElastic has the highest priority since it can also be used inside SLURM + TorchElasticEnvironment, + SLURMEnvironment, + LSFEnvironment, + MPIEnvironment, + ): + if env_type.detect(): + return env_type() + return LightningEnvironment() + + def _choose_strategy(self) -> Union[Strategy, str]: + if self._accelerator_flag == "tpu" or isinstance(self._accelerator_flag, XLAAccelerator): + if self._parallel_devices and len(self._parallel_devices) > 1: + return "xla" + # TODO: lazy initialized device, then here could be self._strategy_flag = "single_xla" + return SingleDeviceXLAStrategy(device=self._parallel_devices[0]) + if self._num_nodes_flag > 1: + return "ddp" + if len(self._parallel_devices) <= 1: + if isinstance(self._accelerator_flag, (CUDAAccelerator, MPSAccelerator)) or ( + isinstance(self._accelerator_flag, str) and self._accelerator_flag in ("cuda", "gpu", "mps") + ): + device = _determine_root_gpu_device(self._parallel_devices) + else: + device = "cpu" + # TODO: lazy initialized device, then here could be self._strategy_flag = "single_device" + return SingleDeviceStrategy(device=device) # type: ignore + if len(self._parallel_devices) > 1 and _IS_INTERACTIVE: + return "ddp_fork" + return "ddp" + + def _check_strategy_and_fallback(self) -> None: + """Checks edge cases when the strategy selection was a string input, and we need to fall back to a different + choice depending on other parameters or the environment.""" + # current fallback and check logic only apply to user pass in str config and object config + # TODO this logic should apply to both str and object config + strategy_flag = "" if isinstance(self._strategy_flag, Strategy) else self._strategy_flag + + # Change fsdp to xla_fsdp if using TPU + if strategy_flag == "fsdp" and self._accelerator_flag == "tpu": + strategy_flag = "xla_fsdp" + if strategy_flag == "dp" and self._accelerator_flag == "cpu": + rank_zero_warn(f"{strategy_flag!r} is not supported on CPUs, hence setting `strategy='ddp'`.") + strategy_flag = "ddp" + if strategy_flag in _DDP_FORK_ALIASES and "fork" not in torch.multiprocessing.get_all_start_methods(): + raise ValueError( + f"You selected `Fabric(strategy='{strategy_flag}')` but process forking is not supported on this" + f" platform. We recommend `Fabric(strategy='ddp_spawn')` instead." + ) + if ( + strategy_flag in _FSDP_ALIASES or type(self._strategy_flag) is FSDPStrategy + ) and self._accelerator_flag not in ("cuda", "gpu"): + raise ValueError( + "You selected the FSDP strategy but FSDP is only available on GPU. Set `Fabric(accelerator='gpu', ...)`" + " to continue or select a different strategy." + ) + if strategy_flag: + self._strategy_flag = strategy_flag + + def _init_strategy(self) -> None: + """Instantiate the Strategy given depending on the setting of ``_strategy_flag``.""" + # The validation of `_strategy_flag` already happened earlier on in the connector + assert isinstance(self._strategy_flag, (str, Strategy)) + if isinstance(self._strategy_flag, str): + self.strategy = STRATEGY_REGISTRY.get(self._strategy_flag) + else: + self.strategy = self._strategy_flag + + def _check_and_init_precision(self) -> Precision: + if isinstance(self._precision_instance, Precision): + if isinstance(self._precision_instance, BitsandbytesPrecision) and not isinstance( + self.accelerator, CUDAAccelerator + ): + raise RuntimeError("Bitsandbytes is only supported on CUDA GPUs.") + return self._precision_instance + if isinstance(self.strategy, (SingleDeviceXLAStrategy, XLAStrategy, XLAFSDPStrategy)): + return XLAPrecision(self._precision_input) # type: ignore + if isinstance(self.strategy, DeepSpeedStrategy): + return DeepSpeedPrecision(self._precision_input) # type: ignore + if isinstance(self.strategy, FSDPStrategy): + return FSDPPrecision(precision=self._precision_input) # type: ignore[arg-type] + mp_precision_supported = ("32-true", "bf16-mixed", "bf16-true", "16-true") + if isinstance(self.strategy, ModelParallelStrategy) and self._precision_input not in mp_precision_supported: + raise ValueError( + f"The `ModelParallelStrategy` does not support `Fabric(..., precision={self._precision_input!r})`." + f" Choose a different precision among: {', '.join(mp_precision_supported)}." + ) + if self._precision_input in ("16-true", "bf16-true"): + return HalfPrecision(self._precision_input) # type: ignore + if self._precision_input == "32-true": + return Precision() + if self._precision_input == "64-true": + return DoublePrecision() + if self._precision_input == "transformer-engine": + return TransformerEnginePrecision(weights_dtype=torch.bfloat16) + if self._precision_input == "transformer-engine-float16": + return TransformerEnginePrecision(weights_dtype=torch.float16) + + if self._precision_input == "16-mixed" and self._accelerator_flag == "cpu": + rank_zero_warn( + "You passed `Fabric(accelerator='cpu', precision='16-mixed')` but AMP with fp16 is not supported on " + "CPU. Using `precision='bf16-mixed'` instead." + ) + self._precision_input = "bf16-mixed" + + if self._precision_input in ("16-mixed", "bf16-mixed"): + rank_zero_info( + "Using 16-bit Automatic Mixed Precision (AMP)" + if self._precision_input == "16-mixed" + else "Using bfloat16 Automatic Mixed Precision (AMP)" + ) + device = self._accelerator_flag if self._accelerator_flag in ("cpu", "mps") else "cuda" + return MixedPrecision(precision=self._precision_input, device=device) # type: ignore[arg-type] + + raise RuntimeError("No precision set") + + def _lazy_init_strategy(self) -> None: + """Lazily set missing attributes on the previously instantiated strategy.""" + self.strategy.accelerator = self.accelerator + if self.precision: + self.strategy.precision = self.precision + if self.checkpoint_io: + self.strategy.checkpoint_io = self.checkpoint_io + if hasattr(self.strategy, "cluster_environment"): + if self.strategy.cluster_environment is None: + self.strategy.cluster_environment = self.cluster_environment + self.cluster_environment = self.strategy.cluster_environment + if hasattr(self.strategy, "parallel_devices"): + if self.strategy.parallel_devices: + self._parallel_devices = self.strategy.parallel_devices + else: + self.strategy.parallel_devices = self._parallel_devices + if hasattr(self.strategy, "num_nodes"): + self.strategy._num_nodes = self._num_nodes_flag + if hasattr(self.strategy, "_set_world_ranks"): + self.strategy._set_world_ranks() + self.strategy._configure_launcher() + + if _IS_INTERACTIVE and self.strategy.launcher and not self.strategy.launcher.is_interactive_compatible: + raise RuntimeError( + f"`Fabric(strategy={self._strategy_flag!r})` is not compatible with an interactive" + " environment. Run your code as a script, or choose one of the compatible strategies:" + f" `Fabric(strategy='dp'|'ddp_notebook')`." + " In case you are spawning processes yourself, make sure to include the Fabric" + " creation inside the worker function." + ) + + # TODO: should be moved to _check_strategy_and_fallback(). + # Current test check precision first, so keep this check here to meet error order + if isinstance(self.accelerator, XLAAccelerator) and not isinstance( + self.strategy, (SingleDeviceXLAStrategy, XLAStrategy, XLAFSDPStrategy) + ): + raise ValueError( + "The `XLAAccelerator` can only be used with a `SingleDeviceXLAStrategy`, `XLAStrategy`, or" + f" `XLAFSDPStrategy`. Found {self.strategy.__class__.__name__}." + ) + + @staticmethod + def _argument_from_env(name: str, current: Any, default: Any) -> Any: + env_value: Optional[str] = os.environ.get("LT_" + name.upper()) + + if env_value is None: + return current + + if env_value is not None and env_value != str(current) and str(current) != str(default) and _is_using_cli(): + raise ValueError( + f"Your code has `Fabric({name}={current!r}, ...)` but it conflicts with the value " + f"`--{name}={env_value}` set through the CLI. " + " Remove it either from the CLI or from the Lightning Fabric object." + ) + return env_value + + +def _convert_precision_to_unified_args(precision: Optional[_PRECISION_INPUT]) -> Optional[_PRECISION_INPUT_STR]: + if precision is None: + return None + + supported_precision = ( + get_args(_PRECISION_INPUT_STR) + get_args(_PRECISION_INPUT_INT) + get_args(_PRECISION_INPUT_STR_ALIAS) + ) + if precision not in supported_precision: + raise ValueError(f"Precision {repr(precision)} is invalid. Allowed precision values: {supported_precision}") + + precision = str(precision) # convert int flags to str here to enable the legacy-conversion below + + if precision in get_args(_PRECISION_INPUT_STR_ALIAS): + if str(precision)[:2] not in ("32", "64"): + rank_zero_warn( + f"`precision={precision}` is supported for historical reasons but its usage is discouraged. " + f"Please set your precision to {_PRECISION_INPUT_STR_ALIAS_CONVERSION[precision]} instead!" + ) + precision = _PRECISION_INPUT_STR_ALIAS_CONVERSION[precision] + return cast(_PRECISION_INPUT_STR, precision) + + +def _is_using_cli() -> bool: + return bool(int(os.environ.get("LT_CLI_USED", "0"))) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/fabric.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/fabric.py new file mode 100644 index 0000000000000000000000000000000000000000..c3e753ab364fe0ac1777f2dbe7f2e6a59f1b313a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/fabric.py @@ -0,0 +1,1260 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import inspect +import os +from collections.abc import Generator, Mapping, Sequence +from contextlib import AbstractContextManager, contextmanager, nullcontext +from functools import partial +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Optional, + Union, + cast, + overload, +) + +import torch +import torch.nn as nn +from lightning_utilities.core.apply_func import apply_to_collection +from lightning_utilities.core.overrides import is_overridden +from torch import Tensor +from torch.optim import Optimizer +from torch.utils.data import BatchSampler, DataLoader, DistributedSampler, RandomSampler, SequentialSampler + +import lightning_fabric +from lightning_fabric.accelerators.accelerator import Accelerator +from lightning_fabric.connector import _PLUGIN_INPUT, _PRECISION_INPUT, _Connector, _is_using_cli +from lightning_fabric.loggers import Logger +from lightning_fabric.plugins import Precision # avoid circular imports: # isort: split +from lightning_fabric.strategies import ( + DataParallelStrategy, + DeepSpeedStrategy, + FSDPStrategy, + SingleDeviceStrategy, + Strategy, + XLAStrategy, +) +from lightning_fabric.strategies.launchers import _MultiProcessingLauncher, _XLALauncher +from lightning_fabric.strategies.strategy import TBroadcast, _Sharded +from lightning_fabric.utilities import move_data_to_device +from lightning_fabric.utilities.apply_func import convert_tensors_to_scalars, convert_to_tensors +from lightning_fabric.utilities.data import ( + _auto_add_worker_init_fn, + _replace_dunder_methods, + _update_dataloader, + has_iterable_dataset, +) +from lightning_fabric.utilities.device_dtype_mixin import _update_properties +from lightning_fabric.utilities.distributed import DistributedSamplerWrapper, _InfiniteBarrier +from lightning_fabric.utilities.init import _has_meta_device_parameters_or_buffers +from lightning_fabric.utilities.rank_zero import rank_zero_deprecation, rank_zero_warn +from lightning_fabric.utilities.registry import _load_external_callbacks +from lightning_fabric.utilities.seed import seed_everything +from lightning_fabric.utilities.types import ReduceOp +from lightning_fabric.utilities.warnings import PossibleUserWarning +from lightning_fabric.wrappers import ( + _FabricDataLoader, + _FabricModule, + _FabricOptimizer, + _to_compiled, + _unwrap_compiled, + _unwrap_objects, +) + +if TYPE_CHECKING: + from torch.optim.lr_scheduler import _LRScheduler + + +def _do_nothing(*_: Any) -> None: + pass + + +class Fabric: + r"""Fabric accelerates your PyTorch training or inference code with minimal changes required. + + Key Features: + - Automatic placement of models and data onto the device. + - Automatic support for mixed and double precision (smaller memory footprint). + - Seamless switching between hardware (CPU, GPU, TPU) and distributed training strategies + (data-parallel training, sharded training, etc.). + - Automated spawning of processes, no launch utilities required. + - Multi-node support. + + Args: + accelerator: The hardware to run on. Possible choices are: + ``"cpu"``, ``"cuda"``, ``"mps"``, ``"gpu"``, ``"tpu"``, ``"auto"``. + Defaults to ``"auto"``. + strategy: Strategy for how to run across multiple devices. Possible choices are: + ``"dp"``, ``"ddp"``, ``"ddp_spawn"``, ``"deepspeed"``, ``"fsdp"``, ``"auto"``. + Defaults to ``"auto"``. + devices: Number of devices to train on (``int``), which GPUs to train on (``list`` or ``str``), or ``"auto"``. + The value applies per node. Defaults to ``"auto"``. + num_nodes: Number of GPU nodes for distributed training. Defaults to ``1``. + precision: Double precision (``"64"``), full precision (``"32"``), half precision AMP (``"16-mixed"``), + or bfloat16 precision AMP (``"bf16-mixed"``). If ``None``, defaults will be used based on the device. + plugins: One or several custom plugins as a single plugin or list of plugins. + callbacks: A single callback or a list of callbacks. A callback can contain any arbitrary methods that + can be invoked through :meth:`~lightning_fabric.fabric.Fabric.call` by the user. + loggers: A single logger or a list of loggers. See :meth:`~lightning_fabric.fabric.Fabric.log` for more + information. + + Example:: + + # Basic usage + fabric = Fabric(accelerator="gpu", devices=2) + + # Set up model and optimizer + model = MyModel() + optimizer = torch.optim.Adam(model.parameters()) + model, optimizer = fabric.setup(model, optimizer) + + # Training loop + for batch in dataloader: + optimizer.zero_grad() + loss = model(batch) + fabric.backward(loss) + optimizer.step() + + """ + + def __init__( + self, + *, + accelerator: Union[str, Accelerator] = "auto", + strategy: Union[str, Strategy] = "auto", + devices: Union[list[int], str, int] = "auto", + num_nodes: int = 1, + precision: Optional[_PRECISION_INPUT] = None, + plugins: Optional[Union[_PLUGIN_INPUT, list[_PLUGIN_INPUT]]] = None, + callbacks: Optional[Union[list[Any], Any]] = None, + loggers: Optional[Union[Logger, list[Logger]]] = None, + ) -> None: + self._connector = _Connector( + accelerator=accelerator, + strategy=strategy, + devices=devices, + num_nodes=num_nodes, + precision=precision, + plugins=plugins, + ) + self._strategy: Strategy = self._connector.strategy + self._accelerator: Accelerator = self._connector.accelerator + self._precision: Precision = self._strategy.precision + self._callbacks = self._configure_callbacks(callbacks) + loggers = loggers if loggers is not None else [] + self._loggers = loggers if isinstance(loggers, list) else [loggers] + self._models_setup: int = 0 + self._launched: bool = False + + self._prepare_run_method() + if _is_using_cli(): + # when the CLI is used to launch the script, we need to set up the environment (init processes) here so + # that the user can immediately use all functionality in strategies + self._strategy.setup_environment() + self._launched = True + + @property + def accelerator(self) -> Accelerator: + return self._accelerator + + @property + def strategy(self) -> Strategy: + return self._strategy + + @property + def device(self) -> torch.device: + """The current device this process runs on. + + Use this to create tensors directly on the device if needed. + + """ + return self._strategy.root_device + + @property + def global_rank(self) -> int: + """The global index of the current process across all devices and nodes.""" + return getattr(self._strategy, "global_rank", 0) + + @property + def local_rank(self) -> int: + """The index of the current process among the processes running on the local node.""" + return getattr(self._strategy, "local_rank", 0) + + @property + def node_rank(self) -> int: + """The index of the current node.""" + return getattr(self._strategy, "node_rank", 0) + + @property + def world_size(self) -> int: + """The total number of processes running across all devices and nodes.""" + return getattr(self._strategy, "world_size", 1) + + @property + def is_global_zero(self) -> bool: + """Whether this rank is rank zero.""" + return self._strategy.is_global_zero + + @property + def loggers(self) -> list[Logger]: + """Returns all loggers passed to Fabric.""" + return self._loggers + + @property + def logger(self) -> Logger: + """Returns the first logger in the list passed to Fabric, which is considered the main logger.""" + return self._loggers[0] + + def run(self, *args: Any, **kwargs: Any) -> Any: + """All the code inside this run method gets accelerated by Fabric. + + You can pass arbitrary arguments to this function when overriding it. + + """ + + def setup( + self, + module: nn.Module, + *optimizers: Optimizer, + scheduler: Optional["_LRScheduler"] = None, + move_to_device: bool = True, + _reapply_compile: bool = True, + ) -> Any: # no specific return because the way we want our API to look does not play well with mypy + r"""Set up a model and its optimizers for accelerated training. + + Args: + module: A :class:`torch.nn.Module` to set up. + *optimizers: The optimizer(s) to set up. Can be zero or more optimizers. + scheduler: An optional learning rate scheduler to set up. Must be provided after optimizers if used. + move_to_device: If set ``True`` (default), moves the model to the correct device. Set this to ``False`` + and alternatively use :meth:`to_device` manually. + _reapply_compile: If ``True`` (default), and the model was ``torch.compile``d before, the + corresponding :class:`~torch._dynamo.OptimizedModule` wrapper will be removed and reapplied with the + same settings after the model was set up by the strategy (e.g., after the model was wrapped by DDP, + FSDP etc.). Set it to ``False`` if compiling DDP/FSDP is causing issues. + + Returns: + If no optimizers are passed, returns the wrapped module. If optimizers are passed, returns a tuple + containing the wrapped module and optimizers, and optionally the scheduler if provided, in the same + order they were passed in. + + Note: + For certain strategies like FSDP, you may need to set up the model first using :meth:`setup_module`, + then create the optimizer, and finally set up the optimizer using :meth:`setup_optimizers`. + + Example:: + + # Basic usage + model, optimizer = fabric.setup(model, optimizer) + + # With multiple optimizers and scheduler + model, opt1, opt2, scheduler = fabric.setup(model, opt1, opt2, scheduler=scheduler) + + # Model only + model = fabric.setup(model) + + """ + self._validate_setup(module, optimizers) + module, compile_kwargs = _unwrap_compiled(module) if _reapply_compile else (module, None) + original_module = module + + module = self._precision.convert_module(module) + + if move_to_device: + module = self._move_model_to_device(model=module, optimizers=list(optimizers)) + + # Let accelerator/plugin wrap and connect the models and optimizers + if optimizers: + module, optimizers, scheduler = self._strategy.setup_module_and_optimizers( # type: ignore[assignment] + module, list(optimizers), scheduler + ) + else: + module = self._strategy.setup_module(module) + + if compile_kwargs is not None: + module = _to_compiled(module, compile_kwargs) + module = _FabricModule(module, self._strategy, original_module=original_module) + + # Update the _DeviceDtypeModuleMixin's device parameter + # NOTE: for sharded strategies or manual device placement, there's no single root device + _update_properties( + module, device=self.device if move_to_device else next(module.parameters(), torch.tensor(0)).device + ) + + optimizers = [_FabricOptimizer(optimizer, self._strategy, self._callbacks) for optimizer in optimizers] + + self._models_setup += 1 + + if hasattr(original_module, "_fabric"): # this is probably a LightningModule + original_module._fabric = self + original_module._fabric_optimizers = optimizers + if original_module not in self._callbacks: + self._callbacks.append(original_module) + + self.call("on_after_setup", fabric=self, module=module) + + if optimizers: + # join both types in a tuple for API convenience + return (module, *optimizers, scheduler) if scheduler is not None else (module, *optimizers) + return module + + def setup_module( + self, module: nn.Module, move_to_device: bool = True, _reapply_compile: bool = True + ) -> _FabricModule: + r"""Set up a model for accelerated training or inference. + + This is the same as calling ``.setup(model)`` with no optimizers. It is useful for inference or for certain + strategies like `FSDP` that require setting up the module before the optimizer can be created and set up. + See also :meth:`setup_optimizers`. + + Args: + module: A :class:`torch.nn.Module` to set up. + move_to_device: If set ``True`` (default), moves the model to the correct device. Set this to ``False`` + and alternatively use :meth:`to_device` manually. + _reapply_compile: If ``True`` (default), and the model was ``torch.compile``d before, the + corresponding :class:`~torch._dynamo.OptimizedModule` wrapper will be removed and reapplied with the + same settings after the model was set up by the strategy (e.g., after the model was wrapped by DDP, + FSDP etc.). Set it to ``False`` if compiling DDP/FSDP is causing issues. + + Returns: + The wrapped model as a :class:`~lightning_fabric.wrappers._FabricModule`. + + Example:: + + # Set up model first (useful for FSDP) + model = fabric.setup_module(model) + + # Then create and set up optimizer + optimizer = torch.optim.Adam(model.parameters()) + optimizer = fabric.setup_optimizers(optimizer) + + """ + self._validate_setup_module(module) + module, compile_kwargs = _unwrap_compiled(module) if _reapply_compile else (module, None) + original_module = module + + module = self._precision.convert_module(module) + + if move_to_device: + module = self._move_model_to_device(model=module, optimizers=[]) + + # Let strategy wrap and connect the module alone + module = self._strategy.setup_module(module) + + if compile_kwargs is not None: + module = _to_compiled(module, compile_kwargs) + module = _FabricModule(module, self._strategy, original_module=original_module) + + # Update the _DeviceDtypeModuleMixin's device parameter + # NOTE: for sharded strategies or manual device placement, there's no single root device + _update_properties( + module, device=self.device if move_to_device else next(module.parameters(), torch.tensor(0)).device + ) + + if hasattr(original_module, "_fabric"): # this is probably a LightningModule + original_module._fabric = self + if original_module not in self._callbacks: + self._callbacks.append(original_module) + + self._models_setup += 1 + return module + + def setup_optimizers(self, *optimizers: Optimizer) -> Union[_FabricOptimizer, tuple[_FabricOptimizer, ...]]: + r"""Set up one or more optimizers for accelerated training. + + Some strategies do not allow setting up model and optimizer independently. For them, you should call + ``.setup(model, optimizer, ...)`` instead to jointly set them up. + + Args: + *optimizers: One or more optimizers to set up. Must provide at least one optimizer. + + Returns: + If a single optimizer is passed, returns the wrapped optimizer. If multiple optimizers are passed, + returns a tuple of wrapped optimizers in the same order they were passed in. + + Raises: + RuntimeError: If using DeepSpeed or XLA strategies, which require joint model-optimizer setup. + + Note: + This method cannot be used with DeepSpeed or XLA strategies. Use :meth:`setup` instead for those strategies. + + Example:: + + # Single optimizer + optimizer = fabric.setup_optimizers(optimizer) + + # Multiple optimizers + opt1, opt2 = fabric.setup_optimizers(opt1, opt2) + + """ + self._validate_setup_optimizers(optimizers) + optimizers = [self._strategy.setup_optimizer(optimizer) for optimizer in optimizers] + optimizers = [ + _FabricOptimizer(optimizer=optimizer, strategy=self._strategy, callbacks=self._callbacks) + for optimizer in optimizers + ] + return optimizers[0] if len(optimizers) == 1 else tuple(optimizers) + + def setup_dataloaders( + self, *dataloaders: DataLoader, use_distributed_sampler: bool = True, move_to_device: bool = True + ) -> Union[DataLoader, list[DataLoader]]: + r"""Set up one or multiple dataloaders for accelerated training. If you need different settings for each + dataloader, call this method individually for each one. + + Args: + *dataloaders: One or more PyTorch :class:`~torch.utils.data.DataLoader` instances to set up. + use_distributed_sampler: If set ``True`` (default), automatically wraps or replaces the sampler on the + dataloader(s) for distributed training. If you have a custom sampler defined, set this argument + to ``False``. + move_to_device: If set ``True`` (default), moves the data returned by the dataloader(s) automatically to + the correct device. Set this to ``False`` and alternatively use :meth:`to_device` manually on the + returned data. + + Returns: + If a single dataloader is passed, returns the wrapped dataloader. If multiple dataloaders are passed, + returns a list of wrapped dataloaders in the same order they were passed in. + + Example:: + + # Single dataloader + train_loader = fabric.setup_dataloaders(train_loader) + + # Multiple dataloaders + train_loader, val_loader = fabric.setup_dataloaders(train_loader, val_loader) + + """ + self._validate_setup_dataloaders(dataloaders) + dataloaders = [ + self._setup_dataloader( + dataloader, use_distributed_sampler=use_distributed_sampler, move_to_device=move_to_device + ) + for dataloader in dataloaders + ] + return dataloaders[0] if len(dataloaders) == 1 else dataloaders + + def _setup_dataloader( + self, dataloader: DataLoader, use_distributed_sampler: bool = True, move_to_device: bool = True + ) -> DataLoader: + r"""Set up a single dataloader for accelerated training. + + Args: + dataloader: The dataloader to accelerate. + use_distributed_sampler: If set ``True`` (default), automatically wraps or replaces the sampler on the + dataloader for distributed training. If you have a custom sampler defined, set this argument to + ``False``. + move_to_device: If set ``True`` (default), moves the data returned by the dataloader automatically to + the correct device. Set this to ``False`` and alternatively use :meth:`to_device` manually on the + returned data. + + Returns: + The wrapped dataloader. + + """ + if use_distributed_sampler and self._requires_distributed_sampler(dataloader): + sampler = self._get_distributed_sampler(dataloader, **self._strategy.distributed_sampler_kwargs) + + # the dataloader needs to be re-instantiated because we want to update the sampler + dataloader = _update_dataloader(dataloader, sampler) + + # add worker_init_fn for correct seeding in worker processes + _auto_add_worker_init_fn(dataloader, self.global_rank) + + dataloader = self._strategy.process_dataloader(dataloader) + device = self.device if move_to_device and not isinstance(self._strategy, XLAStrategy) else None + fabric_dataloader = _FabricDataLoader(dataloader=dataloader, device=device) + fabric_dataloader = cast(DataLoader, fabric_dataloader) + return fabric_dataloader + + def backward(self, tensor: Tensor, *args: Any, model: Optional[_FabricModule] = None, **kwargs: Any) -> None: + r"""Replaces ``loss.backward()`` in your training loop. Handles precision automatically for you. + + Args: + tensor: The tensor (loss) to back-propagate gradients from. + *args: Optional positional arguments passed to the underlying backward function. + model: Optional model instance for plugins that require the model for backward(). Required when using + DeepSpeed strategy with multiple models. + **kwargs: Optional named keyword arguments passed to the underlying backward function. + + Note: + When using ``strategy="deepspeed"`` and multiple models were set up, it is required to pass in the + model as argument here. + + Example:: + + loss = criterion(output, target) + fabric.backward(loss) + + # With DeepSpeed and multiple models + fabric.backward(loss, model=model) + + """ + module = model._forward_module if model is not None else model + module, _ = _unwrap_compiled(module) + if isinstance(self._strategy, DeepSpeedStrategy): + if model is None: + if self._models_setup == 0: + raise RuntimeError("No models were set up for backward. Did you forget to call `fabric.setup()`?") + if self._models_setup > 1: + raise ValueError( + "When using multiple models + deepspeed, please provide the model used to perform" + " the optimization: `self.backward(loss, model=model)`" + ) + module = self._strategy.model + else: + # requires to attach the current `DeepSpeedEngine` for the `_FabricOptimizer.step` call. + self._strategy._deepspeed_engine = module + + lightning_fabric.wrappers._in_fabric_backward = True + try: + self._strategy.backward(tensor, module, *args, **kwargs) + finally: + lightning_fabric.wrappers._in_fabric_backward = False + + def clip_gradients( + self, + module: Union[torch.nn.Module, _FabricModule], + optimizer: Union[Optimizer, _FabricOptimizer], + clip_val: Optional[Union[float, int]] = None, + max_norm: Optional[Union[float, int]] = None, + norm_type: Union[float, int] = 2.0, + error_if_nonfinite: bool = True, + ) -> Optional[torch.Tensor]: + """Clip the gradients of the model to a given max value or max norm. + + Args: + module: The module whose parameters should be clipped. + optimizer: The optimizer referencing the parameters to be clipped. + clip_val: If passed, gradients will be clipped to this value. Cannot be used together with ``max_norm``. + max_norm: If passed, clips the gradients in such a way that the p-norm of the resulting parameters is + no larger than the given value. Cannot be used together with ``clip_val``. + norm_type: The type of norm if ``max_norm`` was passed. Can be ``'inf'`` for infinity norm. + Defaults to 2-norm. + error_if_nonfinite: An error is raised if the total norm of the gradients is NaN or infinite. + Only applies when ``max_norm`` is used. + + Returns: + The total norm of the gradients (before clipping was applied) as a scalar tensor if ``max_norm`` was + passed, otherwise ``None``. + + Raises: + ValueError: If both ``clip_val`` and ``max_norm`` are provided, or if neither is provided. + + Example:: + + # Clip by value + fabric.clip_gradients(model, optimizer, clip_val=1.0) + + # Clip by norm + total_norm = fabric.clip_gradients(model, optimizer, max_norm=1.0) + + """ + if clip_val is not None and max_norm is not None: + raise ValueError( + "Only one of `clip_val` or `max_norm` can be set as this specifies the underlying clipping algorithm!" + ) + + if clip_val is not None: + self.strategy.clip_gradients_value(_unwrap_objects(module), _unwrap_objects(optimizer), clip_val=clip_val) + return None + if max_norm is not None: + return self.strategy.clip_gradients_norm( + _unwrap_objects(module), + _unwrap_objects(optimizer), + max_norm=max_norm, + norm_type=norm_type, + error_if_nonfinite=error_if_nonfinite, + ) + raise ValueError("You have to specify either `clip_val` or `max_norm` to do gradient clipping!") + + def autocast(self) -> AbstractContextManager: + """A context manager to automatically convert operations for the chosen precision. + + Use this only if the `forward` method of your model does not cover all operations you wish to run with the + chosen precision setting. + + """ + return self._precision.forward_context() + + @overload + def to_device(self, obj: nn.Module) -> nn.Module: ... + + @overload + def to_device(self, obj: Tensor) -> Tensor: ... + + @overload + def to_device(self, obj: Any) -> Any: ... + + def to_device(self, obj: Union[nn.Module, Tensor, Any]) -> Union[nn.Module, Tensor, Any]: + r"""Move a :class:`torch.nn.Module` or a collection of tensors to the current device, if it is not already on + that device. + + Args: + obj: An object to move to the device. Can be an instance of :class:`torch.nn.Module`, a tensor, or a + (nested) collection of tensors (e.g., a dictionary). + + Returns: + A reference to the object that was moved to the new device. + + """ + if isinstance(obj, nn.Module): + self._accelerator.setup_device(self.device) + self._strategy.module_to_device(obj) + return obj + return move_data_to_device(obj, device=self.device) + + def print(self, *args: Any, **kwargs: Any) -> None: + r"""Print something only on the first process. If running on multiple machines, it will print from the first + process in each machine. + + Arguments passed to this method are forwarded to the Python built-in :func:`print` function. + + """ + if self.local_rank == 0: + print(*args, **kwargs) + + def barrier(self, name: Optional[str] = None) -> None: + """Wait for all processes to enter this call. + + Use this to synchronize all parallel processes, but only if necessary, otherwise the overhead of synchronization + will cause your program to slow down. This method needs to be called on all processes. Failing to do so will + cause your program to stall forever. + + """ + self._validate_launched() + self._strategy.barrier(name=name) + + def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast: + r"""Send a tensor from one process to all others. + + This method needs to be called on all processes. Failing to do so will cause your program to stall forever. + + Args: + obj: The object to broadcast to all other members. Any serializable object is supported, but it is + most efficient with the object being a :class:`~torch.Tensor`. + src: The (global) rank of the process that should send the data to all others. + + Return: + The transferred data, the same value on every rank. + + """ + self._validate_launched() + return self._strategy.broadcast(obj, src=src) + + def all_gather( + self, data: Union[Tensor, dict, list, tuple], group: Optional[Any] = None, sync_grads: bool = False + ) -> Union[Tensor, dict, list, tuple]: + """Gather tensors or collections of tensors from multiple processes. + + This method needs to be called on all processes and the tensors need to have the same shape across all + processes, otherwise your program will stall forever. + + Args: + data: int, float, tensor of shape (batch, ...), or a (possibly nested) collection thereof. + group: the process group to gather results from. Defaults to all processes (world). + sync_grads: flag that allows users to synchronize gradients for the ``all_gather`` operation + + Return: + A tensor of shape (world_size, batch, ...), or if the input was a collection + the output will also be a collection with tensors of this shape. For the special case where + world_size is 1, no additional dimension is added to the tensor(s). + + """ + self._validate_launched() + group = group if group is not None else torch.distributed.group.WORLD + data = convert_to_tensors(data, device=self.device) + return apply_to_collection(data, Tensor, self._strategy.all_gather, group=group, sync_grads=sync_grads) + + def all_reduce( + self, + data: Union[Tensor, dict, list, tuple], + group: Optional[Any] = None, + reduce_op: Optional[Union[ReduceOp, str]] = "mean", + ) -> Union[Tensor, dict, list, tuple]: + """Reduce tensors or collections of tensors from multiple processes. + + The reduction on tensors is applied in-place, meaning the result will be placed back into the input tensor. + This method needs to be called on all processes and the tensors need to have the same shape across all + processes, otherwise your program will stall forever. + + Args: + data: int, float, tensor of shape (batch, ...), or a (possibly nested) collection thereof. Tensor will be + modified in-place. + group: the process group to reduce results across. Defaults to all processes (world). + reduce_op: the reduction operation. Defaults to 'mean'. Can also be a string 'sum' or ReduceOp. + Some strategies may limit the choices here. + + Return: + A tensor of the same shape as the input with values reduced pointwise across processes. The same is + applied to tensors in a collection if a collection is given as input. + + """ + self._validate_launched() + group = group if group is not None else torch.distributed.group.WORLD + data = convert_to_tensors(data, device=self.device) + return apply_to_collection(data, Tensor, self._strategy.all_reduce, group=group, reduce_op=reduce_op) + + @contextmanager + def rank_zero_first(self, local: bool = False) -> Generator: + r"""The code block under this context manager gets executed first on the main process (rank 0) and only when + completed, the other processes get to run the code in parallel. + + Args: + local: Set this to ``True`` if the **local** rank should be the one going first. Useful if you are + downloading data and the filesystem isn't shared between the nodes. + + Example:: + + with fabric.rank_zero_first(): + dataset = MNIST("datasets/", download=True) + + """ + rank = self.local_rank if local else self.global_rank + with _InfiniteBarrier() as barrier: + if rank > 0: + barrier() + yield + if rank == 0: + barrier() + + def no_backward_sync(self, module: _FabricModule, enabled: bool = True) -> AbstractContextManager: + r"""Skip gradient synchronization during backward to avoid redundant communication overhead. + + Use this context manager when performing gradient accumulation to speed up training with multiple devices. + Both the model's ``.forward()`` and the ``fabric.backward()`` call need to run under this context. + + Args: + module: The module for which to control the gradient synchronization. Must be a module that was + set up with :meth:`setup` or :meth:`setup_module`. + enabled: Whether the context manager is enabled or not. ``True`` means skip the sync, ``False`` means do not + skip. + + Returns: + A context manager that controls gradient synchronization. + + Raises: + TypeError: If the module was not set up with Fabric first. + + Note: + For strategies that don't support gradient sync control, a warning is emitted and the context manager + becomes a no-op. For single-device strategies, it is always a no-op. + + Example:: + + # Accumulate gradients over 8 batches + for batch_idx, batch in enumerate(dataloader): + with fabric.no_backward_sync(model, enabled=(batch_idx % 8 != 0)): + output = model(batch) + loss = criterion(output, target) + fabric.backward(loss) + + if batch_idx % 8 == 0: + optimizer.step() + optimizer.zero_grad() + + """ + module, _ = _unwrap_compiled(module) + if not isinstance(module, _FabricModule): + raise TypeError( + "You need to set up the model first before you can call `fabric.no_backward_sync()`:" + " `model = fabric.setup(model, ...)`" + ) + if isinstance(self._strategy, (SingleDeviceStrategy, XLAStrategy)): + return nullcontext() + if self._strategy._backward_sync_control is None: + rank_zero_warn( + f"The `{self._strategy.__class__.__name__}` does not support skipping the gradient synchronization." + f" Remove `.no_backward_sync()` from your code or choose a different strategy.", + category=PossibleUserWarning, + ) + return nullcontext() + + forward_module, _ = _unwrap_compiled(module._forward_module) + return self._strategy._backward_sync_control.no_backward_sync(forward_module, enabled) + + def sharded_model(self) -> AbstractContextManager: + r"""Instantiate a model under this context manager to prepare it for model-parallel sharding. + + .. deprecated:: This context manager is deprecated in favor of :meth:`init_module`, use it instead. + + """ + rank_zero_deprecation("`Fabric.sharded_model()` is deprecated in favor of `Fabric.init_module()`.") + self._validate_launched() + if isinstance(self.strategy, _Sharded): + return self.strategy.module_sharded_context() + return nullcontext() + + def init_tensor(self) -> AbstractContextManager: + """Tensors that you instantiate under this context manager will be created on the device right away and have + the right data type depending on the precision setting in Fabric.""" + return self._strategy.tensor_init_context() + + def init_module(self, empty_init: Optional[bool] = None) -> AbstractContextManager: + """Instantiate the model and its parameters under this context manager to reduce peak memory usage. + + The parameters get created on the device and with the right data type right away without wasting memory being + allocated unnecessarily. + + Args: + empty_init: Whether to initialize the model with empty weights (uninitialized memory). + If ``None``, the strategy will decide. Some strategies may not support all options. + Set this to ``True`` if you are loading a checkpoint into a large model. + + """ + self._validate_launched() + return self._strategy.module_init_context(empty_init=empty_init) + + def save( + self, + path: Union[str, Path], + state: dict[str, Union[nn.Module, Optimizer, Any]], + filter: Optional[dict[str, Callable[[str, Any], bool]]] = None, + ) -> None: + r"""Save checkpoint contents to a file. + + How and which processes save gets determined by the `strategy`. For example, the `ddp` strategy + saves checkpoints only on process 0, while the `fsdp` strategy saves files from every rank. + This method must be called on all processes! + + Args: + path: A path to where the file(s) should be saved. + state: A dictionary with contents to be saved. If the dict contains modules or optimizers, their + state-dict will be retrieved and converted automatically. + filter: An optional dictionary containing filter callables that return a boolean indicating whether the + given item should be saved (``True``) or filtered out (``False``). Each filter key should match a + state key, where its filter will be applied to the ``state_dict`` generated. + + Raises: + TypeError: If filter is not a dictionary or contains non-callable values. + ValueError: If filter keys don't match state keys. + + Example:: + + state = {"model": model, "optimizer": optimizer, "epoch": epoch} + fabric.save("checkpoint.pth", state) + + # With filter + def param_filter(name, param): + return "bias" not in name # Save only non-bias parameters + + fabric.save("checkpoint.pth", state, filter={"model": param_filter}) + + """ + if filter is not None: + if not isinstance(filter, dict): + raise TypeError(f"Filter should be a dictionary, given {filter!r}") + if not set(filter).issubset(state): + raise ValueError( + f"The filter keys {filter.keys() - state} are not present in the state keys {set(state)}." + ) + for k, v in filter.items(): + if not callable(v): + raise TypeError(f"Expected `fabric.save(filter=...)` for key {k!r} to be a callable, given {v!r}") + self._strategy.save_checkpoint(path=path, state=_unwrap_objects(state), filter=filter) + self.barrier() + + def load( + self, + path: Union[str, Path], + state: Optional[dict[str, Union[nn.Module, Optimizer, Any]]] = None, + strict: bool = True, + *, + weights_only: Optional[bool] = None, + ) -> dict[str, Any]: + """Load a checkpoint from a file and restore the state of objects (modules, optimizers, etc.). + + How and which processes load gets determined by the `strategy`. + This method must be called on all processes! + + Args: + path: A path to where the file is located. + state: A dictionary of objects whose state will be restored in-place from the checkpoint path. + If no state is given, then the checkpoint will be returned in full. + strict: Whether to enforce that the keys in ``state`` match the keys in the checkpoint. + weights_only: Defaults to ``None``. If ``True``, restricts loading to ``state_dicts`` of plain + ``torch.Tensor`` and other primitive types. If loading a checkpoint from a trusted source that contains + an ``nn.Module``, use ``weights_only=False``. If loading checkpoint from an untrusted source, we + recommend using ``weights_only=True``. For more information, please refer to the + `PyTorch Developer Notes on Serialization Semantics `_. + + Returns: + The remaining items that were not restored into the given state dictionary. If no state dictionary is + given, the full checkpoint will be returned. + + Example:: + + # Load full checkpoint + checkpoint = fabric.load("checkpoint.pth") + + # Load into existing objects + state = {"model": model, "optimizer": optimizer} + remainder = fabric.load("checkpoint.pth", state) + epoch = remainder.get("epoch", 0) + + """ + unwrapped_state = _unwrap_objects(state) + remainder = self._strategy.load_checkpoint( + path=path, + state=unwrapped_state, + strict=strict, + weights_only=weights_only, + ) + self.barrier() + if state is not None: + # We need to unwrap objects (see above) but this creates a new dictionary. In-place updates + # (for user metadata) wouldn't show up in the original dict, so we need to copy the data back. + for k in list(unwrapped_state.keys()): + obj, _ = _unwrap_compiled(state[k]) + if isinstance(obj, (_FabricModule, _FabricOptimizer, _FabricDataLoader)): + continue + state[k] = unwrapped_state[k] + return remainder + + def load_raw( + self, + path: Union[str, Path], + obj: Union[nn.Module, Optimizer], + strict: bool = True, + *, + weights_only: Optional[bool] = None, + ) -> None: + """Load the state of a module or optimizer from a single state-dict file. + + Use this for loading a raw PyTorch model checkpoint created without Fabric. + This is conceptually equivalent to ``obj.load_state_dict(torch.load(path))``, but is agnostic to the strategy + being used. + + Args: + path: A path to where the file is located + obj: A :class:`~torch.nn.Module` or :class:`~torch.optim.Optimizer` instance. + strict: Whether to enforce that the keys in the module's state-dict match the keys in the checkpoint. + Does not apply to optimizers. + weights_only: Defaults to ``None``. If ``True``, restricts loading to ``state_dicts`` of plain + ``torch.Tensor`` and other primitive types. If loading a checkpoint from a trusted source that contains + an ``nn.Module``, use ``weights_only=False``. If loading checkpoint from an untrusted source, we + recommend using ``weights_only=True``. For more information, please refer to the + `PyTorch Developer Notes on Serialization Semantics `_. + + """ + obj = _unwrap_objects(obj) + self._strategy.load_checkpoint(path=path, state=obj, strict=strict, weights_only=weights_only) + + def launch(self, function: Callable[["Fabric"], Any] = _do_nothing, *args: Any, **kwargs: Any) -> Any: + """Launch and initialize all the processes needed for distributed execution. + + Args: + function: Optional function to launch when using a spawn/fork-based strategy, for example, when using the + XLA strategy (``accelerator="tpu"``). The function must accept at least one argument, to which + the Fabric object itself will be passed. If not provided, only process initialization will be performed. + *args: Optional positional arguments to be passed to the function. + **kwargs: Optional keyword arguments to be passed to the function. + + Returns: + Returns the output of the function that ran in worker process with rank 0. + + Raises: + RuntimeError: If called when script was launched through the CLI. + TypeError: If function is provided but not callable, or if function doesn't accept required arguments. + + Note: + The ``launch()`` method should only be used if you intend to specify accelerator, devices, and so on in + the code (programmatically). If you are launching with the Lightning CLI, ``fabric run ...``, remove + ``launch()`` from your code. + + The ``launch()`` is a no-op when called multiple times and no function is passed in. + + Example:: + + def train_function(fabric): + model, optimizer = fabric.setup(model, optimizer) + # ... training code ... + + fabric = Fabric(accelerator="tpu", devices=8) + fabric.launch(train_function) + + """ + if _is_using_cli(): + raise RuntimeError( + "This script was launched through the CLI, and processes have already been created. Calling " + " `.launch()` again is not allowed." + ) + if function is not _do_nothing: + if not callable(function): + raise TypeError( + f"`Fabric.launch(...)` needs to be a callable, but got {function}." + " HINT: do `.launch(your_fn)` instead of `.launch(your_fn())`" + ) + if not inspect.signature(function).parameters: + raise TypeError( + f"`Fabric.launch(function={function})` needs to take at least one argument. The launcher will" + " pass in the `Fabric` object so you can use it inside the function." + ) + elif isinstance(self.strategy.launcher, (_MultiProcessingLauncher, _XLALauncher)): + raise TypeError( + f"To spawn processes with the `{type(self.strategy).__name__}` strategy, `.launch()` needs to be called" + " with a function that contains the code to launch in processes." + ) + return self._wrap_and_launch(function, self, *args, **kwargs) + + def _filter_kwargs_for_callback(self, method: Callable, kwargs: dict[str, Any]) -> dict[str, Any]: + """Filter keyword arguments to only include those that match the callback method's signature. + + Args: + method: The callback method to inspect + kwargs: The keyword arguments to filter + + Returns: + A filtered dictionary of keyword arguments that match the method's signature + + """ + try: + sig = inspect.signature(method) + except (ValueError, TypeError): + # If we can't inspect the signature, pass all kwargs to maintain backward compatibility + return kwargs + + filtered_kwargs = {} + for name, param in sig.parameters.items(): + # If the method accepts **kwargs, pass all original kwargs directly + if param.kind == inspect.Parameter.VAR_KEYWORD: + return kwargs + # If the parameter exists in the incoming kwargs, add it to filtered_kwargs + if name in kwargs: + filtered_kwargs[name] = kwargs[name] + + return filtered_kwargs + + def call(self, hook_name: str, *args: Any, **kwargs: Any) -> None: + r"""Trigger the callback methods with the given name and arguments. + + Not all objects registered via ``Fabric(callbacks=...)`` must implement a method with the given name. The ones + that have a matching method name will get called. + + Args: + hook_name: The name of the callback method. + *args: Optional positional arguments that get passed down to the callback method. + **kwargs: Optional keyword arguments that get passed down to the callback method. Keyword arguments + that are not present in the callback's signature will be filtered out automatically, allowing + callbacks to have different signatures for the same hook. + + Example:: + + class MyCallback: + def on_train_epoch_end(self, results): + ... + + fabric = Fabric(callbacks=[MyCallback()]) + fabric.call("on_train_epoch_end", results={...}) + + """ + for callback in self._callbacks: + method = getattr(callback, hook_name, None) + if method is None: + continue + if not callable(method): + rank_zero_warn( + f"Skipping the callback `{type(callback).__name__}.{hook_name}` because it is not callable." + ) + continue + + filtered_kwargs = self._filter_kwargs_for_callback(method, kwargs) + method(*args, **filtered_kwargs) + + def log(self, name: str, value: Any, step: Optional[int] = None) -> None: + """Log a scalar to all loggers that were added to Fabric. + + Args: + name: The name of the metric to log. + value: The metric value to collect. If the value is a :class:`torch.Tensor`, it gets detached from the + graph automatically. + step: Optional step number. Most Logger implementations auto-increment the step value by one with every + log call. You can specify your own value here. + + """ + self.log_dict(metrics={name: value}, step=step) + + def log_dict(self, metrics: Mapping[str, Any], step: Optional[int] = None) -> None: + """Log multiple scalars at once to all loggers that were added to Fabric. + + Args: + metrics: A dictionary where the key is the name of the metric and the value the scalar to be logged. + Any :class:`torch.Tensor` in the dictionary get detached from the graph automatically. + step: Optional step number. Most Logger implementations auto-increment this value by one with every + log call. You can specify your own value here. + + """ + metrics = convert_tensors_to_scalars(metrics) + for logger in self._loggers: + logger.log_metrics(metrics=metrics, step=step) + + @staticmethod + def seed_everything(seed: Optional[int] = None, workers: Optional[bool] = None, verbose: bool = True) -> int: + r"""Helper function to seed everything without explicitly importing Lightning. + + See :func:`~lightning_fabric.utilities.seed.seed_everything` for more details. + + """ + if workers is None: + # Lightning sets `workers=False` by default to avoid breaking reproducibility, but since this is a new + # release, we can afford to do it. + workers = True + return seed_everything(seed=seed, workers=workers, verbose=verbose) + + def _wrap_and_launch(self, to_run: Callable, *args: Any, **kwargs: Any) -> Any: + self._launched = True + to_run = partial(self._wrap_with_setup, to_run) + if (launcher := self._strategy.launcher) is not None: + return launcher.launch(to_run, *args, **kwargs) + return to_run(*args, **kwargs) + + def _wrap_with_setup(self, to_run: Callable, *args: Any, **kwargs: Any) -> Any: + self._strategy.setup_environment() + with _replace_dunder_methods(DataLoader, "dataset"), _replace_dunder_methods(BatchSampler): + return to_run(*args, **kwargs) + + def _move_model_to_device(self, model: nn.Module, optimizers: list[Optimizer]) -> nn.Module: + try: + initial_name, initial_param = next(model.named_parameters()) + except StopIteration: + pass + else: + initial_device = initial_param.device + count = 0 + first_name, first_device = None, None + for name, param in model.named_parameters(): + if param.device != initial_device: + count += 1 + if first_name is None: + first_name = name + first_device = param.device + if count > 0: + rank_zero_warn( + f"The model passed to `Fabric.setup()` has {count} parameters on different devices (for example" + f" {first_name!r} on {first_device} and {initial_name!r} on {initial_device}). Since" + " `move_to_device=True`, all parameters will be moved to the new device. If this is not" + " desired, set `Fabric.setup(..., move_to_device=False)`.", + category=PossibleUserWarning, + ) + + if isinstance(self._strategy, XLAStrategy): + # When the user creates the optimizer, they reference the parameters on the CPU. + # However, when running with TPU the parameters get copied and the reference in the optimizer + # remains invalid. We need to update the references to point to the parameter tensors on the device. + params_before_move = dict(model.named_parameters()) + model = self.to_device(model) + # XLA makes a copy on the parameters, so the device is not the same before and after to_device. + params_on_device = dict(model.named_parameters()) + + mapping = {param: params_on_device[name] for name, param in params_before_move.items()} + for optimizer in optimizers: + for param_group in optimizer.param_groups: + param_group["params"] = [mapping.get(p, p) for p in param_group["params"]] + else: + model = self.to_device(model) + return model + + def _requires_distributed_sampler(self, dataloader: DataLoader) -> bool: + return ( + getattr(self.strategy, "distributed_sampler_kwargs", None) is not None + and not isinstance(dataloader.sampler, DistributedSampler) + and not has_iterable_dataset(dataloader) + ) + + @staticmethod + def _get_distributed_sampler(dataloader: DataLoader, **kwargs: Any) -> DistributedSampler: + kwargs.setdefault("shuffle", isinstance(dataloader.sampler, RandomSampler)) + kwargs.setdefault("seed", int(os.getenv("PL_GLOBAL_SEED", 0))) + if isinstance(dataloader.sampler, (RandomSampler, SequentialSampler)): + return DistributedSampler(dataloader.dataset, **kwargs) + return DistributedSamplerWrapper(dataloader.sampler, **kwargs) + + def _prepare_run_method(self) -> None: + if is_overridden("run", self, Fabric) and _is_using_cli(): + raise TypeError( + "Overriding `Fabric.run()` and launching from the CLI is not allowed. Run the script normally," + " or change your code to directly call `fabric = Fabric(...); fabric.setup(...)` etc." + ) + # wrap the run method, so we can inject setup logic or spawn processes for the user + setattr(self, "run", partial(self._wrap_and_launch, self.run)) + + def _validate_launched(self) -> None: + if not self._launched and not isinstance(self._strategy, (SingleDeviceStrategy, DataParallelStrategy)): + raise RuntimeError( + "To use Fabric with more than one device, you must call `.launch()` or use the CLI:" + " `fabric run --help`." + ) + + def _validate_setup(self, module: nn.Module, optimizers: Sequence[Optimizer]) -> None: + self._validate_launched() + if isinstance(module, _FabricModule): + raise ValueError("A model should be passed only once to the `setup` method.") + + if any(isinstance(opt, _FabricOptimizer) for opt in optimizers): + raise ValueError("An optimizer should be passed only once to the `setup` method.") + + if isinstance(self._strategy, FSDPStrategy) and any( + _has_meta_device_parameters_or_buffers(optimizer) for optimizer in optimizers + ): + raise RuntimeError( + "The optimizer has references to the model's meta-device parameters. Materializing them is" + " is currently not supported unless you to set up the model and optimizer(s) separately." + " Create and set up the model first through `model = fabric.setup_module(model)`. Then create the" + " optimizer and set it up: `optimizer = fabric.setup_optimizers(optimizer)`." + ) + + def _validate_setup_module(self, module: nn.Module) -> None: + self._validate_launched() + if isinstance(module, _FabricModule): + raise ValueError("A model should be passed only once to the `setup_module` method.") + + def _validate_setup_optimizers(self, optimizers: Sequence[Optimizer]) -> None: + self._validate_launched() + if isinstance(self._strategy, (DeepSpeedStrategy, XLAStrategy)): + raise RuntimeError( + f"The `{type(self._strategy).__name__}` requires the model and optimizer(s) to be set up jointly" + " through `.setup(model, optimizer, ...)`." + ) + + if not optimizers: + raise ValueError("`setup_optimizers` requires at least one optimizer as input.") + + if any(isinstance(opt, _FabricOptimizer) for opt in optimizers): + raise ValueError("An optimizer should be passed only once to the `setup_optimizers` method.") + + if any(_has_meta_device_parameters_or_buffers(optimizer) for optimizer in optimizers): + raise RuntimeError( + "The optimizer has references to the model's meta-device parameters. Materializing them is" + " is currently not supported. Create the optimizer after setting up the model, then call" + " `fabric.setup_optimizers(optimizer)`." + ) + + def _validate_setup_dataloaders(self, dataloaders: Sequence[DataLoader]) -> None: + self._validate_launched() + if not dataloaders: + raise ValueError("`setup_dataloaders` requires at least one dataloader as input.") + + if any(isinstance(dl, _FabricDataLoader) for dl in dataloaders): + raise ValueError("A dataloader should be passed only once to the `setup_dataloaders` method.") + + if any(not isinstance(dl, DataLoader) for dl in dataloaders): + raise TypeError("Only PyTorch DataLoader are currently supported in `setup_dataloaders`.") + + @staticmethod + def _configure_callbacks(callbacks: Optional[Union[list[Any], Any]]) -> list[Any]: + callbacks = callbacks if callbacks is not None else [] + callbacks = callbacks if isinstance(callbacks, list) else [callbacks] + callbacks.extend(_load_external_callbacks("lightning_fabric.callbacks_factory")) + return callbacks diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b7790c3aad17da625be36d34059683b1ea33a05f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__init__.py @@ -0,0 +1,15 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from lightning_fabric.loggers.csv_logs import CSVLogger # noqa: F401 +from lightning_fabric.loggers.logger import Logger # noqa: F401 +from lightning_fabric.loggers.tensorboard import TensorBoardLogger # noqa: F401 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d80a8003b78ef234511e180cab59c5fddee9a278 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/csv_logs.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/csv_logs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e740b344a27a3c6284a606f836343483729694b2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/csv_logs.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/logger.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89d03a408202c618da555f12c75314b265f22900 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/logger.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/tensorboard.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/tensorboard.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b7a8533c760cc0222aa881b53917c1ee28151f6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/__pycache__/tensorboard.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/csv_logs.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/csv_logs.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6fa1d4f37c2194e2612c6fc6f21584ee68001a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/csv_logs.py @@ -0,0 +1,273 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import csv +import logging +import os +from argparse import Namespace +from typing import Any, Optional, Union + +from torch import Tensor +from typing_extensions import override + +from lightning_fabric.loggers.logger import Logger, rank_zero_experiment +from lightning_fabric.utilities.cloud_io import _is_dir, get_filesystem +from lightning_fabric.utilities.logger import _add_prefix +from lightning_fabric.utilities.rank_zero import rank_zero_only, rank_zero_warn +from lightning_fabric.utilities.types import _PATH + +log = logging.getLogger(__name__) + + +class CSVLogger(Logger): + r"""Log to the local file system in CSV format. + + Logs are saved to ``os.path.join(root_dir, name, version)``. + + Args: + root_dir: The root directory in which all your experiments with different names and versions will be stored. + name: Experiment name. Defaults to ``'lightning_logs'``. If name is ``None``, logs + (versions) will be stored to the save dir directly. + version: Experiment version. If version is not specified the logger inspects the save + directory for existing versions, then automatically assigns the next available version. + If the version is specified, and the directory already contains a metrics file for that version, it will be + overwritten. + prefix: A string to put at the beginning of metric keys. + flush_logs_every_n_steps: How often to flush logs to disk (defaults to every 100 steps). + + Example:: + + from lightning_fabric.loggers import CSVLogger + + logger = CSVLogger("path/to/logs/root", name="my_model") + logger.log_metrics({"loss": 0.235, "acc": 0.75}) + logger.finalize("success") + + """ + + LOGGER_JOIN_CHAR = "-" + + def __init__( + self, + root_dir: _PATH, + name: Optional[str] = "lightning_logs", + version: Optional[Union[int, str]] = None, + prefix: str = "", + flush_logs_every_n_steps: int = 100, + ): + super().__init__() + root_dir = os.fspath(root_dir) + self._root_dir = root_dir + self._name = name or "" + self._version = version + self._prefix = prefix + self._fs = get_filesystem(root_dir) + self._experiment: Optional[_ExperimentWriter] = None + self._flush_logs_every_n_steps = flush_logs_every_n_steps + + @property + @override + def name(self) -> str: + """Gets the name of the experiment. + + Returns: + The name of the experiment. + + """ + return self._name + + @property + @override + def version(self) -> Union[int, str]: + """Gets the version of the experiment. + + Returns: + The version of the experiment if it is specified, else the next version. + + """ + if self._version is None: + self._version = self._get_next_version() + return self._version + + @property + @override + def root_dir(self) -> str: + """Gets the save directory where the versioned CSV experiments are saved.""" + return self._root_dir + + @property + @override + def log_dir(self) -> str: + """The log directory for this run. + + By default, it is named ``'version_${self.version}'`` but it can be overridden by passing a string value for the + constructor's version parameter instead of ``None`` or an int. + + """ + # create a pseudo standard path + version = self.version if isinstance(self.version, str) else f"version_{self.version}" + return os.path.join(self._root_dir, self.name, version) + + @property + @rank_zero_experiment + def experiment(self) -> "_ExperimentWriter": + """Actual ExperimentWriter object. To use ExperimentWriter features anywhere in your code, do the following. + + Example:: + + self.logger.experiment.some_experiment_writer_function() + + """ + if self._experiment is not None: + return self._experiment + + os.makedirs(self._root_dir, exist_ok=True) + self._experiment = _ExperimentWriter(log_dir=self.log_dir) + return self._experiment + + @override + @rank_zero_only + def log_hyperparams(self, params: Union[dict[str, Any], Namespace]) -> None: + raise NotImplementedError("The `CSVLogger` does not yet support logging hyperparameters.") + + @override + @rank_zero_only + def log_metrics( # type: ignore[override] + self, metrics: dict[str, Union[Tensor, float]], step: Optional[int] = None + ) -> None: + metrics = _add_prefix(metrics, self._prefix, self.LOGGER_JOIN_CHAR) + if step is None: + step = len(self.experiment.metrics) + self.experiment.log_metrics(metrics, step) + if (step + 1) % self._flush_logs_every_n_steps == 0: + self.save() + + @override + @rank_zero_only + def save(self) -> None: + super().save() + self.experiment.save() + + @override + @rank_zero_only + def finalize(self, status: str) -> None: + if self._experiment is None: + # When using multiprocessing, finalize() should be a no-op on the main process, as no experiment has been + # initialized there + return + self.save() + + def _get_next_version(self) -> int: + versions_root = os.path.join(self._root_dir, self.name) + + if not _is_dir(self._fs, versions_root, strict=True): + return 0 + + existing_versions = [] + for d in self._fs.listdir(versions_root): + full_path = d["name"] + name = os.path.basename(full_path) + if _is_dir(self._fs, full_path) and name.startswith("version_"): + dir_ver = name.split("_")[1] + if dir_ver.isdigit(): + existing_versions.append(int(dir_ver)) + + if len(existing_versions) == 0: + return 0 + + return max(existing_versions) + 1 + + +class _ExperimentWriter: + r"""Experiment writer for CSVLogger. + + Args: + log_dir: Directory for the experiment logs + + """ + + NAME_METRICS_FILE = "metrics.csv" + + def __init__(self, log_dir: str) -> None: + self.metrics: list[dict[str, float]] = [] + self.metrics_keys: list[str] = [] + + self._fs = get_filesystem(log_dir) + self.log_dir = log_dir + self.metrics_file_path = os.path.join(self.log_dir, self.NAME_METRICS_FILE) + + self._check_log_dir_exists() + self._fs.makedirs(self.log_dir, exist_ok=True) + + def log_metrics(self, metrics_dict: dict[str, float], step: Optional[int] = None) -> None: + """Record metrics.""" + + def _handle_value(value: Union[Tensor, Any]) -> Any: + if isinstance(value, Tensor): + return value.item() + return value + + if step is None: + step = len(self.metrics) + + metrics = {k: _handle_value(v) for k, v in metrics_dict.items()} + metrics["step"] = step + self.metrics.append(metrics) + + def save(self) -> None: + """Save recorded metrics into files.""" + if not self.metrics: + return + + new_keys = self._record_new_keys() + file_exists = self._fs.isfile(self.metrics_file_path) + + if new_keys and file_exists: + # we need to re-write the file if the keys (header) change + self._rewrite_with_new_header(self.metrics_keys) + + with self._fs.open(self.metrics_file_path, mode=("a" if file_exists else "w"), newline="") as file: + writer = csv.DictWriter(file, fieldnames=self.metrics_keys) + if not file_exists: + # only write the header if we're writing a fresh file + writer.writeheader() + writer.writerows(self.metrics) + + self.metrics = [] # reset + + def _record_new_keys(self) -> set[str]: + """Records new keys that have not been logged before.""" + current_keys = set().union(*self.metrics) + new_keys = current_keys - set(self.metrics_keys) + self.metrics_keys.extend(new_keys) + self.metrics_keys.sort() + return new_keys + + def _rewrite_with_new_header(self, fieldnames: list[str]) -> None: + with self._fs.open(self.metrics_file_path, "r", newline="") as file: + metrics = list(csv.DictReader(file)) + + with self._fs.open(self.metrics_file_path, "w", newline="") as file: + writer = csv.DictWriter(file, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(metrics) + + def _check_log_dir_exists(self) -> None: + if self._fs.exists(self.log_dir) and self._fs.listdir(self.log_dir): + rank_zero_warn( + f"Experiment logs directory {self.log_dir} exists and is not empty." + " Previous log files in this directory will be deleted when the new ones are saved!" + ) + if self._fs.isfile(self.metrics_file_path): + self._fs.rm_file(self.metrics_file_path) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/logger.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..07eb8ee6c9e87d27fc3d8e1977c2c156a476dde7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/logger.py @@ -0,0 +1,137 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Abstract base class used to build new loggers.""" + +from abc import ABC, abstractmethod +from argparse import Namespace +from functools import wraps +from typing import Any, Callable, Optional, Union + +from torch import Tensor +from torch.nn import Module + +from lightning_fabric.utilities.rank_zero import rank_zero_only + + +class Logger(ABC): + """Base class for experiment loggers.""" + + @property + @abstractmethod + def name(self) -> Optional[str]: + """Return the experiment name.""" + + @property + @abstractmethod + def version(self) -> Optional[Union[int, str]]: + """Return the experiment version.""" + + @property + def root_dir(self) -> Optional[str]: + """Return the root directory where all versions of an experiment get saved, or `None` if the logger does not + save data locally.""" + return None + + @property + def log_dir(self) -> Optional[str]: + """Return directory the current version of the experiment gets saved, or `None` if the logger does not save + data locally.""" + return None + + @property + def group_separator(self) -> str: + """Return the default separator used by the logger to group the data into subfolders.""" + return "/" + + @abstractmethod + def log_metrics(self, metrics: dict[str, float], step: Optional[int] = None) -> None: + """Records metrics. This method logs metrics as soon as it received them. + + Args: + metrics: Dictionary with metric names as keys and measured quantities as values + step: Step number at which the metrics should be recorded + + """ + pass + + @abstractmethod + def log_hyperparams(self, params: Union[dict[str, Any], Namespace], *args: Any, **kwargs: Any) -> None: + """Record hyperparameters. + + Args: + params: :class:`~argparse.Namespace` or `Dict` containing the hyperparameters + args: Optional positional arguments, depends on the specific logger being used + kwargs: Optional keyword arguments, depends on the specific logger being used + + """ + + def log_graph(self, model: Module, input_array: Optional[Tensor] = None) -> None: + """Record model graph. + + Args: + model: the model with an implementation of ``forward``. + input_array: input passes to `model.forward` + + """ + pass + + def save(self) -> None: + """Save log data.""" + + def finalize(self, status: str) -> None: + """Do any processing that is necessary to finalize an experiment. + + Args: + status: Status that the experiment finished with (e.g. success, failed, aborted) + + """ + self.save() + + +def rank_zero_experiment(fn: Callable) -> Callable: + """Returns the real experiment on rank 0 and otherwise the _DummyExperiment.""" + + @wraps(fn) + def experiment(self: Logger) -> Union[Any, _DummyExperiment]: + """ + Note: + ``self`` is a custom logger instance. The loggers typically wrap an ``experiment`` method + with a ``@rank_zero_experiment`` decorator. + + ``Union[Any, _DummyExperiment]`` is used because the wrapped hooks have several return + types that are specific to the custom logger. The return type here can be considered as + ``Union[return type of logger.experiment, _DummyExperiment]``. + """ + if rank_zero_only.rank > 0: + return _DummyExperiment() + return fn(self) + + return experiment + + +class _DummyExperiment: + """Dummy experiment.""" + + def nop(self, *args: Any, **kw: Any) -> None: + pass + + def __getattr__(self, _: Any) -> Callable: + return self.nop + + def __getitem__(self, idx: int) -> "_DummyExperiment": + # enables self.logger.experiment[0].add_image(...) + return self + + def __setitem__(self, *args: Any, **kwargs: Any) -> None: + pass diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/tensorboard.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/tensorboard.py new file mode 100644 index 0000000000000000000000000000000000000000..6c3a7cf7a582c01b18c2015663020b908561f9c7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/loggers/tensorboard.py @@ -0,0 +1,334 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +from argparse import Namespace +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, Optional, Union + +from lightning_utilities.core.imports import RequirementCache +from torch import Tensor +from torch.nn import Module +from typing_extensions import override + +from lightning_fabric.loggers.logger import Logger, rank_zero_experiment +from lightning_fabric.utilities.cloud_io import _is_dir, get_filesystem +from lightning_fabric.utilities.logger import _add_prefix, _convert_params, _flatten_dict +from lightning_fabric.utilities.logger import _sanitize_params as _utils_sanitize_params +from lightning_fabric.utilities.rank_zero import rank_zero_only, rank_zero_warn +from lightning_fabric.utilities.types import _PATH +from lightning_fabric.wrappers import _unwrap_objects + +_TENSORBOARD_AVAILABLE = RequirementCache("tensorboard") +_TENSORBOARDX_AVAILABLE = RequirementCache("tensorboardX") +if TYPE_CHECKING: + # assumes at least one will be installed when type checking + if _TENSORBOARD_AVAILABLE: + from torch.utils.tensorboard import SummaryWriter + else: + from tensorboardX import SummaryWriter # type: ignore[no-redef] + + +class TensorBoardLogger(Logger): + r"""Log to local file system in `TensorBoard `_ format. + + Implemented using :class:`~tensorboardX.SummaryWriter`. Logs are saved to + ``os.path.join(root_dir, name, version)``. This is the recommended logger in Lightning Fabric. + + Args: + root_dir: The root directory in which all your experiments with different names and versions will be stored. + name: Experiment name. Defaults to ``'lightning_logs'``. If it is the empty string then no per-experiment + subdirectory is used. + version: Experiment version. If version is not specified the logger inspects the save + directory for existing versions, then automatically assigns the next available version. + If it is a string then it is used as the run-specific subdirectory name, + otherwise ``'version_${version}'`` is used. + default_hp_metric: Enables a placeholder metric with key `hp_metric` when `log_hyperparams` is + called without a metric (otherwise calls to ``log_hyperparams`` without a metric are ignored). + prefix: A string to put at the beginning of all metric keys. + sub_dir: Sub-directory to group TensorBoard logs. If a ``sub_dir`` argument is passed + then logs are saved in ``/root_dir/name/version/sub_dir/``. Defaults to ``None`` in which case + logs are saved in ``/root_dir/name/version/``. + \**kwargs: Additional arguments used by :class:`tensorboardX.SummaryWriter` can be passed as keyword + arguments in this logger. To automatically flush to disk, `max_queue` sets the size + of the queue for pending logs before flushing. `flush_secs` determines how many seconds + elapses before flushing. + + + Example:: + + from lightning_fabric.loggers import TensorBoardLogger + + logger = TensorBoardLogger("path/to/logs/root", name="my_model") + logger.log_hyperparams({"epochs": 5, "optimizer": "Adam"}) + logger.log_metrics({"acc": 0.75}) + logger.finalize("success") + + """ + + LOGGER_JOIN_CHAR = "-" + + def __init__( + self, + root_dir: _PATH, + name: Optional[str] = "lightning_logs", + version: Optional[Union[int, str]] = None, + default_hp_metric: bool = True, + prefix: str = "", + sub_dir: Optional[_PATH] = None, + **kwargs: Any, + ): + if not _TENSORBOARD_AVAILABLE and not _TENSORBOARDX_AVAILABLE: + raise ModuleNotFoundError( + "Neither `tensorboard` nor `tensorboardX` is available. Try `pip install`ing either.\n" + f"{str(_TENSORBOARDX_AVAILABLE)}\n{str(_TENSORBOARD_AVAILABLE)}" + ) + super().__init__() + root_dir = os.fspath(root_dir) + self._root_dir = root_dir + self._name = name or "" + self._version = version + self._sub_dir = None if sub_dir is None else os.fspath(sub_dir) + + self._default_hp_metric = default_hp_metric + self._prefix = prefix + self._fs = get_filesystem(root_dir) + + self._experiment: Optional[SummaryWriter] = None + self._kwargs = kwargs + + @property + @override + def name(self) -> str: + """Get the name of the experiment. + + Returns: + The name of the experiment. + + """ + return self._name + + @property + @override + def version(self) -> Union[int, str]: + """Get the experiment version. + + Returns: + The experiment version if specified else the next version. + + """ + if self._version is None: + self._version = self._get_next_version() + return self._version + + @property + @override + def root_dir(self) -> str: + """Gets the save directory where the TensorBoard experiments are saved. + + Returns: + The local path to the save directory where the TensorBoard experiments are saved. + + """ + return self._root_dir + + @property + @override + def log_dir(self) -> str: + """The directory for this run's tensorboard checkpoint. + + By default, it is named ``'version_${self.version}'`` but it can be overridden by passing a string value for the + constructor's version parameter instead of ``None`` or an int. + + """ + version = self.version if isinstance(self.version, str) else f"version_{self.version}" + log_dir = os.path.join(self.root_dir, self.name, version) + if isinstance(self.sub_dir, str): + log_dir = os.path.join(log_dir, self.sub_dir) + log_dir = os.path.expandvars(log_dir) + log_dir = os.path.expanduser(log_dir) + return log_dir + + @property + def sub_dir(self) -> Optional[str]: + """Gets the sub directory where the TensorBoard experiments are saved. + + Returns: + The local path to the sub directory where the TensorBoard experiments are saved. + + """ + return self._sub_dir + + @property + @rank_zero_experiment + def experiment(self) -> "SummaryWriter": + """Actual tensorboard object. To use TensorBoard features anywhere in your code, do the following. + + Example:: + + logger.experiment.some_tensorboard_function() + + """ + if self._experiment is not None: + return self._experiment + + assert rank_zero_only.rank == 0, "tried to init log dirs in non global_rank=0" + if self.root_dir: + self._fs.makedirs(self.root_dir, exist_ok=True) + + if _TENSORBOARD_AVAILABLE: + from torch.utils.tensorboard import SummaryWriter + else: + from tensorboardX import SummaryWriter # type: ignore[no-redef] + + self._experiment = SummaryWriter(log_dir=self.log_dir, **self._kwargs) + return self._experiment + + @override + @rank_zero_only + def log_metrics(self, metrics: Mapping[str, float], step: Optional[int] = None) -> None: + assert rank_zero_only.rank == 0, "experiment tried to log from global_rank != 0" + + metrics = _add_prefix(metrics, self._prefix, self.LOGGER_JOIN_CHAR) + + for k, v in metrics.items(): + if isinstance(v, Tensor): + v = v.item() + + if isinstance(v, dict): + self.experiment.add_scalars(k, v, step) + else: + try: + self.experiment.add_scalar(k, v, step) + # TODO(fabric): specify the possible exception + except Exception as ex: + raise ValueError( + f"\n you tried to log {v} which is currently not supported. Try a dict or a scalar/tensor." + ) from ex + + @override + @rank_zero_only + def log_hyperparams( + self, + params: Union[dict[str, Any], Namespace], + metrics: Optional[dict[str, Any]] = None, + step: Optional[int] = None, + ) -> None: + """Record hyperparameters. TensorBoard logs with and without saved hyperparameters are incompatible, the + hyperparameters are then not displayed in the TensorBoard. Please delete or move the previously saved logs to + display the new ones with hyperparameters. + + Args: + params: A dictionary-like container with the hyperparameters + metrics: Dictionary with metric names as keys and measured quantities as values + step: Optional global step number for the logged metrics + + """ + params = _convert_params(params) + + # format params into the suitable for tensorboard + params = _flatten_dict(params) + params = self._sanitize_params(params) + + if metrics is None: + if self._default_hp_metric: + metrics = {"hp_metric": -1} + elif not isinstance(metrics, dict): + metrics = {"hp_metric": metrics} + + if metrics: + self.log_metrics(metrics, step) + + if _TENSORBOARD_AVAILABLE: + from torch.utils.tensorboard.summary import hparams + else: + from tensorboardX.summary import hparams # type: ignore[no-redef] + + exp, ssi, sei = hparams(params, metrics) + writer = self.experiment._get_file_writer() + writer.add_summary(exp, step) + writer.add_summary(ssi, step) + writer.add_summary(sei, step) + + @override + @rank_zero_only + def log_graph(self, model: Module, input_array: Optional[Tensor] = None) -> None: + model_example_input = getattr(model, "example_input_array", None) + input_array = model_example_input if input_array is None else input_array + model = _unwrap_objects(model) + + if input_array is None: + rank_zero_warn( + "Could not log computational graph to TensorBoard: The `model.example_input_array` attribute" + " is not set or `input_array` was not given." + ) + elif not isinstance(input_array, (Tensor, tuple)): + rank_zero_warn( + "Could not log computational graph to TensorBoard: The `input_array` or `model.example_input_array`" + f" has type {type(input_array)} which can't be traced by TensorBoard. Make the input array a tuple" + f" representing the positional arguments to the model's `forward()` implementation." + ) + elif callable(getattr(model, "_on_before_batch_transfer", None)) and callable( + getattr(model, "_apply_batch_transfer_handler", None) + ): + # this is probably is a LightningModule + input_array = model._on_before_batch_transfer(input_array) + input_array = model._apply_batch_transfer_handler(input_array) + self.experiment.add_graph(model, input_array) + else: + self.experiment.add_graph(model, input_array) + + @override + @rank_zero_only + def save(self) -> None: + self.experiment.flush() + + @override + @rank_zero_only + def finalize(self, status: str) -> None: + if self._experiment is not None: + self.experiment.flush() + self.experiment.close() + + def _get_next_version(self) -> int: + save_dir = os.path.join(self.root_dir, self.name) + + try: + listdir_info = self._fs.listdir(save_dir) + except OSError: + return 0 + + existing_versions = [] + for listing in listdir_info: + d = listing["name"] + bn = os.path.basename(d) + if _is_dir(self._fs, d) and bn.startswith("version_"): + dir_ver = bn.split("_")[1].replace("/", "") + if dir_ver.isdigit(): + existing_versions.append(int(dir_ver)) + if len(existing_versions) == 0: + return 0 + + return max(existing_versions) + 1 + + @staticmethod + def _sanitize_params(params: dict[str, Any]) -> dict[str, Any]: + params = _utils_sanitize_params(params) + # logging of arrays with dimension > 1 is not supported, sanitize as string + return {k: str(v) if hasattr(v, "ndim") and v.ndim > 1 else v for k, v in params.items()} + + def __getstate__(self) -> dict[str, Any]: + state = self.__dict__.copy() + state["_experiment"] = None + return state diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..98c0c4e6653fe640ad7ea188a454a2c66e80ee00 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/__init__.py @@ -0,0 +1,42 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment +from lightning_fabric.plugins.io.checkpoint_io import CheckpointIO +from lightning_fabric.plugins.io.torch_io import TorchCheckpointIO +from lightning_fabric.plugins.io.xla import XLACheckpointIO +from lightning_fabric.plugins.precision.amp import MixedPrecision +from lightning_fabric.plugins.precision.bitsandbytes import BitsandbytesPrecision +from lightning_fabric.plugins.precision.deepspeed import DeepSpeedPrecision +from lightning_fabric.plugins.precision.double import DoublePrecision +from lightning_fabric.plugins.precision.fsdp import FSDPPrecision +from lightning_fabric.plugins.precision.half import HalfPrecision +from lightning_fabric.plugins.precision.precision import Precision +from lightning_fabric.plugins.precision.transformer_engine import TransformerEnginePrecision +from lightning_fabric.plugins.precision.xla import XLAPrecision + +__all__ = [ + "ClusterEnvironment", + "CheckpointIO", + "TorchCheckpointIO", + "XLACheckpointIO", + "BitsandbytesPrecision", + "Precision", + "DeepSpeedPrecision", + "DoublePrecision", + "HalfPrecision", + "MixedPrecision", + "TransformerEnginePrecision", + "XLAPrecision", + "FSDPPrecision", +] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d23a095e25b2706492710d8fb99b95591e2d1ecb Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..be1c5a17687c9472af1314ae57c07f30c622ec00 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__init__.py @@ -0,0 +1,9 @@ +from lightning_fabric.plugins.collectives.collective import Collective +from lightning_fabric.plugins.collectives.single_device import SingleDeviceCollective +from lightning_fabric.plugins.collectives.torch_collective import TorchCollective + +__all__ = [ + "Collective", + "TorchCollective", + "SingleDeviceCollective", +] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12ccb2915d2442f524ea5f5d19d438dd39b4e31f Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/collective.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/collective.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6cd97194a6f2380d3f1a60167c996bd7f43d007 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/collective.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/single_device.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/single_device.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e54fbccbea828274767b314871c84ae4396a6db1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/single_device.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/torch_collective.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/torch_collective.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d54d1d4ded84ad8008b71ada82b6776d4961544a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/__pycache__/torch_collective.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/collective.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/collective.py new file mode 100644 index 0000000000000000000000000000000000000000..a12dbdeab1352a632af647f1cdf72e259fbed082 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/collective.py @@ -0,0 +1,119 @@ +from abc import ABC, abstractmethod +from typing import Any, Optional + +from torch import Tensor +from typing_extensions import Self + +from lightning_fabric.utilities.types import CollectibleGroup + + +class Collective(ABC): + """Interface for collective operations. + + Supports communications between multiple processes and multiple nodes. A collective owns a group. + + .. warning:: This is an :ref:`experimental ` feature which is still in development. + + """ + + def __init__(self) -> None: + self._group: Optional[CollectibleGroup] = None + + @property + @abstractmethod + def rank(self) -> int: + """Rank.""" + + @property + @abstractmethod + def world_size(self) -> int: + """World size.""" + + @property + def group(self) -> CollectibleGroup: + if self._group is None: + raise RuntimeError( + f"`{type(self).__name__}` does not own a group. HINT: try `collective.create_group().group`" + ) + return self._group + + @abstractmethod + def broadcast(self, tensor: Tensor, src: int) -> Tensor: ... + + @abstractmethod + def all_reduce(self, tensor: Tensor, op: str) -> Tensor: ... + + @abstractmethod + def reduce(self, tensor: Tensor, dst: int, op: str) -> Tensor: ... + + @abstractmethod + def all_gather(self, tensor_list: list[Tensor], tensor: Tensor) -> list[Tensor]: ... + + @abstractmethod + def gather(self, tensor: Tensor, gather_list: list[Tensor], dst: int = 0) -> list[Tensor]: ... + + @abstractmethod + def scatter(self, tensor: Tensor, scatter_list: list[Tensor], src: int = 0) -> Tensor: ... + + @abstractmethod + def reduce_scatter(self, output: Tensor, input_list: list[Tensor], op: str) -> Tensor: ... + + @abstractmethod + def all_to_all(self, output_tensor_list: list[Tensor], input_tensor_list: list[Tensor]) -> list[Tensor]: ... + + @abstractmethod + def send(self, tensor: Tensor, dst: int, tag: int = 0) -> None: ... + + @abstractmethod + def recv(self, tensor: Tensor, src: Optional[int] = None, tag: int = 0) -> Tensor: ... + + @abstractmethod + def barrier(self, device_ids: Optional[list[int]] = None) -> None: ... + + @classmethod + @abstractmethod + def is_available(cls) -> bool: ... + + @classmethod + @abstractmethod + def is_initialized(cls) -> bool: ... + + @classmethod + @abstractmethod + def init_group(cls, **kwargs: Any) -> None: ... + + @classmethod + @abstractmethod + def new_group(cls, **kwargs: Any) -> CollectibleGroup: ... + + @classmethod + @abstractmethod + def destroy_group(cls, group: CollectibleGroup) -> None: ... + + @classmethod + @abstractmethod + def _convert_to_native_op(cls, op: str) -> Any: ... + + def setup(self, **kwargs: Any) -> Self: + if not self.is_initialized(): + self.init_group(**kwargs) + return self + + def create_group(self, **kwargs: Any) -> Self: + """Create a group. + + This assumes that :meth:`~lightning_fabric.plugins.collectives.Collective.init_group` has been + called already by the user. + + """ + if self._group is not None: + raise RuntimeError(f"`{type(self).__name__}` already owns a group.") + self._group = self.new_group(**kwargs) + return self + + def teardown(self) -> Self: + if self._group is None: + raise RuntimeError(f"`{type(self).__name__}` does not own a group to destroy.") + self.destroy_group(self._group) + self._group = None + return self diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/single_device.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/single_device.py new file mode 100644 index 0000000000000000000000000000000000000000..eb03cbc3f7d97810bbd1ad35b5074b9687bfc53b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/single_device.py @@ -0,0 +1,107 @@ +from typing import Any + +from torch import Tensor +from typing_extensions import override + +from lightning_fabric.plugins.collectives.collective import Collective +from lightning_fabric.utilities.types import CollectibleGroup + + +class SingleDeviceCollective(Collective): + """Support for collective operations on a single device (no-op). + + .. warning:: This is an :ref:`experimental ` feature which is still in development. + + """ + + @property + @override + def rank(self) -> int: + return 0 + + @property + @override + def world_size(self) -> int: + return 1 + + @override + def broadcast(self, tensor: Tensor, *_: Any, **__: Any) -> Tensor: + return tensor + + @override + def all_reduce(self, tensor: Tensor, *_: Any, **__: Any) -> Tensor: + return tensor + + @override + def reduce(self, tensor: Tensor, *_: Any, **__: Any) -> Tensor: + return tensor + + @override + def all_gather(self, tensor_list: list[Tensor], tensor: Tensor, **__: Any) -> list[Tensor]: + return [tensor] + + @override + def gather(self, tensor: Tensor, *_: Any, **__: Any) -> list[Tensor]: + return [tensor] + + @override + def scatter( + self, + tensor: Tensor, + scatter_list: list[Tensor], + *_: Any, + **__: Any, + ) -> Tensor: + return scatter_list[0] + + @override + def reduce_scatter(self, output: Tensor, input_list: list[Tensor], *_: Any, **__: Any) -> Tensor: + return input_list[0] + + @override + def all_to_all( + self, output_tensor_list: list[Tensor], input_tensor_list: list[Tensor], *_: Any, **__: Any + ) -> list[Tensor]: + return input_tensor_list + + @override + def send(self, *_: Any, **__: Any) -> None: + pass + + @override + def recv(self, tensor: Tensor, *_: Any, **__: Any) -> Tensor: + return tensor + + @override + def barrier(self, *_: Any, **__: Any) -> None: + pass + + @classmethod + @override + def is_available(cls) -> bool: + return True # vacuous truth + + @classmethod + @override + def is_initialized(cls) -> bool: + return True # vacuous truth + + @classmethod + @override + def init_group(cls, **_: Any) -> None: + pass + + @classmethod + @override + def new_group(cls, **_: Any) -> CollectibleGroup: + return object() # type: ignore[return-value] + + @classmethod + @override + def destroy_group(cls, group: CollectibleGroup) -> None: + pass + + @classmethod + @override + def _convert_to_native_op(cls, op: str) -> str: + return op diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/torch_collective.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/torch_collective.py new file mode 100644 index 0000000000000000000000000000000000000000..bc8a540881f292c6aa010f8341403fd0bbea2586 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/collectives/torch_collective.py @@ -0,0 +1,219 @@ +import datetime +import os +from typing import Any, Optional, Union + +import torch +import torch.distributed as dist +from torch import Tensor +from typing_extensions import Self, override + +from lightning_fabric.plugins.collectives.collective import Collective +from lightning_fabric.utilities.types import CollectibleGroup, RedOpType, ReduceOp + +if dist.is_available(): + from torch.distributed.constants import default_pg_timeout +else: + default_pg_timeout = datetime.timedelta(seconds=1800) + + +class TorchCollective(Collective): + """Collective operations using `torch.distributed `__. + + .. warning:: This is an :ref:`experimental ` feature which is still in development. + + """ + + manages_default_group = False + addr_key = "MASTER_ADDR" + port_key = "MASTER_PORT" + + def __init__(self) -> None: + if not dist.is_available(): + raise RuntimeError("Torch distributed is not available.") + super().__init__() + + @property + @override + def group(self) -> CollectibleGroup: + if self._group is None: + self._group = dist.GroupMember.WORLD + return super().group + + @property + @override + def rank(self) -> int: + # local rank + return dist.get_rank(self.group) # type: ignore[arg-type] + + @property + @override + def world_size(self) -> int: + return dist.get_world_size(self.group) # type: ignore[arg-type] + + @override + def broadcast(self, tensor: Tensor, src: int) -> Tensor: + dist.broadcast(tensor, src, group=self.group) # type: ignore[arg-type] + return tensor + + @override + def all_reduce(self, tensor: Tensor, op: Union[str, ReduceOp, RedOpType] = "sum") -> Tensor: + op = self._convert_to_native_op(op) + dist.all_reduce(tensor, op=op, group=self.group) + return tensor + + @override + def reduce(self, tensor: Tensor, dst: int, op: Union[str, ReduceOp, RedOpType] = "sum") -> Tensor: + op = self._convert_to_native_op(op) + dist.reduce(tensor, dst, op=op, group=self.group) # type: ignore[arg-type] + return tensor + + @override + def all_gather(self, tensor_list: list[Tensor], tensor: Tensor) -> list[Tensor]: + dist.all_gather(tensor_list, tensor, group=self.group) + return tensor_list + + @override + def gather(self, tensor: Tensor, gather_list: list[Tensor], dst: int = 0) -> list[Tensor]: + dist.gather(tensor, gather_list, dst, group=self.group) # type: ignore[arg-type] + return gather_list + + @override + def scatter(self, tensor: Tensor, scatter_list: list[Tensor], src: int = 0) -> Tensor: + dist.scatter(tensor, scatter_list, src, group=self.group) # type: ignore[arg-type] + return tensor + + @override + def reduce_scatter( + self, output: Tensor, input_list: list[Tensor], op: Union[str, ReduceOp, RedOpType] = "sum" + ) -> Tensor: + op = self._convert_to_native_op(op) + dist.reduce_scatter(output, input_list, op=op, group=self.group) + return output + + @override + def all_to_all(self, output_tensor_list: list[Tensor], input_tensor_list: list[Tensor]) -> list[Tensor]: + dist.all_to_all(output_tensor_list, input_tensor_list, group=self.group) + return output_tensor_list + + @override + def send(self, tensor: Tensor, dst: int, tag: int = 0) -> None: + dist.send(tensor, dst, tag=tag, group=self.group) # type: ignore[arg-type] + + @override + def recv(self, tensor: Tensor, src: Optional[int] = None, tag: int = 0) -> Tensor: + dist.recv(tensor, src, tag=tag, group=self.group) # type: ignore[arg-type] + return tensor + + def all_gather_object(self, object_list: list[Any], obj: Any) -> list[Any]: + dist.all_gather_object(object_list, obj, group=self.group) + return object_list + + def broadcast_object_list( + self, object_list: list[Any], src: int, device: Optional[torch.device] = None + ) -> list[Any]: + dist.broadcast_object_list(object_list, src, group=self.group, device=device) # type: ignore[arg-type] + return object_list + + def gather_object(self, obj: Any, object_gather_list: list[Any], dst: int = 0) -> list[Any]: + dist.gather_object(obj, object_gather_list, dst, group=self.group) # type: ignore[arg-type] + return object_gather_list + + def scatter_object_list( + self, scatter_object_output_list: list[Any], scatter_object_input_list: list[Any], src: int = 0 + ) -> list[Any]: + dist.scatter_object_list(scatter_object_output_list, scatter_object_input_list, src, group=self.group) # type: ignore[arg-type] + return scatter_object_output_list + + @override + def barrier(self, device_ids: Optional[list[int]] = None) -> None: + if self.group == dist.GroupMember.NON_GROUP_MEMBER: + return + dist.barrier(group=self.group, device_ids=device_ids) # type: ignore[arg-type] + + def monitored_barrier(self, timeout: Optional[datetime.timedelta] = None, wait_all_ranks: bool = False) -> None: + dist.monitored_barrier(group=self.group, timeout=timeout, wait_all_ranks=wait_all_ranks) # type: ignore[arg-type] + + @override + def setup(self, main_address: Optional[str] = None, main_port: Optional[str] = None, **kwargs: Any) -> Self: + if self.is_initialized(): + return self + # maybe set addr + setting_env = [] + if main_address is not None and self.addr_key not in os.environ: + os.environ[self.addr_key] = main_address + setting_env.append(self.addr_key) + # maybe set port + if main_port is not None and self.port_key not in os.environ: + os.environ[self.port_key] = str(main_port) + setting_env.append(self.port_key) + # this will `init_group` + super().setup(**kwargs) + # set as a class attribute so any instance can know whether we initialized the default process group + TorchCollective.manages_default_group = True + # cleanup + for kenv in setting_env: + os.environ.pop(kenv, None) + return self + + @override + def teardown(self) -> Self: + group_member = self.group != dist.GroupMember.NON_GROUP_MEMBER + super().teardown() # will destroy its own group + # try to destroy the default group. this should only be done by a group member to avoid race conditions, + # and only if the class is managing it + if ( + group_member + and TorchCollective.manages_default_group + and (default_group := dist.GroupMember.WORLD) is not None # not destroyed already + and len(dist.distributed_c10d._pg_map) == 1 # only the default group is left + ): + self.destroy_group(default_group) + TorchCollective.manages_default_group = False + elif TorchCollective.manages_default_group and dist.GroupMember.WORLD is None: + TorchCollective.manages_default_group = False + return self + + @classmethod + @override + def is_available(cls) -> bool: + return dist.is_available() + + @classmethod + @override + def is_initialized(cls) -> bool: + return cls.is_available() and dist.is_initialized() + + @classmethod + @override + def init_group(cls, **kwargs: Any) -> None: + dist.init_process_group(**kwargs) + + @classmethod + @override + def new_group(cls, **kwargs: Any) -> CollectibleGroup: + return dist.new_group(**kwargs) + + @classmethod + @override + def destroy_group(cls, group: CollectibleGroup) -> None: + # can be called by all processes in the default group, group will be `object()` if they are not part of the + # current group + if group in dist.distributed_c10d._pg_map: + dist.destroy_process_group(group) # type: ignore[arg-type] + + @classmethod + @override + def _convert_to_native_op(cls, op: Union[str, ReduceOp, RedOpType]) -> Union[ReduceOp, RedOpType]: + # `ReduceOp` is an empty shell for `RedOpType`, the latter being the actually returned class. + # For example, `ReduceOp.SUM` returns a `RedOpType.SUM`. the only exception is `RedOpType.PREMUL_SUM` where + # `ReduceOp` is still the desired class, but it's created via a special `_make_nccl_premul_sum` function + if isinstance(op, (ReduceOp, RedOpType)): + return op + if not isinstance(op, str): + raise ValueError(f"Unsupported op {op!r} of type {type(op).__name__}") + op = op.upper() + # `ReduceOp` should contain `RedOpType`'s members + value = getattr(ReduceOp, op, None) + if value is None: + raise ValueError(f"op {op!r} is not a member of `ReduceOp`") + return value diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..002c3d59878d20615d1eaa205e7a3edbf08582f6 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__init__.py @@ -0,0 +1,21 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment # noqa: F401 +from lightning_fabric.plugins.environments.kubeflow import KubeflowEnvironment # noqa: F401 +from lightning_fabric.plugins.environments.lightning import LightningEnvironment # noqa: F401 +from lightning_fabric.plugins.environments.lsf import LSFEnvironment # noqa: F401 +from lightning_fabric.plugins.environments.mpi import MPIEnvironment # noqa: F401 +from lightning_fabric.plugins.environments.slurm import SLURMEnvironment # noqa: F401 +from lightning_fabric.plugins.environments.torchelastic import TorchElasticEnvironment # noqa: F401 +from lightning_fabric.plugins.environments.xla import XLAEnvironment # noqa: F401 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ed0979865d27d400b2c4b76f00d4cb5304126fc Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/cluster_environment.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/cluster_environment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..093ad0a8f430885601eae802c1e48958695ecbd6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/cluster_environment.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/kubeflow.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/kubeflow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a8ce46968ed3a6848e906c3a52ce37649986417 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/kubeflow.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/lightning.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/lightning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6e455134e143678d77a9c18b34fd948a747ff94 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/lightning.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/lsf.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/lsf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3a3ce5f55aa35b301830c4561c404e411bd9f62 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/lsf.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/mpi.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/mpi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbebf462781e4f6c3e4ced536531872a6a2ab4f6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/mpi.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/slurm.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/slurm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92df9069cdc74a72d9f00c7ed4043c4443d128ef Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/slurm.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/torchelastic.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/torchelastic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bbc1fc4e04d112b9eab8e5d277afc97aa188206 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/torchelastic.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/xla.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/xla.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bdb2a9da89fe2cc872eab4afc7f268889d9207a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/__pycache__/xla.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/cluster_environment.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/cluster_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ad96d3ab6c3fdf58b6569457515633c5731276 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/cluster_environment.py @@ -0,0 +1,71 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from abc import ABC, abstractmethod + + +class ClusterEnvironment(ABC): + """Specification of a cluster environment.""" + + @property + @abstractmethod + def creates_processes_externally(self) -> bool: + """Whether the environment creates the subprocesses or not.""" + + @property + @abstractmethod + def main_address(self) -> str: + """The main address through which all processes connect and communicate.""" + + @property + @abstractmethod + def main_port(self) -> int: + """An open and configured port in the main node through which all processes communicate.""" + + @staticmethod + @abstractmethod + def detect() -> bool: + """Detects the environment settings corresponding to this cluster and returns ``True`` if they match.""" + + @abstractmethod + def world_size(self) -> int: + """The number of processes across all devices and nodes.""" + + @abstractmethod + def set_world_size(self, size: int) -> None: + pass + + @abstractmethod + def global_rank(self) -> int: + """The rank (index) of the currently running process across all nodes and devices.""" + + @abstractmethod + def set_global_rank(self, rank: int) -> None: + pass + + @abstractmethod + def local_rank(self) -> int: + """The rank (index) of the currently running process inside of the current node.""" + + @abstractmethod + def node_rank(self) -> int: + """The rank (index) of the node on which the current process runs.""" + + def validate_settings(self, num_devices: int, num_nodes: int) -> None: + """Validates settings configured in the script against the environment, and raises an exception if there is an + inconsistency.""" + pass + + def teardown(self) -> None: + """Clean up any state set after execution finishes.""" + pass diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/kubeflow.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/kubeflow.py new file mode 100644 index 0000000000000000000000000000000000000000..6ef7ada2b73c30dd8377ecb0cec2188f7c7b6a5c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/kubeflow.py @@ -0,0 +1,78 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import os + +from typing_extensions import override + +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment + +log = logging.getLogger(__name__) + + +class KubeflowEnvironment(ClusterEnvironment): + """Environment for distributed training using the `PyTorchJob`_ operator from `Kubeflow`_. + + This environment, unlike others, does not get auto-detected and needs to be passed to the Fabric/Trainer + constructor manually. + + .. _PyTorchJob: https://www.kubeflow.org/docs/components/trainer/legacy-v1/user-guides/pytorch/ + .. _Kubeflow: https://www.kubeflow.org + + """ + + @property + @override + def creates_processes_externally(self) -> bool: + return True + + @property + @override + def main_address(self) -> str: + return os.environ["MASTER_ADDR"] + + @property + @override + def main_port(self) -> int: + return int(os.environ["MASTER_PORT"]) + + @staticmethod + @override + def detect() -> bool: + raise NotImplementedError("The Kubeflow environment can't be detected automatically.") + + @override + def world_size(self) -> int: + return int(os.environ["WORLD_SIZE"]) + + @override + def set_world_size(self, size: int) -> None: + log.debug("KubeflowEnvironment.set_world_size was called, but setting world size is not allowed. Ignored.") + + @override + def global_rank(self) -> int: + return int(os.environ["RANK"]) + + @override + def set_global_rank(self, rank: int) -> None: + log.debug("KubeflowEnvironment.set_global_rank was called, but setting global rank is not allowed. Ignored.") + + @override + def local_rank(self) -> int: + return 0 + + @override + def node_rank(self) -> int: + return self.global_rank() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/lightning.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/lightning.py new file mode 100644 index 0000000000000000000000000000000000000000..0c8f27edc7e9ea9c94e6b0962ae3164d0d1069f8 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/lightning.py @@ -0,0 +1,124 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import socket + +from typing_extensions import override + +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment +from lightning_fabric.utilities.rank_zero import rank_zero_only + + +class LightningEnvironment(ClusterEnvironment): + """The default environment used by Lightning for a single node or free cluster (not managed). + + There are two modes the Lightning environment can operate with: + + 1. The user only launches the main process by :code:`python train.py ...` with no additional environment variables + set. Lightning will spawn new worker processes for distributed training in the current node. + 2. The user launches all processes manually or with utilities like :code:`torch.distributed.launch`. + The appropriate environment variables need to be set, and at minimum :code:`LOCAL_RANK`. + + If the main address and port are not provided, the default environment will choose them + automatically. It is recommended to use this default environment for single-node distributed + training as it provides a convenient way to launch the training script. + + """ + + def __init__(self) -> None: + super().__init__() + self._main_port: int = -1 + self._global_rank: int = 0 + self._world_size: int = 1 + + @property + @override + def creates_processes_externally(self) -> bool: + """Returns whether the cluster creates the processes or not. + + If at least :code:`LOCAL_RANK` is available as environment variable, Lightning assumes the user acts as the + process launcher/job scheduler and Lightning will not launch new processes. + + """ + return "LOCAL_RANK" in os.environ + + @property + @override + def main_address(self) -> str: + return os.environ.get("MASTER_ADDR", "127.0.0.1") + + @property + @override + def main_port(self) -> int: + if self._main_port == -1: + self._main_port = ( + int(os.environ["MASTER_PORT"]) if "MASTER_PORT" in os.environ else find_free_network_port() + ) + return self._main_port + + @staticmethod + @override + def detect() -> bool: + return True + + @override + def world_size(self) -> int: + return self._world_size + + @override + def set_world_size(self, size: int) -> None: + self._world_size = size + + @override + def global_rank(self) -> int: + return self._global_rank + + @override + def set_global_rank(self, rank: int) -> None: + self._global_rank = rank + rank_zero_only.rank = rank + + @override + def local_rank(self) -> int: + return int(os.environ.get("LOCAL_RANK", 0)) + + @override + def node_rank(self) -> int: + group_rank = os.environ.get("GROUP_RANK", 0) + return int(os.environ.get("NODE_RANK", group_rank)) + + @override + def teardown(self) -> None: + if "WORLD_SIZE" in os.environ: + del os.environ["WORLD_SIZE"] + + +def find_free_network_port() -> int: + """Finds a free port on localhost. + + If the environment variable `STANDALONE_PORT` is set, its value is used as the port number. + + It is useful in single-node training when we don't want to connect to a real main node but have to set the + `MASTER_PORT` environment variable. + + """ + if "STANDALONE_PORT" in os.environ: + _port = os.environ["STANDALONE_PORT"] + return int(_port) + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("", 0)) + port = s.getsockname()[1] + s.close() + return port diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/lsf.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/lsf.py new file mode 100644 index 0000000000000000000000000000000000000000..769fe3e754459ed41210c3f0f58c600ba25f1b58 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/lsf.py @@ -0,0 +1,200 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import logging +import os +import socket + +from typing_extensions import override + +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment +from lightning_fabric.utilities.cloud_io import get_filesystem + +log = logging.getLogger(__name__) + + +class LSFEnvironment(ClusterEnvironment): + """An environment for running on clusters managed by the LSF resource manager. + + It is expected that any execution using this ClusterEnvironment was executed + using the Job Step Manager i.e. ``jsrun``. + + This plugin expects the following environment variables: + + ``LSB_JOBID`` + The LSF assigned job ID + + ``LSB_DJOB_RANKFILE`` + The OpenMPI compatible rank file for the LSF job + + ``JSM_NAMESPACE_LOCAL_RANK`` + The node local rank for the task. This environment variable is set by ``jsrun`` + + ``JSM_NAMESPACE_SIZE`` + The world size for the task. This environment variable is set by ``jsrun`` + + ``JSM_NAMESPACE_RANK`` + The global rank for the task. This environment variable is set by ``jsrun`` + + """ + + def __init__(self) -> None: + super().__init__() + self._main_address = self._get_main_address() + self._main_port = self._get_main_port() + self._node_rank = self._get_node_rank() + self._set_init_progress_group_env_vars() + + def _set_init_progress_group_env_vars(self) -> None: + # set environment variables needed for initializing torch distributed process group + os.environ["MASTER_ADDR"] = str(self._main_address) + log.debug(f"MASTER_ADDR: {os.environ['MASTER_ADDR']}") + os.environ["MASTER_PORT"] = str(self._main_port) + log.debug(f"MASTER_PORT: {os.environ['MASTER_PORT']}") + + @property + @override + def creates_processes_externally(self) -> bool: + """LSF creates subprocesses, i.e., PyTorch Lightning does not need to spawn them.""" + return True + + @property + @override + def main_address(self) -> str: + """The main address is read from an OpenMPI host rank file in the environment variable + ``LSB_DJOB_RANKFILE``.""" + return self._main_address + + @property + @override + def main_port(self) -> int: + """The main port is calculated from the LSF job ID.""" + return self._main_port + + @staticmethod + @override + def detect() -> bool: + """Returns ``True`` if the current process was launched using the ``jsrun`` command.""" + required_env_vars = {"LSB_JOBID", "LSB_DJOB_RANKFILE", "JSM_NAMESPACE_LOCAL_RANK", "JSM_NAMESPACE_SIZE"} + return required_env_vars.issubset(os.environ.keys()) + + @override + def world_size(self) -> int: + """The world size is read from the environment variable ``JSM_NAMESPACE_SIZE``.""" + world_size = os.environ.get("JSM_NAMESPACE_SIZE") + if world_size is None: + raise ValueError( + "Cannot determine world size. Environment variable `JSM_NAMESPACE_SIZE` not found." + " Make sure you run your executable with `jsrun`." + ) + return int(world_size) + + @override + def set_world_size(self, size: int) -> None: + log.debug("LSFEnvironment.set_world_size was called, but setting world size is not allowed. Ignored.") + + @override + def global_rank(self) -> int: + """The world size is read from the environment variable ``JSM_NAMESPACE_RANK``.""" + global_rank = os.environ.get("JSM_NAMESPACE_RANK") + if global_rank is None: + raise ValueError( + "Cannot determine global rank. Environment variable `JSM_NAMESPACE_RANK` not found." + " Make sure you run your executable with `jsrun`." + ) + return int(global_rank) + + @override + def set_global_rank(self, rank: int) -> None: + log.debug("LSFEnvironment.set_global_rank was called, but setting global rank is not allowed. Ignored.") + + @override + def local_rank(self) -> int: + """The local rank is read from the environment variable `JSM_NAMESPACE_LOCAL_RANK`.""" + local_rank = os.environ.get("JSM_NAMESPACE_LOCAL_RANK") + if local_rank is None: + raise ValueError( + "Cannot determine local rank. Environment variable `JSM_NAMESPACE_LOCAL_RANK` not found." + " Make sure you run your executable with `jsrun`." + ) + return int(local_rank) + + @override + def node_rank(self) -> int: + """The node rank is determined by the position of the current hostname in the OpenMPI host rank file stored in + ``LSB_DJOB_RANKFILE``.""" + return self._node_rank + + def _get_node_rank(self) -> int: + """A helper method for getting the node rank. + + The node rank is determined by the position of the current node in the list of hosts used in the job. This is + calculated by reading all hosts from ``LSB_DJOB_RANKFILE`` and finding this node's hostname in the list. + + """ + hosts = self._read_hosts() + count: dict[str, int] = {} + for host in hosts: + if host not in count: + count[host] = len(count) + return count[socket.gethostname()] + + @staticmethod + def _read_hosts() -> list[str]: + """Read compute hosts that are a part of the compute job. + + LSF uses the Job Step Manager (JSM) to manage job steps. Job steps are executed by the JSM from "launch" nodes. + Each job is assigned a launch node. This launch node will be the first node in the list contained in + ``LSB_DJOB_RANKFILE``. + + """ + var = "LSB_DJOB_RANKFILE" + rankfile = os.environ.get(var) + if rankfile is None: + raise ValueError("Did not find the environment variable `LSB_DJOB_RANKFILE`") + if not rankfile: + raise ValueError("The environment variable `LSB_DJOB_RANKFILE` is empty") + + fs = get_filesystem(rankfile) + with fs.open(rankfile, "r") as f: + ret = [line.strip() for line in f] + # remove the launch node (i.e. the first node in LSB_DJOB_RANKFILE) from the list + return ret[1:] + + def _get_main_address(self) -> str: + """A helper for getting the main address. + + The main address is assigned to the first node in the list of nodes used for the job. + + """ + hosts = self._read_hosts() + return hosts[0] + + @staticmethod + def _get_main_port() -> int: + """A helper function for accessing the main port. + + Uses the LSF job ID so all ranks can compute the main port. + + """ + # check for user-specified main port + if "MASTER_PORT" in os.environ: + log.debug(f"Using externally specified main port: {os.environ['MASTER_PORT']}") + return int(os.environ["MASTER_PORT"]) + if "LSB_JOBID" in os.environ: + port = int(os.environ["LSB_JOBID"]) + # all ports should be in the 10k+ range + port = port % 1000 + 10000 + log.debug(f"calculated LSF main port: {port}") + return port + raise ValueError("Could not find job id in environment variable LSB_JOBID") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/mpi.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/mpi.py new file mode 100644 index 0000000000000000000000000000000000000000..8ec248f377067a524f9517938d689833fec76567 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/mpi.py @@ -0,0 +1,131 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import socket +from functools import lru_cache +from typing import Optional + +from lightning_utilities.core.imports import RequirementCache +from typing_extensions import override + +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment +from lightning_fabric.plugins.environments.lightning import find_free_network_port + +log = logging.getLogger(__name__) + +_MPI4PY_AVAILABLE = RequirementCache("mpi4py") + + +class MPIEnvironment(ClusterEnvironment): + """An environment for running on clusters with processes created through MPI. + + Requires the installation of the `mpi4py` package. See also: https://github.com/mpi4py/mpi4py + + """ + + def __init__(self) -> None: + if not _MPI4PY_AVAILABLE: + raise ModuleNotFoundError(str(_MPI4PY_AVAILABLE)) + + from mpi4py import MPI + + self._comm_world = MPI.COMM_WORLD + self._comm_local: Optional[MPI.Comm] = None + self._node_rank: Optional[int] = None + self._main_address: Optional[str] = None + self._main_port: Optional[int] = None + + @property + @override + def creates_processes_externally(self) -> bool: + return True + + @property + @override + def main_address(self) -> str: + if self._main_address is None: + self._main_address = self._get_main_address() + return self._main_address + + @property + @override + def main_port(self) -> int: + if self._main_port is None: + self._main_port = self._get_main_port() + return self._main_port + + @staticmethod + @override + def detect() -> bool: + """Returns ``True`` if the `mpi4py` package is installed and MPI returns a world size greater than 1.""" + if not _MPI4PY_AVAILABLE: + return False + + try: + # mpi4py may be installed without MPI being present + from mpi4py import MPI + except ImportError: + return False + + return MPI.COMM_WORLD.Get_size() > 1 + + @override + @lru_cache(1) + def world_size(self) -> int: + return self._comm_world.Get_size() + + @override + def set_world_size(self, size: int) -> None: + log.debug("MPIEnvironment.set_world_size was called, but setting world size is not allowed. Ignored.") + + @override + @lru_cache(1) + def global_rank(self) -> int: + return self._comm_world.Get_rank() + + @override + def set_global_rank(self, rank: int) -> None: + log.debug("MPIEnvironment.set_global_rank was called, but setting global rank is not allowed. Ignored.") + + @override + @lru_cache(1) + def local_rank(self) -> int: + if self._comm_local is None: + self._init_comm_local() + assert self._comm_local is not None + return self._comm_local.Get_rank() + + @override + def node_rank(self) -> int: + if self._node_rank is None: + self._init_comm_local() + assert self._node_rank is not None + return self._node_rank + + def _get_main_address(self) -> str: + return self._comm_world.bcast(socket.gethostname(), root=0) + + def _get_main_port(self) -> int: + return self._comm_world.bcast(find_free_network_port(), root=0) + + def _init_comm_local(self) -> None: + hostname = socket.gethostname() + all_hostnames = self._comm_world.gather(hostname, root=0) # returns None on non-root ranks + # sort all the hostnames, and find unique ones + unique_hosts = sorted(set(all_hostnames)) if all_hostnames is not None else [] + unique_hosts = self._comm_world.bcast(unique_hosts, root=0) + # find the index for this host in the list of hosts: + self._node_rank = unique_hosts.index(hostname) + self._comm_local = self._comm_world.Split(color=self._node_rank) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/slurm.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/slurm.py new file mode 100644 index 0000000000000000000000000000000000000000..73eedac6485dc807a20158709099cceb09d7b102 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/slurm.py @@ -0,0 +1,232 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import os +import re +import shutil +import signal +import sys +from typing import Optional + +from typing_extensions import override + +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment +from lightning_fabric.utilities.imports import _IS_WINDOWS +from lightning_fabric.utilities.rank_zero import rank_zero_warn +from lightning_fabric.utilities.warnings import PossibleUserWarning + +log = logging.getLogger(__name__) + + +class SLURMEnvironment(ClusterEnvironment): + """Cluster environment for training on a cluster managed by SLURM. + + You can configure the `main_address` and `main_port` properties via the env variables `MASTER_ADDR` and + `MASTER_PORT`, respectively. + + Args: + auto_requeue: Whether automatic job resubmission is enabled or not. How and under which conditions a job gets + rescheduled gets determined by the owner of this plugin. + requeue_signal: The signal that SLURM will send to indicate that the job should be requeued. Defaults to + SIGUSR1 on Unix. + + """ + + def __init__(self, auto_requeue: bool = True, requeue_signal: Optional[signal.Signals] = None) -> None: + super().__init__() + self.auto_requeue = auto_requeue + if requeue_signal is None and not _IS_WINDOWS: + requeue_signal = signal.SIGUSR1 + self.requeue_signal = requeue_signal + self._validate_srun_used() + self._validate_srun_variables() + + @property + @override + def creates_processes_externally(self) -> bool: + return True + + @property + @override + def main_address(self) -> str: + root_node = os.environ.get("MASTER_ADDR") + if root_node is None: + nodelist = os.environ.get("SLURM_NODELIST", "127.0.0.1") + root_node = self.resolve_root_node_address(nodelist) + os.environ["MASTER_ADDR"] = root_node + + log.debug(f"MASTER_ADDR: {os.environ['MASTER_ADDR']}") + return root_node + + @property + @override + def main_port(self) -> int: + # ----------------------- + # SLURM JOB = PORT number + # ----------------------- + # this way every process knows what port to use + job_id = os.environ.get("SLURM_JOB_ID") + if job_id is not None: + # use the last 4 numbers in the job id as the id + default_port = job_id[-4:] + # all ports should be in the 10k+ range + default_port = int(default_port) + 15000 + else: + default_port = 12910 + + # ----------------------- + # PORT NUMBER = MASTER_PORT + # ----------------------- + # in case the user passed it in + if "MASTER_PORT" in os.environ: + default_port = int(os.environ["MASTER_PORT"]) + else: + os.environ["MASTER_PORT"] = str(default_port) + + log.debug(f"MASTER_PORT: {os.environ['MASTER_PORT']}") + return default_port + + @staticmethod + @override + def detect() -> bool: + """Returns ``True`` if the current process was launched on a SLURM cluster. + + It is possible to use the SLURM scheduler to request resources and then launch processes manually using a + different environment. For this, the user can set the job name in SLURM to 'bash' or 'interactive' (srun --job- + name=interactive). This will then avoid the detection of ``SLURMEnvironment`` and another environment can be + detected automatically. + + """ + SLURMEnvironment._validate_srun_used() + return _is_srun_used() + + @staticmethod + def job_name() -> Optional[str]: + return os.environ.get("SLURM_JOB_NAME") + + @staticmethod + def job_id() -> Optional[int]: + # in interactive mode, don't make logs use the same job id + if _is_slurm_interactive_mode(): + return None + + job_id = os.environ.get("SLURM_JOB_ID") + if job_id is None: + return None + try: + return int(job_id) + except ValueError: + return None + + @override + def world_size(self) -> int: + return int(os.environ["SLURM_NTASKS"]) + + @override + def set_world_size(self, size: int) -> None: + log.debug("SLURMEnvironment.set_world_size was called, but setting world size is not allowed. Ignored.") + + @override + def global_rank(self) -> int: + return int(os.environ["SLURM_PROCID"]) + + @override + def set_global_rank(self, rank: int) -> None: + log.debug("SLURMEnvironment.set_global_rank was called, but setting global rank is not allowed. Ignored.") + + @override + def local_rank(self) -> int: + return int(os.environ["SLURM_LOCALID"]) + + @override + def node_rank(self) -> int: + return int(os.environ["SLURM_NODEID"]) + + @override + def validate_settings(self, num_devices: int, num_nodes: int) -> None: + if _is_slurm_interactive_mode(): + return + ntasks_per_node = os.environ.get("SLURM_NTASKS_PER_NODE") + if ntasks_per_node is not None and int(ntasks_per_node) != num_devices: + raise ValueError( + f"You set `devices={num_devices}` in Lightning, but the number of tasks per node configured in SLURM" + f" `--ntasks-per-node={ntasks_per_node}` does not match. HINT: Set `devices={ntasks_per_node}`." + ) + nnodes = os.environ.get("SLURM_NNODES") + if nnodes is not None and int(nnodes) != num_nodes: + raise ValueError( + f"You set `num_nodes={num_nodes}` in Lightning, but the number of nodes configured in SLURM" + f" `--nodes={nnodes}` does not match. HINT: Set `num_nodes={nnodes}`." + ) + + @staticmethod + def resolve_root_node_address(nodes: str) -> str: + """The node selection format in SLURM supports several formats. + + This function selects the first host name from + + - a space-separated list of host names, e.g., 'host0 host1 host3' yields 'host0' as the root + - a comma-separated list of host names, e.g., 'host0,host1,host3' yields 'host0' as the root + - the range notation with brackets, e.g., 'host[5-9]' yields 'host5' as the root + + """ + nodes = re.sub(r"\[(.*?)[,-].*\]", "\\1", nodes) # Take the first node of every node range + nodes = re.sub(r"\[(.*?)\]", "\\1", nodes) # handle special case where node range is single number + return nodes.split(" ")[0].split(",")[0] + + @staticmethod + def _validate_srun_used() -> None: + """Checks if the `srun` command is available and used. + + Parallel jobs (multi-GPU, multi-node) in SLURM are launched by prepending `srun` in front of the Python command. + Not doing so will result in processes hanging, which is a frequent user error. Lightning will emit a warning if + `srun` is found but not used. + + """ + if _IS_WINDOWS: + return + + srun_exists = shutil.which("srun") is not None + if srun_exists and not _is_srun_used(): + hint = " ".join(["srun", os.path.basename(sys.executable), *sys.argv])[:64] + rank_zero_warn( + "The `srun` command is available on your system but is not used. HINT: If your intention is to run" + f" Lightning on SLURM, prepend your python command with `srun` like so: {hint} ...", + category=PossibleUserWarning, + ) + + @staticmethod + def _validate_srun_variables() -> None: + """Checks for conflicting or incorrectly set variables set through `srun` and raises a useful error message. + + Right now, we only check for the most common user errors. See + `the srun docs `_ + for a complete list of supported srun variables. + + """ + ntasks = int(os.environ.get("SLURM_NTASKS", "1")) + if ntasks > 1 and "SLURM_NTASKS_PER_NODE" not in os.environ: + raise RuntimeError( + f"You set `--ntasks={ntasks}` in your SLURM bash script, but this variable is not supported." + f" HINT: Use `--ntasks-per-node={ntasks}` instead." + ) + + +def _is_srun_used() -> bool: + return "SLURM_NTASKS" in os.environ and not _is_slurm_interactive_mode() + + +def _is_slurm_interactive_mode() -> bool: + return SLURMEnvironment.job_name() in ("bash", "interactive") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/torchelastic.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/torchelastic.py new file mode 100644 index 0000000000000000000000000000000000000000..a1845e5f3746fb60d0843fd7fb5875a046b4f214 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/torchelastic.py @@ -0,0 +1,93 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import os + +import torch.distributed +from typing_extensions import override + +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment +from lightning_fabric.utilities.rank_zero import rank_zero_warn + +log = logging.getLogger(__name__) + + +class TorchElasticEnvironment(ClusterEnvironment): + """Environment for fault-tolerant and elastic training with `torchelastic `_""" + + @property + @override + def creates_processes_externally(self) -> bool: + return True + + @property + @override + def main_address(self) -> str: + if "MASTER_ADDR" not in os.environ: + rank_zero_warn("MASTER_ADDR environment variable is not defined. Set as localhost") + os.environ["MASTER_ADDR"] = "127.0.0.1" + log.debug(f"MASTER_ADDR: {os.environ['MASTER_ADDR']}") + return os.environ["MASTER_ADDR"] + + @property + @override + def main_port(self) -> int: + if "MASTER_PORT" not in os.environ: + rank_zero_warn("MASTER_PORT environment variable is not defined. Set as 12910") + os.environ["MASTER_PORT"] = "12910" + log.debug(f"MASTER_PORT: {os.environ['MASTER_PORT']}") + + return int(os.environ["MASTER_PORT"]) + + @staticmethod + @override + def detect() -> bool: + """Returns ``True`` if the current process was launched using the torchelastic command.""" + # if not available (for example on MacOS), `is_torchelastic_launched` is not defined + return torch.distributed.is_available() and torch.distributed.is_torchelastic_launched() + + @override + def world_size(self) -> int: + return int(os.environ["WORLD_SIZE"]) + + @override + def set_world_size(self, size: int) -> None: + log.debug("TorchElasticEnvironment.set_world_size was called, but setting world size is not allowed. Ignored.") + + @override + def global_rank(self) -> int: + return int(os.environ["RANK"]) + + @override + def set_global_rank(self, rank: int) -> None: + log.debug( + "TorchElasticEnvironment.set_global_rank was called, but setting global rank is not allowed. Ignored." + ) + + @override + def local_rank(self) -> int: + return int(os.environ["LOCAL_RANK"]) + + @override + def node_rank(self) -> int: + return int(os.environ.get("GROUP_RANK", 0)) + + @override + def validate_settings(self, num_devices: int, num_nodes: int) -> None: + if num_devices * num_nodes != self.world_size(): + raise ValueError( + f"You set `devices={num_devices}` and `num_nodes={num_nodes}` in Lightning, but the product" + f" ({num_devices} * {num_nodes}) does not match the world size ({self.world_size()})." + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/xla.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/xla.py new file mode 100644 index 0000000000000000000000000000000000000000..72ba27b0291338553a2be0ed39b0e02662995bbe --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/environments/xla.py @@ -0,0 +1,135 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import functools +import logging +from typing import Any + +from typing_extensions import override + +from lightning_fabric.accelerators.xla import _XLA_AVAILABLE, _XLA_GREATER_EQUAL_2_1, XLAAccelerator +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment + +log = logging.getLogger(__name__) + + +class XLAEnvironment(ClusterEnvironment): + """Cluster environment for training on a TPU Pod with the `PyTorch/XLA `_ library. + + A list of environment variables set by XLA can be found + `here `_. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + if not _XLA_AVAILABLE: + raise ModuleNotFoundError(str(_XLA_AVAILABLE)) + super().__init__(*args, **kwargs) + + @property + @override + def creates_processes_externally(self) -> bool: + return False + + @property + @override + def main_address(self) -> str: + # unused by lightning + raise NotImplementedError + + @property + @override + def main_port(self) -> int: + # unused by lightning + raise NotImplementedError + + @staticmethod + @override + def detect() -> bool: + return XLAAccelerator.is_available() + + @override + @functools.lru_cache(maxsize=1) + def world_size(self) -> int: + """The number of processes across all devices and hosts. + + The output is cached for performance. + + """ + if _XLA_GREATER_EQUAL_2_1: + from torch_xla import runtime as xr + + return xr.world_size() + + import torch_xla.core.xla_model as xm + + return xm.xrt_world_size() + + @override + def set_world_size(self, size: int) -> None: + log.debug("XLAEnvironment.set_world_size was called, but setting world size is not allowed. Ignored.") + + @override + @functools.lru_cache(maxsize=1) + def global_rank(self) -> int: + """The rank (index) of the currently running process across all host and devices. + + The output is cached for performance. + + """ + if _XLA_GREATER_EQUAL_2_1: + from torch_xla import runtime as xr + + return xr.global_ordinal() + + import torch_xla.core.xla_model as xm + + return xm.get_ordinal() + + @override + def set_global_rank(self, rank: int) -> None: + log.debug("XLAEnvironment.set_global_rank was called, but setting global rank is not allowed. Ignored.") + + @override + @functools.lru_cache(maxsize=1) + def local_rank(self) -> int: + """The rank (index) of the currently running process inside of the current host. + + The output is cached for performance. + + """ + if _XLA_GREATER_EQUAL_2_1: + from torch_xla import runtime as xr + + return xr.local_ordinal() + + import torch_xla.core.xla_model as xm + + return xm.get_local_ordinal() + + @override + @functools.lru_cache(maxsize=1) + def node_rank(self) -> int: + """The rank (index) of the host on which the current process runs. + + The output is cached for performance. + + """ + if _XLA_GREATER_EQUAL_2_1: + from torch_xla import runtime as xr + + return xr.host_index() + import torch_xla.core.xla_env_vars as xenv + from torch_xla.utils.utils import getenv_as + + return getenv_as(xenv.HOST_ORDINAL, int, 0) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..413cdf2b5a1d77adfe8010d66d9da4af3ca40a3c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__init__.py @@ -0,0 +1,18 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from lightning_fabric.plugins.io.checkpoint_io import CheckpointIO +from lightning_fabric.plugins.io.torch_io import TorchCheckpointIO +from lightning_fabric.plugins.io.xla import XLACheckpointIO + +__all__ = ["CheckpointIO", "TorchCheckpointIO", "XLACheckpointIO"] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6683fa4a4c9e74a61ce9027dc67e41065c9c1212 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/checkpoint_io.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/checkpoint_io.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22f0a228257d7de6b68ffd12e46c56493e6401e2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/checkpoint_io.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/torch_io.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/torch_io.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c87d72a4fba21390b2444b42e60e3f987192210e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/torch_io.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/xla.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/xla.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b885e36e60a19471b50d4ba135a4b37e8fbe4cc Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/__pycache__/xla.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/checkpoint_io.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/checkpoint_io.py new file mode 100644 index 0000000000000000000000000000000000000000..3f69773656a0283d9d39d78c1b94c521e3a049eb --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/checkpoint_io.py @@ -0,0 +1,79 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from abc import ABC, abstractmethod +from typing import Any, Optional + +from lightning_fabric.utilities.types import _PATH + + +class CheckpointIO(ABC): + """Interface to save/load checkpoints as they are saved through the ``Strategy``. + + .. warning:: This is an :ref:`experimental ` feature. + + Typically most plugins either use the Torch based IO Plugin; ``TorchCheckpointIO`` but may + require particular handling depending on the plugin. + + In addition, you can pass a custom ``CheckpointIO`` by extending this class and passing it + to the Trainer, i.e ``Trainer(plugins=[MyCustomCheckpointIO()])``. + + .. note:: + + For some plugins, it is not possible to use a custom checkpoint plugin as checkpointing logic is not + modifiable. + + """ + + @abstractmethod + def save_checkpoint(self, checkpoint: dict[str, Any], path: _PATH, storage_options: Optional[Any] = None) -> None: + """Save model/training states as a checkpoint file through state-dump and file-write. + + Args: + checkpoint: dict containing model and trainer state + path: write-target path + storage_options: Optional parameters when saving the model/training states. + + """ + + @abstractmethod + def load_checkpoint( + self, path: _PATH, map_location: Optional[Any] = None, weights_only: Optional[bool] = None + ) -> dict[str, Any]: + """Load checkpoint from a path when resuming or loading ckpt for test/validate/predict stages. + + Args: + path: Path to checkpoint + map_location: a function, :class:`torch.device`, string or a dict specifying how to remap storage + locations. + weights_only: Defaults to ``None``. If ``True``, restricts loading to ``state_dicts`` of plain + ``torch.Tensor`` and other primitive types. If loading a checkpoint from a trusted source that contains + an ``nn.Module``, use ``weights_only=False``. If loading checkpoint from an untrusted source, we + recommend using ``weights_only=True``. For more information, please refer to the + `PyTorch Developer Notes on Serialization Semantics `_. + + Returns: The loaded checkpoint. + + """ + + @abstractmethod + def remove_checkpoint(self, path: _PATH) -> None: + """Remove checkpoint file from the filesystem. + + Args: + path: Path to checkpoint + + """ + + def teardown(self) -> None: + """This method is called to teardown the process.""" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/torch_io.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/torch_io.py new file mode 100644 index 0000000000000000000000000000000000000000..b5063608ec29e4e14a4b2610196477982a22a71f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/torch_io.py @@ -0,0 +1,104 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import logging +import os +from typing import Any, Callable, Optional + +from typing_extensions import override + +from lightning_fabric.plugins.io.checkpoint_io import CheckpointIO +from lightning_fabric.utilities.cloud_io import _atomic_save, get_filesystem +from lightning_fabric.utilities.cloud_io import _load as pl_load +from lightning_fabric.utilities.types import _PATH + +log = logging.getLogger(__name__) + + +class TorchCheckpointIO(CheckpointIO): + """CheckpointIO that utilizes :func:`torch.save` and :func:`torch.load` to save and load checkpoints respectively, + common for most use cases. + + .. warning:: This is an :ref:`experimental ` feature. + + """ + + @override + def save_checkpoint(self, checkpoint: dict[str, Any], path: _PATH, storage_options: Optional[Any] = None) -> None: + """Save model/training states as a checkpoint file through state-dump and file-write. + + Args: + checkpoint: dict containing model and trainer state + path: write-target path + storage_options: not used in ``TorchCheckpointIO.save_checkpoint`` + + Raises: + TypeError: + If ``storage_options`` arg is passed in + + """ + if storage_options is not None: + raise TypeError( + "`Trainer.save_checkpoint(..., storage_options=...)` with `storage_options` arg" + f" is not supported for `{self.__class__.__name__}`. Please implement your custom `CheckpointIO`" + " to define how you'd like to use `storage_options`." + ) + fs = get_filesystem(path) + fs.makedirs(os.path.dirname(path), exist_ok=True) + _atomic_save(checkpoint, path) + + @override + def load_checkpoint( + self, + path: _PATH, + map_location: Optional[Callable] = lambda storage, loc: storage, + weights_only: Optional[bool] = None, + ) -> dict[str, Any]: + """Loads checkpoint using :func:`torch.load`, with additional handling for ``fsspec`` remote loading of files. + + Args: + path: Path to checkpoint + map_location: a function, :class:`torch.device`, string or a dict specifying how to remap storage + locations. + weights_only: Defaults to ``None``. If ``True``, restricts loading to ``state_dicts`` of plain + ``torch.Tensor`` and other primitive types. If loading a checkpoint from a trusted source that contains + an ``nn.Module``, use ``weights_only=False``. If loading checkpoint from an untrusted source, we + recommend using ``weights_only=True``. For more information, please refer to the + `PyTorch Developer Notes on Serialization Semantics `_. + + Returns: The loaded checkpoint. + + Raises: + FileNotFoundError: If ``path`` is not found by the ``fsspec`` filesystem + + """ + + # Try to read the checkpoint at `path`. If not exist, do not restore checkpoint. + fs = get_filesystem(path) + if not fs.exists(path): + raise FileNotFoundError(f"Checkpoint file not found: {path}") + + return pl_load(path, map_location=map_location, weights_only=weights_only) + + @override + def remove_checkpoint(self, path: _PATH) -> None: + """Remove checkpoint file from the filesystem. + + Args: + path: Path to checkpoint + + """ + fs = get_filesystem(path) + if fs.exists(path): + fs.rm(path, recursive=True) + log.debug(f"Removed checkpoint: {path}") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/xla.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/xla.py new file mode 100644 index 0000000000000000000000000000000000000000..455a3c43a5ab48fec0c8ef03d57bf2dd30e80606 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/io/xla.py @@ -0,0 +1,74 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import logging +import os +from typing import Any, Optional + +import torch +from lightning_utilities.core.apply_func import apply_to_collection +from lightning_utilities.core.imports import RequirementCache +from typing_extensions import override + +from lightning_fabric.accelerators.xla import _XLA_AVAILABLE +from lightning_fabric.plugins.io.torch_io import TorchCheckpointIO +from lightning_fabric.utilities.cloud_io import get_filesystem +from lightning_fabric.utilities.types import _PATH + +log = logging.getLogger(__name__) + + +class XLACheckpointIO(TorchCheckpointIO): + """CheckpointIO that utilizes ``xm.save`` to save checkpoints for TPU training strategies. + + .. warning:: This is an :ref:`experimental ` feature. + + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + if not _XLA_AVAILABLE: + raise ModuleNotFoundError(str(_XLA_AVAILABLE)) + super().__init__(*args, **kwargs) + + @override + def save_checkpoint(self, checkpoint: dict[str, Any], path: _PATH, storage_options: Optional[Any] = None) -> None: + """Save model/training states as a checkpoint file through state-dump and file-write. + + Args: + checkpoint: dict containing model and trainer state + path: write-target path + storage_options: not used in ``XLACheckpointIO.save_checkpoint`` + + Raises: + TypeError: + If ``storage_options`` arg is passed in + + """ + if storage_options is not None: + raise TypeError( + "`Trainer.save_checkpoint(..., storage_options=...)` with `storage_options` arg" + f" is not supported for `{self.__class__.__name__}`. Please implement your custom `CheckpointIO`" + " to define how you'd like to use `storage_options`." + ) + fs = get_filesystem(path) + fs.makedirs(os.path.dirname(path), exist_ok=True) + if RequirementCache("omegaconf"): + # workaround for https://github.com/pytorch/xla/issues/2773 + from omegaconf import DictConfig, ListConfig, OmegaConf + + checkpoint = apply_to_collection(checkpoint, (DictConfig, ListConfig), OmegaConf.to_container) + import torch_xla.core.xla_model as xm + + cpu_data = xm._maybe_convert_to_cpu(checkpoint, convert=True) + log.debug(f"Saving checkpoint: {path}") + torch.save(cpu_data, path) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee9ae099dff6d898658b9f125ed6ac1b9b38cb09 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__init__.py @@ -0,0 +1,34 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from lightning_fabric.plugins.precision.amp import MixedPrecision +from lightning_fabric.plugins.precision.bitsandbytes import BitsandbytesPrecision +from lightning_fabric.plugins.precision.deepspeed import DeepSpeedPrecision +from lightning_fabric.plugins.precision.double import DoublePrecision +from lightning_fabric.plugins.precision.fsdp import FSDPPrecision +from lightning_fabric.plugins.precision.half import HalfPrecision +from lightning_fabric.plugins.precision.precision import Precision +from lightning_fabric.plugins.precision.transformer_engine import TransformerEnginePrecision +from lightning_fabric.plugins.precision.xla import XLAPrecision + +__all__ = [ + "BitsandbytesPrecision", + "DeepSpeedPrecision", + "DoublePrecision", + "HalfPrecision", + "MixedPrecision", + "Precision", + "XLAPrecision", + "FSDPPrecision", + "TransformerEnginePrecision", +] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7049970dc11df771d3446f2b0b3748e94a249a58 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/amp.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/amp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c74ee6c74518de05be746a3734fa8efe0d031802 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/amp.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/bitsandbytes.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/bitsandbytes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1545d7476d30f79ffa5b877643aceae4ed7ce941 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/bitsandbytes.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/deepspeed.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/deepspeed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69997dfd8bbd2293b3c3d3a9d6ebe5f79e5c8608 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/deepspeed.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/double.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/double.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f58e247ff1a23c23eea1a35b98c92204ba950ce Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/double.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/fsdp.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/fsdp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..603becea657f3e5e6835a624e91a6c37fc2bca62 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/fsdp.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/half.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/half.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0c06d2379dd151a710d76f3a92d2708da08dcb2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/half.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/precision.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/precision.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76640cf264ab9b839b1d9b0d809aeb09793fc94e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/precision.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/transformer_engine.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/transformer_engine.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b6b95d39187991c2b3b724322354e4e1b853873 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/transformer_engine.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/utils.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b26d308852dac7fba0382fab4cb9eadf31e4d881 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/utils.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/xla.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/xla.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf3d0051a04774b75eedbd14fb028febb56f6d7b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/__pycache__/xla.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/amp.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/amp.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc6fd674b0008cc881a6002d65cbe0028ee9fda --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/amp.py @@ -0,0 +1,124 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from contextlib import AbstractContextManager +from typing import Any, Literal, Optional + +import torch +from lightning_utilities.core.apply_func import apply_to_collection +from torch import Tensor +from torch.nn import Module +from torch.optim import LBFGS, Optimizer +from typing_extensions import override + +from lightning_fabric.plugins.precision.precision import Precision +from lightning_fabric.plugins.precision.utils import _convert_fp_tensor +from lightning_fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_4 +from lightning_fabric.utilities.types import Optimizable + + +class MixedPrecision(Precision): + """Plugin for Automatic Mixed Precision (AMP) training with ``torch.autocast``. + + Args: + precision: Whether to use ``torch.float16`` (``'16-mixed'``) or ``torch.bfloat16`` (``'bf16-mixed'``). + device: The device for ``torch.autocast``. + scaler: An optional :class:`torch.cuda.amp.GradScaler` to use. + + """ + + def __init__( + self, + precision: Literal["16-mixed", "bf16-mixed"], + device: str, + scaler: Optional["torch.amp.GradScaler"] = None, + ) -> None: + if precision not in ("16-mixed", "bf16-mixed"): + raise ValueError( + f"Passed `{type(self).__name__}(precision={precision!r})`." + " Precision must be '16-mixed' or 'bf16-mixed'." + ) + + self.precision = precision + if scaler is None and self.precision == "16-mixed": + scaler = torch.amp.GradScaler(device=device) if _TORCH_GREATER_EQUAL_2_4 else torch.cuda.amp.GradScaler() + if scaler is not None and self.precision == "bf16-mixed": + raise ValueError(f"`precision='bf16-mixed'` does not use a scaler, found {scaler}.") + self.device = device + self.scaler = scaler + + self._desired_input_dtype = torch.bfloat16 if self.precision == "bf16-mixed" else torch.float16 + + @override + def forward_context(self) -> AbstractContextManager: + return torch.autocast(self.device, dtype=self._desired_input_dtype) + + @override + def convert_input(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=self._desired_input_dtype) + + @override + def convert_output(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.get_default_dtype()) + + @override + def backward(self, tensor: Tensor, model: Optional[Module], *args: Any, **kwargs: Any) -> None: + if self.scaler is not None: + tensor = self.scaler.scale(tensor) + super().backward(tensor, model, *args, **kwargs) + + @override + def optimizer_step( + self, + optimizer: Optimizable, + **kwargs: Any, + ) -> Any: + if self.scaler is None: + # skip scaler logic, as bfloat16 does not require scaler + return super().optimizer_step(optimizer, **kwargs) + if isinstance(optimizer, LBFGS): + raise TypeError("AMP and the LBFGS optimizer are not compatible.") + # note: the scaler will skip the `optimizer.step` if nonfinite gradients are found + step_output = self.scaler.step(optimizer, **kwargs) # type: ignore[arg-type] + self.scaler.update() + return step_output + + @override + def state_dict(self) -> dict[str, Any]: + if self.scaler is not None: + return self.scaler.state_dict() + return {} + + @override + def load_state_dict(self, state_dict: dict[str, Any]) -> None: + if self.scaler is not None: + self.scaler.load_state_dict(state_dict) + + @override + def unscale_gradients(self, optimizer: Optimizer) -> None: + scaler = self.scaler + if scaler is not None: + if _optimizer_handles_unscaling(optimizer): + raise NotImplementedError("Gradient clipping is not implemented for optimizers handling the unscaling.") + scaler.unscale_(optimizer) + + +def _optimizer_handles_unscaling(optimizer: Any) -> bool: + """Determines whether a PyTorch optimizer handles unscaling gradients in the step method rather than through the + :class:`torch.cuda.amp.GradScaler`. + + Since, the current implementation of this function checks a PyTorch internal variable on the optimizer, the return + value will only be reliable for built-in PyTorch optimizers. + + """ + return getattr(optimizer, "_step_supports_amp_scaling", False) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/bitsandbytes.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/bitsandbytes.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8f2ae6b194a816424b41c1f73b07208dbb6581 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/bitsandbytes.py @@ -0,0 +1,448 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import functools +import logging +import math +import os +import warnings +from collections import OrderedDict +from contextlib import AbstractContextManager, ExitStack +from functools import partial +from types import ModuleType +from typing import Any, Callable, Literal, Optional, cast + +import torch +from lightning_utilities import apply_to_collection +from lightning_utilities.core.imports import RequirementCache +from torch import Tensor +from torch.nn import init +from torch.nn.modules.module import _IncompatibleKeys +from typing_extensions import Self, override + +from lightning_fabric.plugins.precision.precision import Precision +from lightning_fabric.plugins.precision.utils import ( + _ClassReplacementContextManager, + _convert_fp_tensor, + _DtypeContextManager, +) +from lightning_fabric.utilities.types import _DEVICE + +log = logging.getLogger(__name__) + +_BITSANDBYTES_AVAILABLE = RequirementCache("bitsandbytes") + + +class BitsandbytesPrecision(Precision): + """Plugin for quantizing weights with `bitsandbytes `__. + + .. warning:: This is an :ref:`experimental ` feature. + + .. note:: + The optimizer is not automatically replaced with ``bitsandbytes.optim.Adam8bit`` or equivalent 8-bit optimizers. + + Args: + mode: The quantization mode to use. + dtype: The compute dtype to use. + ignore_modules: The submodules whose Linear layers should not be replaced, for example. ``{"lm_head"}``. + This might be desirable for numerical stability. The string will be checked in as a prefix, so a value like + "transformer.blocks" will ignore all linear layers in all of the transformer blocks. + """ + + # Note: you'll notice that the `precision` str class attribute is not defined. This is on purpose because there are + # many configuration options so `precision="bitsandbytes"` would be ambiguous about which one to use. Additionally, + # it would create backwards compatibility challenges if better modes or dtypes are added in the future + + # TODO: we could implement optimizer replacement with + # - Fabric: Add `Precision.convert_optimizer` from `Strategy.setup_optimizer` + # - Trainer: Use `Precision.connect` + + def __init__( + self, + mode: Literal["nf4", "nf4-dq", "fp4", "fp4-dq", "int8", "int8-training"], + dtype: Optional[torch.dtype] = None, + ignore_modules: Optional[set[str]] = None, + ) -> None: + _import_bitsandbytes() + + if dtype is None: + # try to be smart about the default selection + if mode.startswith("int8"): + dtype = torch.float16 + else: + dtype = ( + torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else torch.float16 + ) + if mode.startswith("int8") and dtype is not torch.float16: + # this limitation is mentioned in https://huggingface.co/blog/hf-bitsandbytes-integration#usage + raise ValueError(f"{mode!r} only works with `dtype=torch.float16`, but you chose `{dtype}`") + + globals_ = globals() + mode_to_cls = { + "nf4": globals_["_NF4Linear"], + "nf4-dq": globals_["_NF4DQLinear"], + "fp4": globals_["_FP4Linear"], + "fp4-dq": globals_["_FP4DQLinear"], + "int8-training": globals_["_Linear8bitLt"], + "int8": globals_["_Int8LinearInference"], + } + self._linear_cls = mode_to_cls[mode] + self.dtype = dtype + self.ignore_modules = ignore_modules or set() + + @override + def convert_module(self, module: torch.nn.Module) -> torch.nn.Module: + # avoid naive users thinking they quantized their model + if not any(isinstance(m, torch.nn.Linear) for m in module.modules()): + raise TypeError( + "You are using the bitsandbytes precision plugin, but your model has no Linear layers. This plugin" + " won't work for your model." + ) + + # convert modules if they haven't been converted already + bnb = _import_bitsandbytes() + if not any(isinstance(m, (bnb.nn.Linear8bitLt, bnb.nn.Linear4bit)) for m in module.modules()): + # this will not quantize the model but only replace the layer classes + _convert_layers(module, self._linear_cls, self.ignore_modules) + + # set the compute dtype if necessary + for m in module.modules(): + if isinstance(m, bnb.nn.Linear4bit): + m.compute_dtype = self.dtype + m.compute_type_is_set = False + return module + + @override + def tensor_init_context(self) -> AbstractContextManager: + return _DtypeContextManager(self.dtype) + + @override + def module_init_context(self) -> AbstractContextManager: + if self.ignore_modules: + # cannot patch the Linear class if the user wants to skip some submodules + raise RuntimeError( + "Instantiating your model under the `init_module` context manager is not supported when used with" + f" `BitsandbytesPrecision(..., ignore_modules={self.ignore_modules})` as this" + " may initialize the layers on-device, defeating the purpose of quantization. You can remove" + " `ignore_modules` or remove the `init_module` context manager." + ) + dtype_ctx = self.tensor_init_context() + # TODO: this could also support replacing `Embedding` and `Conv1D` + context_manager = _ClassReplacementContextManager({"torch.nn.Linear": self._linear_cls}) + stack = ExitStack() + stack.enter_context(dtype_ctx) + stack.enter_context(context_manager) + return stack + + @override + def forward_context(self) -> AbstractContextManager: + return _DtypeContextManager(self.dtype) + + @override + def convert_input(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=self.dtype) + + @override + def convert_output(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.get_default_dtype()) + + +def _quantize_on_load_hook(quantize_fn: Callable[[torch.Tensor], None], state_dict: OrderedDict, *_: Any) -> None: + # There is only one key that ends with `*.weight`, the other one is the bias + weight_key = next((name for name in state_dict if name.endswith("weight")), None) + if weight_key is None: + return + # Load the weight from the state dict and re-quantize it + weight = state_dict.pop(weight_key) + quantize_fn(weight) + + +def _ignore_missing_weights_hook(module: torch.nn.Module, incompatible_keys: _IncompatibleKeys) -> None: + # since we manually loaded the weight in the `_quantize_on_load_hook` hook, we need to avoid this missing key false + # positive + for key in reversed(incompatible_keys.missing_keys): + if key.endswith("weight"): + incompatible_keys.missing_keys.remove(key) + + +def _replace_param( + param: torch.nn.Parameter, data: torch.Tensor, quant_state: Optional[tuple] = None +) -> torch.nn.Parameter: + bnb = _import_bitsandbytes() + + # doing `param.data = weight` raises a RuntimeError if param.data was on meta-device, so + # we need to re-create the parameters instead of overwriting the data + if param.device.type == "meta": + if isinstance(param, bnb.nn.Params4bit): + return bnb.nn.Params4bit( + data=data, + requires_grad=data.requires_grad, + quant_state=quant_state, + blocksize=param.blocksize, + compress_statistics=param.compress_statistics, + quant_type=param.quant_type, + quant_storage=param.quant_storage, + module=param.module, + bnb_quantized=param.bnb_quantized, + ) + return torch.nn.Parameter(data, requires_grad=data.requires_grad) + param.data = data + if isinstance(param, bnb.nn.Params4bit): + param.quant_state = quant_state + return param + + +@functools.lru_cache(maxsize=1) +def _import_bitsandbytes() -> ModuleType: + if not _BITSANDBYTES_AVAILABLE: + raise ModuleNotFoundError(str(_BITSANDBYTES_AVAILABLE)) + # configuration for bitsandbytes before import + nowelcome_set = "BITSANDBYTES_NOWELCOME" in os.environ + if not nowelcome_set: + os.environ["BITSANDBYTES_NOWELCOME"] = "1" + warnings.filterwarnings("ignore", message=r".*bitsandbytes was compiled without GPU support.*") + warnings.filterwarnings( + "ignore", message=r"MatMul8bitLt: inputs will be cast from .* to float16 during quantization" + ) + import bitsandbytes as bnb + + if not nowelcome_set: + del os.environ["BITSANDBYTES_NOWELCOME"] + + class _Linear8bitLt(bnb.nn.Linear8bitLt): + """Wraps `bnb.nn.Linear8bitLt` and enables instantiation directly on the device and re-quantizaton when loading + the state dict.""" + + def __init__(self, *args: Any, device: Optional[_DEVICE] = None, threshold: float = 6.0, **kwargs: Any) -> None: + super().__init__(*args, device=device, threshold=threshold, **kwargs) + self.weight = cast(bnb.nn.Int8Params, self.weight) # type: ignore[has-type] + self.bias: Optional[torch.nn.Parameter] = self.bias + # if the device is CUDA or we are under a CUDA context manager, quantize the weight here, so we don't end up + # filling the device memory with float32 weights which could lead to OOM + if torch.tensor(0, device=device).device.type == "cuda": + self.quantize_() + self._register_load_state_dict_pre_hook(partial(_quantize_on_load_hook, self.quantize_)) + self.register_load_state_dict_post_hook(_ignore_missing_weights_hook) + + def quantize_(self, weight: Optional[torch.Tensor] = None, device: Optional[torch.device] = None) -> None: + """Inplace quantize.""" + if weight is None: + weight = self.weight.data + if weight.data.dtype == torch.int8: + # already quantized + return + assert isinstance(self.weight, bnb.nn.Int8Params) + self.weight = self.quantize(self.weight, weight, device) + + @staticmethod + def quantize( + int8params: bnb.nn.Int8Params, weight: torch.Tensor, device: Optional[torch.device] + ) -> bnb.nn.Int8Params: + device = device or torch.device("cuda") + if device.type != "cuda": + raise RuntimeError(f"Unexpected device type: {device.type}") + # https://github.com/TimDettmers/bitsandbytes/blob/0.41.0/bitsandbytes/nn/modules.py#L291-L302 + B = weight.contiguous().to(device=device, dtype=torch.float16) + if int8params.has_fp16_weights: + int8params.data = B + else: + # bitsandbytes >= 0.45 supports an improved API + if hasattr(bnb.functional, "int8_vectorwise_quant"): + CB, SCB, _ = bnb.functional.int8_vectorwise_quant(B) + else: # old method is deprecated in 0.45, removed in 0.46+. + CB, _, SCB, _, _ = bnb.functional.double_quant(B) + + int8params.data = CB + setattr(int8params, "CB", CB) + setattr(int8params, "SCB", SCB) + return int8params + + def to_empty(self, *, device: _DEVICE, recurse: bool = True) -> Self: + if self.weight.device.type == "meta": + # need custom logic if int8params is on meta device + raise NotImplementedError + if self.weight.dtype == torch.uint8: # was quantized + # need the original shape here + raise NotImplementedError + device = torch.device(device) + weight = torch.empty_like(self.weight.data, device=device) + if device.type == "cuda": # re-quantize + self.quantize_(weight, device) + else: + self.weight = _replace_param(self.weight, weight) + if self.bias is not None: + self.bias = _replace_param(self.bias, torch.empty_like(self.bias, device=device)) + return self + + def reset_parameters(self) -> None: + # from `torch.nn.Linear.reset_parameters` + if self.bias is not None: + fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(self.weight) + bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0 + init.uniform_(self.bias, -bound, bound) + + linear_init_finished = isinstance(self.weight, bnb.nn.Params4bit) + if linear_init_finished and self.weight.dtype == torch.uint8: # was quantized + # need the original shape here + raise NotImplementedError + weight = self.weight.data + torch.nn.init.kaiming_uniform_(weight, a=math.sqrt(5)) + if linear_init_finished: + if self.weight.device.type == "meta": + # need custom logic if int8params is on meta device + raise NotImplementedError + if self.weight.device.type == "cuda": # re-quantize + self.quantize_(weight) + else: + self.weight = _replace_param(self.weight, weight) + + class _Linear4bit(bnb.nn.Linear4bit): + """Wraps `bnb.nn.Linear4bit` to enable: instantiation directly on the device, re-quantizaton when loading the + state dict, meta-device initialization, and materialization.""" + + def __init__(self, *args: Any, device: Optional[_DEVICE] = None, **kwargs: Any) -> None: + super().__init__(*args, device=device, **kwargs) + self.weight = cast(bnb.nn.Params4bit, self.weight) # type: ignore[has-type] + self.bias: Optional[torch.nn.Parameter] = self.bias + # if the device is CUDA or we are under a CUDA context manager, quantize the weight here, so we don't end up + # filling the device memory with float32 weights which could lead to OOM + if torch.tensor(0, device=device).device.type == "cuda": + self.quantize_() + self._register_load_state_dict_pre_hook(partial(_quantize_on_load_hook, self.quantize_)) + self.register_load_state_dict_post_hook(_ignore_missing_weights_hook) + + def quantize_(self, weight: Optional[torch.Tensor] = None, device: Optional[torch.device] = None) -> None: + """Inplace quantize.""" + if weight is None: + weight = self.weight.data + if weight.data.dtype == torch.uint8: + # already quantized + return + assert isinstance(self.weight, bnb.nn.Params4bit) + self.weight = self.quantize(self.weight, weight, device) + self.weight.bnb_quantized = True + + @staticmethod + def quantize( + params4bit: bnb.nn.Params4bit, weight: torch.Tensor, device: Optional[torch.device] + ) -> bnb.nn.Params4bit: + device = device or torch.device("cuda") + if device.type != "cuda": + raise RuntimeError(f"Unexpected device type: {device.type}") + # https://github.com/TimDettmers/bitsandbytes/blob/0.41.0/bitsandbytes/nn/modules.py#L156-L159 + w = weight.contiguous().to(device=device, dtype=torch.half) + w_4bit, quant_state = bnb.functional.quantize_4bit( + w, + blocksize=params4bit.blocksize, + compress_statistics=params4bit.compress_statistics, + quant_type=params4bit.quant_type, + quant_storage=params4bit.quant_storage, + ) + return _replace_param(params4bit, w_4bit, quant_state) + + def to_empty(self, *, device: _DEVICE, recurse: bool = True) -> Self: + if self.weight.dtype == torch.uint8: # was quantized + # cannot init the quantized params directly + weight = torch.empty(self.weight.quant_state.shape, device=device, dtype=torch.half) + else: + weight = torch.empty_like(self.weight.data, device=device) + device = torch.device(device) + if device.type == "cuda": # re-quantize + self.quantize_(weight, device) + else: + self.weight = _replace_param(self.weight, weight) + if self.bias is not None: + self.bias = _replace_param(self.bias, torch.empty_like(self.bias, device=device)) + return self + + def reset_parameters(self) -> None: + # from `torch.nn.Linear.reset_parameters` + if self.bias is not None: + fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(self.weight) + bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0 + init.uniform_(self.bias, -bound, bound) + + linear_init_finished = isinstance(self.weight, bnb.nn.Params4bit) + if linear_init_finished and self.weight.dtype == torch.uint8: # was quantized + # cannot init the quantized params directly + weight = torch.empty(self.weight.quant_state.shape, device=self.weight.device, dtype=torch.half) + else: + weight = self.weight.data + torch.nn.init.kaiming_uniform_(weight, a=math.sqrt(5)) + if linear_init_finished: + if self.weight.device.type == "cuda": # re-quantize + self.quantize_(weight) + else: + self.weight = _replace_param(self.weight, weight) + + # Use a class instead `functools.partial` to respect `isinstance` checks and attribute accesses + class _Int8LinearInference(_Linear8bitLt): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, has_fp16_weights=False, **kwargs) + + class _FP4Linear(_Linear4bit): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, quant_type="fp4", compress_statistics=False, **kwargs) + + class _FP4DQLinear(_Linear4bit): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, quant_type="fp4", compress_statistics=True, **kwargs) + + class _NF4Linear(_Linear4bit): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, quant_type="nf4", compress_statistics=False, **kwargs) + + class _NF4DQLinear(_Linear4bit): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, quant_type="nf4", compress_statistics=True, **kwargs) + + # these classes are defined programmatically like this to avoid importing bitsandbytes in environments that have + # it available but will not use it + classes = { + "_Linear8bitLt": _Linear8bitLt, + "_Linear4bit": _Linear4bit, + "_Int8LinearInference": _Int8LinearInference, + "_FP4Linear": _FP4Linear, + "_FP4DQLinear": _FP4DQLinear, + "_NF4Linear": _NF4Linear, + "_NF4DQLinear": _NF4DQLinear, + } + globals().update(classes) + + return bnb + + +def _convert_layers(module: torch.nn.Module, linear_cls: type, ignore_modules: set[str], prefix: str = "") -> None: + for name, child in module.named_children(): + fullname = f"{prefix}.{name}" if prefix else name + if isinstance(child, torch.nn.Linear) and not any(fullname.startswith(s) for s in ignore_modules): + log.debug(f"Replacing layer {fullname!r} with bitsandbytes equivalent") + has_bias = child.bias is not None + # since we are going to copy over the child's data, the device doesn't matter. I chose CPU + # to avoid spiking CUDA memory even though initialization is slower + # 4bit layers support quantizing from meta-device params so this is only relevant for 8-bit + _Linear4bit = globals()["_Linear4bit"] + device = torch.device("meta" if issubclass(linear_cls, _Linear4bit) else "cpu") + replacement = linear_cls( + child.in_features, + child.out_features, + bias=has_bias, + device=device, + ) + if has_bias: + replacement.bias = _replace_param(replacement.bias, child.bias.data.clone()) + state = {"quant_state": replacement.weight.quant_state if issubclass(linear_cls, _Linear4bit) else None} + replacement.weight = _replace_param(replacement.weight, child.weight.data.clone(), **state) + module.__setattr__(name, replacement) + else: + _convert_layers(child, linear_cls, ignore_modules, prefix=fullname) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/deepspeed.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/deepspeed.py new file mode 100644 index 0000000000000000000000000000000000000000..67dc512b6a46a2c8f9fecb3202e2d9354580e018 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/deepspeed.py @@ -0,0 +1,100 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from contextlib import AbstractContextManager, nullcontext +from typing import TYPE_CHECKING, Any, Literal + +import torch +from lightning_utilities.core.apply_func import apply_to_collection +from torch import Tensor +from torch.nn import Module +from typing_extensions import get_args, override + +from lightning_fabric.plugins.precision.precision import Precision +from lightning_fabric.plugins.precision.utils import _convert_fp_tensor, _DtypeContextManager +from lightning_fabric.utilities.types import Steppable + +if TYPE_CHECKING: + from deepspeed import DeepSpeedEngine + +_PRECISION_INPUT = Literal["32-true", "16-true", "bf16-true", "16-mixed", "bf16-mixed"] + + +class DeepSpeedPrecision(Precision): + """Precision plugin for DeepSpeed integration. + + Args: + precision: Full precision (32-true), half precision (16-true, bf16-true) or + mixed precision (16-mixed, bf16-mixed). + + Raises: + ValueError: + If unsupported ``precision`` is provided. + + """ + + def __init__(self, precision: _PRECISION_INPUT) -> None: + supported_precision = get_args(_PRECISION_INPUT) + if precision not in supported_precision: + raise ValueError( + f"`precision={precision!r})` is not supported in DeepSpeed." + f" `precision` must be one of: {supported_precision}." + ) + self.precision = precision + + precision_to_type = { + "bf16-mixed": torch.bfloat16, + "16-mixed": torch.float16, + "bf16-true": torch.bfloat16, + "16-true": torch.float16, + "32-true": torch.float32, + } + self._desired_dtype = precision_to_type[self.precision] + + @override + def convert_module(self, module: Module) -> Module: + if "true" in self.precision: + return module.to(dtype=self._desired_dtype) + return module + + @override + def tensor_init_context(self) -> AbstractContextManager: + if "true" not in self.precision: + return nullcontext() + return _DtypeContextManager(self._desired_dtype) + + @override + def module_init_context(self) -> AbstractContextManager: + return self.tensor_init_context() + + @override + def convert_input(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=self._desired_dtype) + + @override + def convert_output(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.get_default_dtype()) + + @override + def backward(self, tensor: Tensor, model: "DeepSpeedEngine", *args: Any, **kwargs: Any) -> None: + """Performs back-propagation using DeepSpeed's engine.""" + model.backward(tensor, *args, **kwargs) + + @override + def optimizer_step( + self, + optimizer: Steppable, + **kwargs: Any, + ) -> Any: + # DeepSpeed handles the optimizer step internally + return optimizer.step(**kwargs) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/double.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/double.py new file mode 100644 index 0000000000000000000000000000000000000000..a06b15b1debeb139725d640b396a3ae555d219b0 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/double.py @@ -0,0 +1,54 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from contextlib import AbstractContextManager +from typing import Any, Literal + +import torch +from lightning_utilities.core.apply_func import apply_to_collection +from torch import Tensor +from torch.nn import Module +from typing_extensions import override + +from lightning_fabric.plugins.precision.precision import Precision +from lightning_fabric.plugins.precision.utils import _convert_fp_tensor, _DtypeContextManager + + +class DoublePrecision(Precision): + """Plugin for training with double (``torch.float64``) precision.""" + + precision: Literal["64-true"] = "64-true" + + @override + def convert_module(self, module: Module) -> Module: + return module.double() + + @override + def tensor_init_context(self) -> AbstractContextManager: + return _DtypeContextManager(torch.double) + + @override + def module_init_context(self) -> AbstractContextManager: + return self.tensor_init_context() + + @override + def forward_context(self) -> AbstractContextManager: + return self.tensor_init_context() + + @override + def convert_input(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.double) + + @override + def convert_output(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.get_default_dtype()) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/fsdp.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/fsdp.py new file mode 100644 index 0000000000000000000000000000000000000000..3323a9edce84c049faa86bbb4060774ba2050948 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/fsdp.py @@ -0,0 +1,168 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from contextlib import AbstractContextManager +from typing import TYPE_CHECKING, Any, Literal, Optional + +import torch +from lightning_utilities import apply_to_collection +from torch import Tensor +from torch.nn import Module +from torch.optim import Optimizer +from typing_extensions import get_args, override + +from lightning_fabric.plugins.precision.amp import _optimizer_handles_unscaling +from lightning_fabric.plugins.precision.precision import Precision +from lightning_fabric.plugins.precision.utils import _convert_fp_tensor, _DtypeContextManager +from lightning_fabric.utilities import rank_zero_warn +from lightning_fabric.utilities.types import Optimizable + +if TYPE_CHECKING: + from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision as TorchMixedPrecision + from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler + +_PRECISION_INPUT = Literal["32-true", "16-true", "bf16-true", "16-mixed", "bf16-mixed"] + + +class FSDPPrecision(Precision): + """Precision plugin for training with Fully Sharded Data Parallel (FSDP). + + .. warning:: This is an :ref:`experimental ` feature. + + Args: + precision: Full precision (32-true), half precision (16-true, bf16-true) or + mixed precision (16-mixed, bf16-mixed). + scaler: An optional :class:`torch.distributed.fsdp.sharded_grad_scaler.ShardedGradScaler` to use. + + Raises: + ValueError: + If unsupported ``precision`` is provided. + + """ + + def __init__(self, precision: _PRECISION_INPUT, scaler: Optional["ShardedGradScaler"] = None) -> None: + supported_precision = get_args(_PRECISION_INPUT) + if precision not in supported_precision: + raise ValueError( + f"`precision={precision!r})` is not supported in FSDP." + f" `precision` must be one of: {supported_precision}." + ) + + from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler + + if scaler is not None and self.precision != "16-mixed": + raise ValueError(f"`precision={precision!r}` does not use a scaler, found {scaler}.") + + self.scaler = ShardedGradScaler() if scaler is None and precision == "16-mixed" else None + self.precision = precision + + precision_to_type = { + "bf16-mixed": torch.float32, + "16-mixed": torch.float32, + "bf16-true": torch.bfloat16, + "16-true": torch.float16, + "32-true": torch.float32, + } + self._desired_input_dtype = precision_to_type[self.precision] + + @override + def convert_module(self, module: Module) -> Module: + if "true" in self.precision: + return module.to(dtype=self._desired_input_dtype) + return module + + @property + def mixed_precision_config(self) -> "TorchMixedPrecision": + from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision as TorchMixedPrecision + + if self.precision in ("16-true", "bf16-true"): + rank_zero_warn( + f"FSDP with `{self.precision}` enables computation in lower precision. " + "FSDP will always retain a full-precision copy of the model parameters for sharding." + ) + + if self.precision in ("16-true", "16-mixed"): + param_dtype = reduce_dtype = buffer_dtype = torch.float16 + elif self.precision in ("bf16-true", "bf16-mixed"): + param_dtype = reduce_dtype = buffer_dtype = torch.bfloat16 + elif self.precision == "32-true": + param_dtype = reduce_dtype = buffer_dtype = torch.float32 + else: + raise ValueError(f"Was unable to infer precision type, received {self.precision!r}.") + + return TorchMixedPrecision( + param_dtype=param_dtype, + reduce_dtype=reduce_dtype, + buffer_dtype=buffer_dtype, + ) + + @override + def tensor_init_context(self) -> AbstractContextManager: + return _DtypeContextManager(self._desired_input_dtype) + + @override + def module_init_context(self) -> AbstractContextManager: + return _DtypeContextManager(self._desired_input_dtype) + + @override + def forward_context(self) -> AbstractContextManager: + if "mixed" in self.precision: + return torch.autocast("cuda", dtype=(torch.bfloat16 if self.precision == "bf16-mixed" else torch.float16)) + return self.tensor_init_context() + + @override + def convert_input(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=self._desired_input_dtype) + + @override + def convert_output(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.get_default_dtype()) + + @override + def backward(self, tensor: Tensor, model: Optional[Module], *args: Any, **kwargs: Any) -> None: + if self.scaler is not None: + tensor = self.scaler.scale(tensor) + super().backward(tensor, model, *args, **kwargs) + + @override + def optimizer_step( + self, + optimizer: Optimizable, + **kwargs: Any, + ) -> Any: + if self.scaler is None: + # skip scaler logic, as bfloat16 does not require scaler + return super().optimizer_step(optimizer, **kwargs) + # note: the scaler will skip the `optimizer.step` if nonfinite gradients are found + step_output = self.scaler.step(optimizer, **kwargs) # type: ignore[arg-type] + self.scaler.update() + return step_output + + @override + def unscale_gradients(self, optimizer: Optimizer) -> None: + scaler = self.scaler + if scaler is not None: + if _optimizer_handles_unscaling(optimizer): + raise NotImplementedError("Gradient clipping is not implemented for optimizers handling the unscaling.") + scaler.unscale_(optimizer) + + @override + def state_dict(self) -> dict[str, Any]: + if self.scaler is not None: + return self.scaler.state_dict() + return {} + + @override + def load_state_dict(self, state_dict: dict[str, Any]) -> None: + if self.scaler is not None: + self.scaler.load_state_dict(state_dict) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/half.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/half.py new file mode 100644 index 0000000000000000000000000000000000000000..5ba81a6d858e233c52c44a63b9621cb3a6564d03 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/half.py @@ -0,0 +1,63 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from contextlib import AbstractContextManager +from typing import Any, Literal + +import torch +from lightning_utilities.core.apply_func import apply_to_collection +from torch import Tensor +from torch.nn import Module +from typing_extensions import override + +from lightning_fabric.plugins.precision.precision import Precision +from lightning_fabric.plugins.precision.utils import _convert_fp_tensor, _DtypeContextManager + + +class HalfPrecision(Precision): + """Plugin for training with half precision. + + Args: + precision: Whether to use ``torch.float16`` (``'16-true'``) or ``torch.bfloat16`` (``'bf16-true'``). + + """ + + precision: Literal["bf16-true", "16-true"] = "16-true" + + def __init__(self, precision: Literal["bf16-true", "16-true"] = "16-true") -> None: + self.precision = precision + self._desired_input_dtype = torch.bfloat16 if precision == "bf16-true" else torch.float16 + + @override + def convert_module(self, module: Module) -> Module: + return module.to(dtype=self._desired_input_dtype) + + @override + def tensor_init_context(self) -> AbstractContextManager: + return _DtypeContextManager(self._desired_input_dtype) + + @override + def module_init_context(self) -> AbstractContextManager: + return self.tensor_init_context() + + @override + def forward_context(self) -> AbstractContextManager: + return self.tensor_init_context() + + @override + def convert_input(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=self._desired_input_dtype) + + @override + def convert_output(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.get_default_dtype()) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/precision.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/precision.py new file mode 100644 index 0000000000000000000000000000000000000000..5de24826466e3fc1ba48fbdfa81f901c90a3561a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/precision.py @@ -0,0 +1,162 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from contextlib import AbstractContextManager, nullcontext +from typing import Any, Literal, Optional, Union + +from torch import Tensor +from torch.nn import Module +from torch.optim import Optimizer + +from lightning_fabric.utilities.types import _PARAMETERS, Optimizable + +_PRECISION_INPUT_INT = Literal[64, 32, 16] +_PRECISION_INPUT_STR_ALIAS_CONVERSION = {"64": "64-true", "32": "32-true", "16": "16-mixed", "bf16": "bf16-mixed"} +_PRECISION_INPUT_STR_ALIAS = Literal["64", "32", "16", "bf16"] +_PRECISION_INPUT_STR = Literal[ + "transformer-engine", + "transformer-engine-float16", + "16-true", + "16-mixed", + "bf16-true", + "bf16-mixed", + "32-true", + "64-true", +] +_PRECISION_INPUT = Union[_PRECISION_INPUT_INT, _PRECISION_INPUT_STR, _PRECISION_INPUT_STR_ALIAS] + + +class Precision: + """Base class for all plugins handling the precision-specific parts of the training. + + The class attribute precision must be overwritten in child classes. The default value reflects fp32 training. + + """ + + precision: _PRECISION_INPUT_STR = "32-true" + + def convert_module(self, module: Module) -> Module: + """Convert the module parameters to the precision type this plugin handles. + + This is optional and depends on the precision limitations during optimization. + + """ + return module + + def tensor_init_context(self) -> AbstractContextManager: + """Controls how tensors get created (device, dtype).""" + return nullcontext() + + def module_init_context(self) -> AbstractContextManager: + """Instantiate module parameters or tensors in the precision type this plugin handles. + + This is optional and depends on the precision limitations during optimization. + + """ + return nullcontext() + + def forward_context(self) -> AbstractContextManager: + """A contextmanager for managing model forward/training_step/evaluation_step/predict_step.""" + return nullcontext() + + def convert_input(self, data: Any) -> Any: + """Convert model inputs (forward) to the floating point precision type of this plugin. + + This is a no-op in the base precision plugin, since we assume the data already has the desired type (default is + torch.float32). + + """ + return data + + def convert_output(self, data: Any) -> Any: + """Convert outputs to the floating point precision type expected after model's forward. + + This is a no-op in the base precision plugin, since we assume the data already has the desired type (default is + torch.float32). + + """ + return data + + def pre_backward(self, tensor: Tensor, module: Optional[Module]) -> Any: + """Runs before precision plugin executes backward. + + Args: + tensor: The tensor that will be used for backpropagation + module: The module that was involved in producing the tensor and whose parameters need the gradients + + """ + + def backward(self, tensor: Tensor, model: Optional[Module], *args: Any, **kwargs: Any) -> None: + """Performs the actual backpropagation. + + Args: + tensor: The tensor that will be used for backpropagation + model: The module that was involved in producing the tensor and whose parameters need the gradients + + """ + tensor.backward(*args, **kwargs) + + def post_backward(self, tensor: Tensor, module: Optional[Module]) -> Any: + """Runs after precision plugin executes backward. + + Args: + tensor: The tensor that will be used for backpropagation + module: The module that was involved in producing the tensor and whose parameters need the gradients + + """ + + def optimizer_step( + self, + optimizer: Optimizable, + **kwargs: Any, + ) -> Any: + """Hook to run the optimizer step.""" + return optimizer.step(**kwargs) + + def main_params(self, optimizer: Optimizer) -> _PARAMETERS: + """The main params of the model. + + Returns the plain model params here. Maybe different in other precision plugins. + + """ + for group in optimizer.param_groups: + yield from group["params"] + + def unscale_gradients(self, optimizer: Optimizer) -> None: + return + + def state_dict(self) -> dict[str, Any]: + """Called when saving a checkpoint, implement to generate precision plugin state_dict. + + Returns: + A dictionary containing precision plugin state. + + """ + return {} + + def load_state_dict(self, state_dict: dict[str, Any]) -> None: + """Called when loading a checkpoint, implement to reload precision plugin state given precision plugin + state_dict. + + Args: + state_dict: the precision plugin state returned by ``state_dict``. + + """ + pass + + def teardown(self) -> None: + """This method is called to teardown the training process. + + It is the right place to release memory and free other resources. + + """ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/transformer_engine.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/transformer_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..d5bd57c778045ebe7a6c14c1167a7f79492cb30b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/transformer_engine.py @@ -0,0 +1,182 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import logging +from collections.abc import Mapping +from contextlib import AbstractContextManager, ExitStack +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +import torch +from lightning_utilities import apply_to_collection +from lightning_utilities.core.imports import RequirementCache +from torch import Tensor +from typing_extensions import override + +from lightning_fabric.plugins.precision.precision import Precision +from lightning_fabric.plugins.precision.utils import ( + _ClassReplacementContextManager, + _convert_fp_tensor, + _DtypeContextManager, +) +from lightning_fabric.utilities.rank_zero import rank_zero_info, rank_zero_warn + +if TYPE_CHECKING: + from transformer_engine.common.recipe import DelayedScaling + +_TRANSFORMER_ENGINE_AVAILABLE = RequirementCache("transformer_engine>=0.11.0") +log = logging.getLogger(__name__) + + +class TransformerEnginePrecision(Precision): + """Plugin for training with fp8 precision via nvidia's + `Transformer Engine `__. + + .. warning:: This is an :ref:`experimental ` feature. + + Args: + weights_dtype: The weights dtype to use. + recipe: Recipe for the DelayedScaling + `configuration `__. + In dict format or the dataclass format. + replace_layers: Whether to replace ``Linear`` and ``LayerNorm`` layers automatically with their Transformer + Engine alternatives. Note that they don't subclass the torch equivalents so checks like + ``isinstance(l, torch.nn.Linear)`` will not pass. + fallback_compute_dtype: The compute dtype to use for operations that don't support fp8 autocast. Defaults to the + same as ``weights_dtype``. + + .. note:: + + Support for FP8 in the linear layers with this plugin is currently limited to tensors + with shapes where the dimensions are divisible by 8 and 16 respectively. You might want to add padding to your + inputs to conform to this restriction. + + """ + + precision: Literal["transformer-engine", "transformer-engine-float16"] = "transformer-engine" + + def __init__( + self, + *, + weights_dtype: torch.dtype, + recipe: Optional[Union[Mapping[str, Any], "DelayedScaling"]] = None, + replace_layers: Optional[bool] = None, + fallback_compute_dtype: Optional[torch.dtype] = None, + ) -> None: + if not _TRANSFORMER_ENGINE_AVAILABLE: + raise ModuleNotFoundError(str(_TRANSFORMER_ENGINE_AVAILABLE)) + from transformer_engine.common.recipe import DelayedScaling + + if recipe is None: + recipe = DelayedScaling() + elif isinstance(recipe, Mapping): + recipe = dict(recipe) # copy + if "fp8_format" in recipe: + from transformer_engine.common.recipe import Format + + recipe["fp8_format"] = getattr(Format, recipe["fp8_format"]) + recipe = DelayedScaling(**recipe) + + self.weights_dtype = weights_dtype + self.recipe = recipe + self.replace_layers = replace_layers + self.fallback_compute_dtype = fallback_compute_dtype or weights_dtype + + @override + def convert_module(self, module: torch.nn.Module) -> torch.nn.Module: + # avoid converting if any is found. assume the user took care of it + if any("transformer_engine.pytorch" in m.__module__ for m in module.modules()): + if self.replace_layers is True: + # info level because this is expected with `init_module` + rank_zero_info( + "`TransformerEnginePrecision(replace_layers=True)` is set but the model already contains" + " TransformerEngine layers. Skipping" + ) + elif self.replace_layers in (None, True): + _convert_layers(module) + module = module.to(dtype=self.weights_dtype) + return module + + @override + def tensor_init_context(self) -> AbstractContextManager: + return _DtypeContextManager(self.weights_dtype) + + @override + def module_init_context(self) -> AbstractContextManager: + dtype_ctx = self.tensor_init_context() + stack = ExitStack() + if self.replace_layers: + import transformer_engine.pytorch as te + + context_manager = _ClassReplacementContextManager({ + "torch.nn.Linear": te.Linear, + "torch.nn.LayerNorm": te.LayerNorm, + }) + stack.enter_context(context_manager) + stack.enter_context(dtype_ctx) + return stack + + @override + def forward_context(self) -> AbstractContextManager: + dtype_ctx = _DtypeContextManager(self.weights_dtype) + fallback_autocast_ctx = torch.autocast(device_type="cuda", dtype=self.fallback_compute_dtype) + import transformer_engine.pytorch as te + + autocast_ctx = te.fp8_autocast(enabled=True, fp8_recipe=self.recipe) + stack = ExitStack() + stack.enter_context(dtype_ctx) + # enable an outer fallback autocast for operations that do not support fp8 + stack.enter_context(fallback_autocast_ctx) + stack.enter_context(autocast_ctx) + return stack + + @override + def convert_input(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=self.weights_dtype) + + @override + def convert_output(self, data: Any) -> Any: + return apply_to_collection(data, function=_convert_fp_tensor, dtype=Tensor, dst_type=torch.get_default_dtype()) + + +def _convert_layers(module: torch.nn.Module) -> None: + import transformer_engine.pytorch as te + + for name, child in module.named_children(): + if isinstance(child, torch.nn.Linear): + if child.in_features % 8 != 0 or child.out_features % 16 != 0: + # https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/examples/fp8_primer.html#FP8-autocasting + rank_zero_warn( + "Support for FP8 in the linear layers with this plugin is currently limited to" + " tensors with shapes where the dimensions are divisible by 8 and 16 respectively." + f" The layer {name!r} does not fit this criteria. You might want to add padding to your inputs." + ) + continue + has_bias = child.bias is not None + replacement = te.Linear(child.in_features, child.out_features, bias=has_bias) + replacement.weight.data = child.weight.data.clone() + if has_bias: + replacement.bias.data = child.bias.data.clone() + log.debug(f"Replacing layer {name!r} with Transformer Engine equivalent") + module.__setattr__(name, replacement) + elif isinstance(child, torch.nn.LayerNorm): + replacement = te.LayerNorm(child.normalized_shape[0], eps=child.eps) + replacement.weight.data = child.weight.data.clone() + # Check if bias exists before attempting to clone its data + if child.bias is not None and replacement.bias is not None: + replacement.bias.data = child.bias.data.clone() + log.debug(f"Replacing layer {name!r} with Transformer Engine equivalent") + module.__setattr__(name, replacement) + else: + # there are other transformer engine layers that we could convert but require fusion. full list at: + # https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/pytorch.html + _convert_layers(child) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/utils.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8362384cb104222b20d9e3d7610228f9a74308b7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/utils.py @@ -0,0 +1,65 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import Mapping +from typing import Any, Union + +import torch +from torch import Tensor + + +def _convert_fp_tensor(tensor: Tensor, dst_type: Union[str, torch.dtype]) -> Tensor: + return tensor.to(dst_type) if torch.is_floating_point(tensor) else tensor + + +# do not support using as a decorator or else `torch.get_default_dtype` will get picked up at initialization +class _DtypeContextManager: + """A context manager to change the default tensor type when tensors get created. + + See: :func:`torch.set_default_dtype` + + """ + + def __init__(self, dtype: torch.dtype) -> None: + self._previous_dtype: torch.dtype = torch.get_default_dtype() + self._new_dtype = dtype + + def __enter__(self) -> None: + torch.set_default_dtype(self._new_dtype) + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + torch.set_default_dtype(self._previous_dtype) + + +class _ClassReplacementContextManager: + """A context manager to monkeypatch classes.""" + + def __init__(self, mapping: Mapping[str, type]) -> None: + self._mapping = mapping + self._originals = {} + self._modules = {} + for class_string in mapping: + module_name, class_name = class_string.rsplit(".", 1) + module = __import__(module_name, fromlist=[class_name]) + self._modules[class_string] = module + self._originals[class_string] = getattr(module, class_name) + + def __enter__(self) -> None: + for class_string, replacement in self._mapping.items(): + _, class_name = class_string.rsplit(".", 1) + setattr(self._modules[class_string], class_name, replacement) + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + for class_string, replacement in self._mapping.items(): + _, class_name = class_string.rsplit(".", 1) + setattr(self._modules[class_string], class_name, self._originals[class_string]) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/xla.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/xla.py new file mode 100644 index 0000000000000000000000000000000000000000..3b3f72fee976a0fe138092e40509501fbaf9380e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/plugins/precision/xla.py @@ -0,0 +1,73 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +from typing import Any, Literal + +import torch +from typing_extensions import get_args, override + +from lightning_fabric.accelerators.xla import _XLA_AVAILABLE +from lightning_fabric.plugins.precision.precision import Precision +from lightning_fabric.utilities.types import Optimizable + +_PRECISION_INPUT = Literal["32-true", "16-true", "bf16-true"] + + +class XLAPrecision(Precision): + """Plugin for training with XLA. + + Args: + precision: Full precision (32-true) or half precision (16-true, bf16-true). + + Raises: + ValueError: + If unsupported ``precision`` is provided. + + """ + + def __init__(self, precision: _PRECISION_INPUT) -> None: + if not _XLA_AVAILABLE: + raise ModuleNotFoundError(str(_XLA_AVAILABLE)) + supported_precision = get_args(_PRECISION_INPUT) + if precision not in supported_precision: + raise ValueError( + f"`precision={precision!r})` is not supported in XLA." + f" `precision` must be one of: {supported_precision}." + ) + self.precision = precision + + if precision == "16-true": + os.environ["XLA_USE_F16"] = "1" + self._desired_dtype = torch.float16 + elif precision == "bf16-true": + os.environ["XLA_USE_BF16"] = "1" + self._desired_dtype = torch.bfloat16 + else: + self._desired_dtype = torch.float32 + + @override + def optimizer_step( + self, + optimizer: Optimizable, + **kwargs: Any, + ) -> Any: + import torch_xla.core.xla_model as xm + + # you always want to `xm.mark_step()` after `optimizer.step` for better performance, so we set `barrier=True` + return xm.optimizer_step(optimizer, optimizer_args=kwargs, barrier=True) + + @override + def teardown(self) -> None: + os.environ.pop("XLA_USE_BF16", None) + os.environ.pop("XLA_USE_F16", None) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/py.typed b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ff33b1db5303c1b5f0df0ad8b233685974f1a7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__init__.py @@ -0,0 +1,31 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import sys + +from lightning_fabric.strategies.ddp import DDPStrategy # noqa: F401 +from lightning_fabric.strategies.deepspeed import DeepSpeedStrategy # noqa: F401 +from lightning_fabric.strategies.dp import DataParallelStrategy # noqa: F401 +from lightning_fabric.strategies.fsdp import FSDPStrategy # noqa: F401 +from lightning_fabric.strategies.model_parallel import ModelParallelStrategy # noqa: F401 +from lightning_fabric.strategies.parallel import ParallelStrategy # noqa: F401 +from lightning_fabric.strategies.registry import _StrategyRegistry +from lightning_fabric.strategies.single_device import SingleDeviceStrategy # noqa: F401 +from lightning_fabric.strategies.single_xla import SingleDeviceXLAStrategy # noqa: F401 +from lightning_fabric.strategies.strategy import Strategy +from lightning_fabric.strategies.xla import XLAStrategy # noqa: F401 +from lightning_fabric.strategies.xla_fsdp import XLAFSDPStrategy # noqa: F401 +from lightning_fabric.utilities.registry import _register_classes + +STRATEGY_REGISTRY = _StrategyRegistry() +_register_classes(STRATEGY_REGISTRY, "register_strategies", sys.modules[__name__], Strategy) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92c1c0a0e9de5e55103f97ff1744fc205a5479e0 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/ddp.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/ddp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c2098d6a7699626092ebd24d85a96160e4be64e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/ddp.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/deepspeed.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/deepspeed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f88e2dfba2bbda9ff5fd1808585c90bdb5496528 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/deepspeed.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/dp.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/dp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..738b8edacc67a4a2198b67f7980d23f3273f0308 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/dp.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/fsdp.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/fsdp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0be118098af287f819db87d326bcd0cb8dd0797d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/fsdp.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/model_parallel.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/model_parallel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..519cfc567197e1e4f4a7864a5f574146fa127c2d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/model_parallel.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/parallel.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/parallel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0ec29ce7d9affedada6d2d42e7dd6926c29cd20 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/parallel.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/registry.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff7c2ca1dfcc33347db6e338e58c6563012e344c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/registry.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/single_device.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/single_device.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e514f0af13ee45bcf5825694f51d301653141e2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/single_device.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/single_xla.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/single_xla.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da99438665c508ebb128a1aee4c78a44bbce9732 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/single_xla.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/strategy.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/strategy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97838794bcecaf9f0c1f357120c9d5abe9fa048b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/strategy.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/xla.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/xla.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e24723244b0cc764bc4ac415dcf65096b49c4f22 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/xla.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/xla_fsdp.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/xla_fsdp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a14f29eb8d25f656966b45d1b15767522f980ae1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/__pycache__/xla_fsdp.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/ddp.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/ddp.py new file mode 100644 index 0000000000000000000000000000000000000000..888e4de6b644752b8631f91c9dd2289eec4e9342 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/ddp.py @@ -0,0 +1,260 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from contextlib import AbstractContextManager, nullcontext +from datetime import timedelta +from typing import Any, Literal, Optional, Union + +import torch +import torch.distributed +from lightning_utilities.core.rank_zero import rank_zero_only as utils_rank_zero_only +from torch import Tensor +from torch.nn import Module +from torch.nn.parallel.distributed import DistributedDataParallel +from typing_extensions import override + +from lightning_fabric.accelerators.accelerator import Accelerator +from lightning_fabric.plugins.collectives.torch_collective import default_pg_timeout +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment +from lightning_fabric.plugins.io.checkpoint_io import CheckpointIO +from lightning_fabric.plugins.precision import Precision +from lightning_fabric.strategies.launchers.multiprocessing import _MultiProcessingLauncher +from lightning_fabric.strategies.launchers.subprocess_script import _SubprocessScriptLauncher +from lightning_fabric.strategies.parallel import ParallelStrategy +from lightning_fabric.strategies.registry import _StrategyRegistry +from lightning_fabric.strategies.strategy import TBroadcast, _BackwardSyncControl +from lightning_fabric.utilities.distributed import ( + ReduceOp, + _distributed_is_initialized, + _get_default_process_group_backend_for_device, + _init_dist_connection, + _sync_ddp_if_available, +) +from lightning_fabric.utilities.distributed import group as _group +from lightning_fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_3 +from lightning_fabric.utilities.rank_zero import rank_zero_only + +_DDP_FORK_ALIASES = ( + "ddp_fork", + "ddp_notebook", +) + + +class DDPStrategy(ParallelStrategy): + """Strategy for multi-process single-device training on one or multiple nodes.""" + + def __init__( + self, + accelerator: Optional[Accelerator] = None, + parallel_devices: Optional[list[torch.device]] = None, + cluster_environment: Optional[ClusterEnvironment] = None, + checkpoint_io: Optional[CheckpointIO] = None, + precision: Optional[Precision] = None, + process_group_backend: Optional[str] = None, + timeout: Optional[timedelta] = default_pg_timeout, + start_method: Literal["popen", "spawn", "fork", "forkserver"] = "popen", + **kwargs: Any, + ) -> None: + super().__init__( + accelerator=accelerator, + parallel_devices=parallel_devices, + cluster_environment=cluster_environment, + checkpoint_io=checkpoint_io, + precision=precision, + ) + self._num_nodes = 1 + self._process_group_backend: Optional[str] = process_group_backend + self._timeout: Optional[timedelta] = timeout + self._start_method = start_method + self._backward_sync_control = _DDPBackwardSyncControl() + self._ddp_kwargs = kwargs + + @property + @override + def root_device(self) -> torch.device: + assert self.parallel_devices is not None + return self.parallel_devices[self.local_rank] + + @property + def num_nodes(self) -> int: + return self._num_nodes + + @num_nodes.setter + def num_nodes(self, num_nodes: int) -> None: + # note that world ranks is related to num_nodes, when resetting it, need to reset world ranks + self._num_nodes = num_nodes + + @property + def num_processes(self) -> int: + return len(self.parallel_devices) if self.parallel_devices is not None else 0 + + @property + @override + def distributed_sampler_kwargs(self) -> dict[str, Any]: + return {"num_replicas": (self.num_nodes * self.num_processes), "rank": self.global_rank} + + @property + def process_group_backend(self) -> Optional[str]: + return self._process_group_backend + + @override + def _configure_launcher(self) -> None: + assert self.cluster_environment is not None + if self._start_method == "popen": + self._launcher = _SubprocessScriptLauncher(self.cluster_environment, self.num_processes, self.num_nodes) + else: + self._launcher = _MultiProcessingLauncher(self, start_method=self._start_method) + + @override + def setup_environment(self) -> None: + super().setup_environment() + self._setup_distributed() + + @override + def setup_module(self, module: Module) -> DistributedDataParallel: + """Wraps the model into a :class:`~torch.nn.parallel.distributed.DistributedDataParallel` module.""" + device_ids = self._determine_ddp_device_ids() + # https://pytorch.org/docs/stable/notes/cuda.html#id5 + ctx = torch.cuda.stream(torch.cuda.Stream()) if device_ids is not None else nullcontext() + with ctx: + return DistributedDataParallel(module=module, device_ids=device_ids, **self._ddp_kwargs) + + @override + def module_to_device(self, module: Module) -> None: + module.to(self.root_device) + + @override + def all_reduce( + self, tensor: Tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean" + ) -> Tensor: + """Reduces a tensor from several distributed processes to one aggregated tensor. + + Args: + tensor: the tensor to sync and reduce + group: the process group to gather results from. Defaults to all processes (world) + reduce_op: the reduction operation. Defaults to 'mean'/'avg'. + Can also be a string 'sum' to calculate the sum during reduction. + + Return: + reduced value, except when the input was not a tensor the output remains is unchanged + + """ + if isinstance(tensor, Tensor): + return _sync_ddp_if_available(tensor, group, reduce_op=reduce_op) + return tensor + + @override + def barrier(self, *args: Any, **kwargs: Any) -> None: + if not _distributed_is_initialized(): + return + if torch.distributed.get_backend() == "nccl": + torch.distributed.barrier(device_ids=self._determine_ddp_device_ids()) + else: + # Handle PyTorch bug where barrier() fails on CPU with "PrivateUse1HooksInterface" error + try: + torch.distributed.barrier() + except RuntimeError as e: + if "PrivateUse1HooksInterface" in str(e): + # Fallback: Use all_reduce as barrier - all processes must participate + # This achieves the same synchronization effect as barrier() + dummy_tensor = torch.tensor(0.0, device=self.root_device) + torch.distributed.all_reduce(dummy_tensor) + else: + raise + + @override + def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast: + if not _distributed_is_initialized(): + return obj + + obj = [obj] + torch.distributed.broadcast_object_list(obj, src, group=_group.WORLD) + return obj[0] + + @override + def get_module_state_dict(self, module: Module) -> dict[str, Union[Any, Tensor]]: + if isinstance(module, DistributedDataParallel): + module = module.module + return super().get_module_state_dict(module) + + @override + def load_module_state_dict( + self, module: Module, state_dict: dict[str, Union[Any, Tensor]], strict: bool = True + ) -> None: + if isinstance(module, DistributedDataParallel): + module = module.module + super().load_module_state_dict(module=module, state_dict=state_dict, strict=strict) + + @classmethod + @override + def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: + entries = ( + ("ddp", "popen"), + ("ddp_spawn", "spawn"), + ("ddp_fork", "fork"), + ("ddp_notebook", "fork"), + ) + for name, start_method in entries: + strategy_registry.register( + name, + cls, + description=f"DDP strategy with `start_method={start_method!r}`", + start_method=start_method, + ) + strategy_registry.register( + "ddp_find_unused_parameters_true", + cls, + description="Alias for `find_unused_parameters_true` and `start_method='popen'`", + find_unused_parameters=True, + start_method="popen", + ) + + def _setup_distributed(self) -> None: + self._set_world_ranks() + self._process_group_backend = self._get_process_group_backend() + assert self.cluster_environment is not None + kwargs: dict[str, Any] = {"timeout": self._timeout} + if _TORCH_GREATER_EQUAL_2_3: + kwargs["device_id"] = self.root_device if self.root_device.type != "cpu" else None + _init_dist_connection(self.cluster_environment, self._process_group_backend, **kwargs) + + def _get_process_group_backend(self) -> str: + return self._process_group_backend or _get_default_process_group_backend_for_device(self.root_device) + + def _set_world_ranks(self) -> None: + if self.cluster_environment is not None: + self.cluster_environment.set_global_rank(self.node_rank * self.num_processes + self.local_rank) + self.cluster_environment.set_world_size(self.num_nodes * self.num_processes) + # `LightningEnvironment.set_global_rank` will do this too, but we cannot rely on that implementation detail + # additionally, for some implementations, the setter is a no-op, so it's safer to access the getter + rank_zero_only.rank = utils_rank_zero_only.rank = self.global_rank + + def _determine_ddp_device_ids(self) -> Optional[list[int]]: + return None if self.root_device.type == "cpu" else [self.root_device.index] + + +class _DDPBackwardSyncControl(_BackwardSyncControl): + @override + def no_backward_sync(self, module: Module, enabled: bool) -> AbstractContextManager: + """Blocks gradient synchronization inside the :class:`~torch.nn.parallel.distributed.DistributedDataParallel` + wrapper.""" + if not enabled: + return nullcontext() + + if not isinstance(module, DistributedDataParallel): + raise TypeError( + "Blocking backward sync is only possible if the module passed to" + f" `{self.__class__.__name__}.no_backward_sync` is wrapped in `DistributedDataParallel`." + f" Got: {module.__class__.__name__}." + ) + return module.no_sync() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/deepspeed.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/deepspeed.py new file mode 100644 index 0000000000000000000000000000000000000000..64379f6ed7d3ca3530b43cfb23363dbd2ac396cf --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/deepspeed.py @@ -0,0 +1,950 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import argparse +import json +import logging +import os +import platform +from collections.abc import Mapping +from contextlib import AbstractContextManager, ExitStack +from datetime import timedelta +from itertools import chain +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Optional, Union + +import torch +from lightning_utilities.core.imports import RequirementCache +from torch.nn import Module +from torch.optim import Optimizer +from typing_extensions import override + +from lightning_fabric.accelerators import Accelerator, CUDAAccelerator +from lightning_fabric.plugins.collectives.torch_collective import default_pg_timeout +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment +from lightning_fabric.plugins.precision import Precision +from lightning_fabric.strategies.ddp import DDPStrategy +from lightning_fabric.strategies.registry import _StrategyRegistry +from lightning_fabric.strategies.strategy import _Sharded +from lightning_fabric.utilities.distributed import log +from lightning_fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_6 +from lightning_fabric.utilities.load import _move_state_into +from lightning_fabric.utilities.rank_zero import rank_zero_info, rank_zero_warn +from lightning_fabric.utilities.seed import reset_seed +from lightning_fabric.utilities.types import _PATH + +if TYPE_CHECKING: + from deepspeed import DeepSpeedEngine + from torch.optim.lr_scheduler import _LRScheduler + +_DEEPSPEED_AVAILABLE = RequirementCache("deepspeed") +_DEEPSPEED_GREATER_EQUAL_0_16 = RequirementCache("deepspeed>=0.16.0") + + +# TODO(fabric): Links in the docstrings to PL-specific deepspeed user docs need to be replaced. +class DeepSpeedStrategy(DDPStrategy, _Sharded): + DEEPSPEED_ENV_VAR = "PL_DEEPSPEED_CONFIG_PATH" + + def __init__( + self, + accelerator: Optional[Accelerator] = None, + zero_optimization: bool = True, + stage: int = 2, + remote_device: Optional[str] = None, + offload_optimizer: bool = False, + offload_parameters: bool = False, + offload_params_device: str = "cpu", + nvme_path: str = "/local_nvme", + params_buffer_count: int = 5, + params_buffer_size: int = 100_000_000, + max_in_cpu: int = 1_000_000_000, + offload_optimizer_device: str = "cpu", + optimizer_buffer_count: int = 4, + block_size: int = 1048576, + queue_depth: int = 8, + single_submit: bool = False, + overlap_events: bool = True, + thread_count: int = 1, + pin_memory: bool = False, + sub_group_size: int = 1_000_000_000_000, + contiguous_gradients: bool = True, + overlap_comm: bool = True, + allgather_partitions: bool = True, + reduce_scatter: bool = True, + allgather_bucket_size: int = 200_000_000, + reduce_bucket_size: int = 200_000_000, + zero_allow_untested_optimizer: bool = True, + logging_batch_size_per_gpu: Optional[int] = None, + config: Optional[Union[_PATH, dict[str, Any]]] = None, + logging_level: int = logging.WARN, + parallel_devices: Optional[list[torch.device]] = None, + cluster_environment: Optional[ClusterEnvironment] = None, + loss_scale: float = 0, + initial_scale_power: int = 16, + loss_scale_window: int = 1000, + hysteresis: int = 2, + min_loss_scale: int = 1, + partition_activations: bool = False, + cpu_checkpointing: bool = False, + contiguous_memory_optimization: bool = False, + synchronize_checkpoint_boundary: bool = False, + load_full_weights: bool = False, + precision: Optional[Precision] = None, + process_group_backend: Optional[str] = None, + timeout: Optional[timedelta] = default_pg_timeout, + exclude_frozen_parameters: bool = False, + ) -> None: + """Provides capabilities to run training using the DeepSpeed library, with training optimizations for large + billion parameter models. `For more information: https://pytorch- + lightning.readthedocs.io/en/stable/advanced/model_parallel.html#deepspeed`. + + .. warning:: This is an :ref:`experimental ` feature. + + Defaults have been set to enable ZeRO-Offload and some have been taken from the link below. + These defaults have been set generally, but may require tuning for optimum performance based on your model size. + `For more information: https://www.deepspeed.ai/docs/config-json/#zero-optimizations-for-fp16-training`. + + Arguments: + + zero_optimization: Enable ZeRO optimization. This is compatible with either ``precision="16-mixed"`` or + ``precision="bf16-mixed"``. + + stage: Different stages of the ZeRO Optimizer. 0 is disabled, + 1 is optimizer state partitioning, 2 is optimizer+gradient state partitioning, + 3 is optimizer+gradient_parameter partitioning using the infinity engine. + + remote_device: Device to instantiate the model on initially (``cpu`` or ``nvme``). Defaults to GPU. + + offload_optimizer: Enable offloading optimizer memory and computation to CPU or NVMe + based on ``offload_optimizer_device``. + + offload_parameters: When using ZeRO Stage 3, Enable offloading parameter memory and computation + to CPU or NVMe based on ``offload_params_device``. + + offload_params_device: When offloading parameters choose the device to offload to, ``cpu`` or ``nvme``. + + offload_optimizer_device: When offloading optimizer state choose the device to offload to, + ``cpu`` or ``nvme``. + + params_buffer_count: Number of buffers in buffer pool for + parameter offloading when ``offload_params_device`` is ``nvme``. + + params_buffer_size: Size of buffers in buffer pool for parameter offloading + when ``offload_params_device`` is ``nvme``. + + max_in_cpu: Number of parameter elements to maintain in CPU memory when offloading to NVMe is enabled. + + nvme_path: Filesystem path for NVMe device for optimizer/parameter state offloading. + + optimizer_buffer_count: Number of buffers in buffer pool for optimizer state offloading + when ``offload_optimizer_device`` is set to ``nvme``. + This should be at least the number of states maintained per parameter by the optimizer. + For example, Adam optimizer has 4 states (parameter, gradient, momentum, and variance). + + block_size: When using NVMe Offloading, the I/O block size in bytes. + + queue_depth: When using NVMe Offloading, the I/O queue depth. + + single_submit: When using NVMe Offloading, + submit requests to storage device as multiple individual requests, + as opposed to one block of requests. + + overlap_events: When using NVMe Offloading, + submit requests to storage device in an overlapped fashion + without waiting for completion of earlier requests. + + thread_count: When using NVMe Offloading, + Intra-request parallelism for each read/write submitted by a user thread. + + pin_memory: When using ZeRO stage 3, pin optimizer state memory on CPU. + This could boost throughput at the cost of extra memory overhead. + + sub_group_size: When using ZeRO stage 3, defines the number of parameters + within a sub group to offload at a time. + Smaller numbers require more communication, but improve memory efficiency. + + contiguous_gradients: Copies gradients to a continuous buffer as they are produced. + Avoids memory fragmentation during backwards. Useful when training large models. + + overlap_comm: Overlap the reduction (synchronization) of gradients with the backwards computation. + This is a speed optimization when training across multiple GPUs/machines. + + allgather_partitions: All gather updated parameters at the end of training step, + instead of using a series of broadcast collectives. + + reduce_scatter: Use reduce/scatter instead of allreduce to average gradients. + + allgather_bucket_size: Number of elements to allgather at once. + Used to limit the memory required for larger model sizes, with a tradeoff with speed. + + reduce_bucket_size: Number of elements to reduce at once. + Used to limit the memory required for larger model sizes, with a tradeoff with speed. + + zero_allow_untested_optimizer: Allow untested optimizers to be used with ZeRO. Currently only Adam is a + DeepSpeed supported optimizer when using ZeRO. + + logging_batch_size_per_gpu: Config used in DeepSpeed to calculate verbose timing for logging + on a per sample per second basis (only displayed if logging=logging.INFO). + To obtain accurate logs when using datasets that do not support batch samplers, + set this to the actual per gpu batch size. + + config: Pass in a deepspeed formatted config dict, + or path to a deepspeed config: https://www.deepspeed.ai/docs/config-json. + All defaults will be ignored if a config is passed in. + + logging_level: Set logging level for deepspeed. + + loss_scale: Loss scaling value for FP16 training. + 0.0 results in dynamic loss scaling, otherwise static. + + initial_scale_power: Power of the initial dynamic loss scale value. Loss scale is computed + by ``2^initial_scale_power``. + + loss_scale_window: Window in which to raise/lower the dynamic FP16 loss scaling value. + + hysteresis: FP16 Delay shift in Dynamic Loss scaling. + + min_loss_scale: The minimum FP16 dynamic loss scaling value. + + partition_activations: Enables partition activation when used with ZeRO stage 3 and model parallelism. + Still requires you to wrap your forward functions in deepspeed.checkpointing.checkpoint. + See `deepspeed tutorial + `_. + + cpu_checkpointing: Offloads partitioned activations to CPU if ``partition_activations`` is enabled. + + contiguous_memory_optimization: Copies partitioned activations so that they are contiguous in memory. + Not supported by all models. + + synchronize_checkpoint_boundary: Insert :func:`torch.cuda.synchronize` at each checkpoint boundary. + + load_full_weights: True when loading a single checkpoint file containing the model state dict + when using ZeRO Stage 3. This differs from the DeepSpeed checkpoint which contains shards + per worker. + + exclude_frozen_parameters: Exclude frozen parameters when saving checkpoints. + + """ + if not _DEEPSPEED_AVAILABLE: + raise ImportError( + "To use the `DeepSpeedStrategy`, you must have DeepSpeed installed." + " Install it by running `pip install -U deepspeed`." + ) + + if _TORCH_GREATER_EQUAL_2_6 and not _DEEPSPEED_GREATER_EQUAL_0_16: + # Starting with PyTorch 2.6, `torch.load` defaults to `weights_only=True` when loading full checkpoints. + # DeepSpeed added support for this behavior in version 0.16.0. + import deepspeed + + deepspeed_version = deepspeed.__version__ + + raise ImportError( + f"PyTorch >= 2.6 requires DeepSpeed >= 0.16.0. " + f"Detected DeepSpeed version: {deepspeed_version}. " + "Please upgrade by running `pip install -U 'deepspeed>=0.16.0'`." + ) + + super().__init__( + accelerator=accelerator, + parallel_devices=parallel_devices, + cluster_environment=cluster_environment, + precision=precision, + process_group_backend=process_group_backend, + ) + self._backward_sync_control = None # DeepSpeed handles gradient accumulation internally + self._timeout: Optional[timedelta] = timeout + + self.config = self._load_config(config) + if self.config is None: + # User has not overridden config, set defaults + self.config = self._create_default_config( + zero_optimization, + zero_allow_untested_optimizer, + logging_batch_size_per_gpu, + offload_optimizer=offload_optimizer, + offload_parameters=offload_parameters, + nvme_path=nvme_path, + offload_params_device=offload_params_device, + params_buffer_count=params_buffer_count, + params_buffer_size=params_buffer_size, + max_in_cpu=max_in_cpu, + pin_memory=pin_memory, + offload_optimizer_device=offload_optimizer_device, + optimizer_buffer_count=optimizer_buffer_count, + block_size=block_size, + queue_depth=queue_depth, + single_submit=single_submit, + overlap_events=overlap_events, + thread_count=thread_count, + partition_activations=partition_activations, + cpu_checkpointing=cpu_checkpointing, + contiguous_memory_optimization=contiguous_memory_optimization, + synchronize_checkpoint_boundary=synchronize_checkpoint_boundary, + stage=stage, + contiguous_gradients=contiguous_gradients, + overlap_comm=overlap_comm, + allgather_partitions=allgather_partitions, + reduce_scatter=reduce_scatter, + allgather_bucket_size=allgather_bucket_size, + reduce_bucket_size=reduce_bucket_size, + sub_group_size=sub_group_size, + ) + + import deepspeed + + self._config_initialized = False + deepspeed.utils.logging.logger.setLevel(logging_level) + + self.remote_device = remote_device + self.load_full_weights = load_full_weights + self.exclude_frozen_parameters = exclude_frozen_parameters + + # default FP16 parameters. + self.loss_scale = loss_scale + self.initial_scale_power = initial_scale_power + self.loss_scale_window = loss_scale_window + self.hysteresis = hysteresis + self.min_loss_scale = min_loss_scale + + self._deepspeed_engine: Optional[DeepSpeedEngine] = None + + @property + def zero_stage_3(self) -> bool: + assert isinstance(self.config, dict) + zero_optimization = self.config.get("zero_optimization") + return zero_optimization is not None and zero_optimization.get("stage") == 3 + + @property + @override + def distributed_sampler_kwargs(self) -> dict[str, int]: + return {"num_replicas": self.world_size, "rank": self.global_rank} + + @property + def model(self) -> "DeepSpeedEngine": + return self._deepspeed_engine + + @override + def setup_module_and_optimizers( + self, module: Module, optimizers: list[Optimizer], scheduler: Optional["_LRScheduler"] = None + ) -> tuple["DeepSpeedEngine", list[Optimizer], Any]: + """Set up a model and multiple optimizers together, along with an optional learning rate scheduler. Currently, + only a single optimizer is supported. + + Return: + The model wrapped into a :class:`deepspeed.DeepSpeedEngine`, a list with a single + deepspeed optimizer, and an optional learning rate scheduler. + + """ + if len(optimizers) != 1: + raise ValueError( + f"Currently only one optimizer is supported with DeepSpeed. Got {len(optimizers)} optimizers instead." + ) + + self._deepspeed_engine, optimizer, scheduler = self._initialize_engine(module, optimizers[0], scheduler) + self._set_deepspeed_activation_checkpointing() + return self._deepspeed_engine, [optimizer], scheduler + + @override + def setup_module(self, module: Module) -> "DeepSpeedEngine": + """Set up a module for inference (no optimizers). + + For training, see :meth:`setup_module_and_optimizers`. + + """ + self._deepspeed_engine, _, _ = self._initialize_engine(module) + return self._deepspeed_engine + + @override + def setup_optimizer(self, optimizer: Optimizer) -> Optimizer: + """Optimizers can only be set up jointly with the model in this strategy. + + Please use :meth:`setup_module_and_optimizers` to set up both module and optimizer together. + + """ + raise NotImplementedError(self._err_msg_joint_setup_required()) + + @override + def module_init_context(self, empty_init: Optional[bool] = None) -> AbstractContextManager: + if self.zero_stage_3 and empty_init is False: + raise NotImplementedError( + f"`{empty_init=}` is not a valid choice with `DeepSpeedStrategy` when ZeRO stage 3 is enabled." + ) + module_sharded_ctx = self.module_sharded_context() + stack = ExitStack() + if not self.zero_stage_3: + stack.enter_context(super().module_init_context(empty_init=empty_init)) + stack.enter_context(module_sharded_ctx) + return stack + + @override + def module_sharded_context(self) -> AbstractContextManager: + # Current limitation in Fabric: The config needs to be fully determined at the time of calling the context + # manager. Later modifications through e.g. `Fabric.setup()` won't have an effect here. + + import deepspeed + + assert self._config_initialized + return deepspeed.zero.Init( + enabled=self.zero_stage_3, + remote_device=self.remote_device, + config_dict_or_path=self.config, + ) + + @override + def save_checkpoint( + self, + path: _PATH, + state: dict[str, Union[Module, Optimizer, Any]], + storage_options: Optional[Any] = None, + filter: Optional[dict[str, Callable[[str, Any], bool]]] = None, + ) -> None: + """Save model, optimizer, and other state in a checkpoint directory. + + Args: + path: A path to where the files should be saved + state: A dictionary with contents to be saved. If the dict contains modules or optimizers, their + state-dict will be retrieved and converted automatically. + storage_options: Unused by this strategy, since it doesn't use a ``CheckpointIO`` plugin. + filter: Unsupported. + + Raises: + TypeError: + If the unused ``storage_options`` gets passed. + ValueError: + When no :class:`deepspeed.DeepSpeedEngine` objects were found in the state, or when multiple + :class:`deepspeed.DeepSpeedEngine` objects were found. + + """ + if storage_options is not None: + raise TypeError( + "`DeepSpeedStrategy.save_checkpoint(..., storage_options=...)` is not supported because" + " `DeepSpeedStrategy` does not use the `CheckpointIO`." + ) + if filter is not None: + raise TypeError( + "`DeepSpeedStrategy.save_checkpoint(..., filter=...)` is not supported because" + " `DeepSpeedStrategy` manages the state serialization internally." + ) + + engines = _get_deepspeed_engines_from_state(state) + if len(engines) == 0: + raise ValueError( + "Could not find a DeepSpeed model in the provided checkpoint state. Please provide the model as" + " part of the state like so: `save_checkpoint(..., state={'model': model, ...})`. Make sure" + " you set up the model (and optimizers if any) through the strategy before saving the checkpoint." + ) + if len(engines) > 1: + raise ValueError( + "Found multiple DeepSpeed engine modules in the given state. Saving checkpoints with DeepSpeed is" + " currently limited to a single model per checkpoint. To save multiple models, call the" + " save method for each model separately with a different path." + ) + engine = engines[0] + + # broadcast the path from rank 0 to ensure all the states are saved in a common path + path = self.broadcast(path) + + # split the checkpoint into two parts: + # 1) the deepspeed engine encapsulating both the model and optionally the optimizer(s) + # 2) the rest of the user's state, which in deepspeed is called `client state` + excluded_objects = (engine, engine.optimizer) if engine.optimizer is not None else (engine,) + state = {k: v for k, v in state.items() if v not in excluded_objects} + _validate_state_keys(state) + # there might be other stateful objects unrelated to the deepspeed engine - convert them to a state_dict + state = self._convert_stateful_objects_in_state(state, filter={}) + # use deepspeed's internal checkpointing function to handle partitioned weights across processes + engine.save_checkpoint( + path, client_state=state, tag="checkpoint", exclude_frozen_parameters=self.exclude_frozen_parameters + ) + + @override + def load_checkpoint( + self, + path: _PATH, + state: Optional[Union[Module, Optimizer, dict[str, Union[Module, Optimizer, Any]]]] = None, + strict: bool = True, + weights_only: Optional[bool] = None, + ) -> dict[str, Any]: + """Load the contents from a checkpoint and restore the state of the given objects. + + Args: + path: A path to where the file is located + state: A dictionary of objects whose state will be restored in-place from the checkpoint path. + This should contain exactly one model, and the model must already be set up by DeepSpeed. + strict: Whether to enforce that the keys in `state` match the keys in the checkpoint. + + Returns: + Dictionary with the state inside DeepSpeed's engine + + Raises: + ValueError: + If no state is provided, when no :class:`deepspeed.DeepSpeedEngine` objects were found in the + state, or when multiple :class:`deepspeed.DeepSpeedEngine` objects were found. + RuntimeError: + If DeepSpeed was unable to load the checkpoint due to missing files or because the checkpoint is + not in the expected DeepSpeed format. + + """ + if isinstance(state, (Module, Optimizer)) or self.load_full_weights and self.zero_stage_3: + # This code path to enables loading a checkpoint from a non-deepspeed checkpoint or from + # a consolidated checkpoint + path = self.broadcast(path) + return super().load_checkpoint(path=path, state=state, strict=strict, weights_only=weights_only) + + if not state: + raise ValueError( + f"Got DeepSpeedStrategy.load_checkpoint(..., state={state!r}) but a state with at least " + f" a model instance to reload is required. Pass it in like so:" + " DeepSpeedStrategy.load_checkpoint(..., state={'model': model, ...})" + ) + _validate_checkpoint_directory(path) + + engines = _get_deepspeed_engines_from_state(state) + if len(engines) == 0: + raise ValueError( + "Could not find a DeepSpeed model in the provided checkpoint state. Please provide the model as" + " part of the state like so: `load_checkpoint(..., state={'model': model, ...})`. Make sure" + " you set up the model (and optimizers if any) through the strategy before loading the checkpoint." + ) + if len(engines) > 1: + raise ValueError( + "Found multiple DeepSpeed engine modules in the given state. Saving and loading checkpoints" + " with DeepSpeed is currently limited to a single model per checkpoint. To load multiple model" + " states, call the load method for each model checkpoint separately." + ) + engine = engines[0] + + from deepspeed.runtime.base_optimizer import DeepSpeedOptimizer + + optimzer_state_requested = any(isinstance(item, (Optimizer, DeepSpeedOptimizer)) for item in state.values()) + + torch.cuda.empty_cache() + _, client_state = engine.load_checkpoint( + path, + tag="checkpoint", + load_optimizer_states=optimzer_state_requested, + load_lr_scheduler_states=False, + load_module_strict=strict, + ) + + if client_state is None: + raise RuntimeError( + "DeepSpeed was unable to load the checkpoint. Ensure you passed in a DeepSpeed compatible checkpoint" + " or a single checkpoint file by setting `DeepSpeedStrategy(..., load_full_weights=True)`." + ) + + # `Engine.load_checkpoint` adds useless keys 'optimizer' and 'lr_scheduler' to the client state; remove + # them to avoid name collision with user state + keys = set(client_state) & set(state) - {"optimizer", "lr_scheduler"} + _move_state_into(source=client_state, destination=state, keys=keys) + return client_state + + @override + def clip_gradients_norm( + self, + module: "DeepSpeedEngine", + optimizer: Optimizer, + max_norm: Union[float, int], + norm_type: Union[float, int] = 2.0, + error_if_nonfinite: bool = True, + ) -> torch.Tensor: + raise NotImplementedError( + "DeepSpeed handles gradient clipping automatically within the optimizer. " + "Make sure to set the `gradient_clipping` value in your Config." + ) + + @override + def clip_gradients_value( + self, module: "DeepSpeedEngine", optimizer: Optimizer, clip_val: Union[float, int] + ) -> None: + raise NotImplementedError( + "DeepSpeed handles gradient clipping automatically within the optimizer. " + "Make sure to set the `gradient_clipping` value in your Config." + ) + + @classmethod + @override + def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: + strategy_registry.register("deepspeed", cls, description="Default DeepSpeed Strategy") + strategy_registry.register("deepspeed_stage_1", cls, description="DeepSpeed with ZeRO Stage 1 enabled", stage=1) + strategy_registry.register( + "deepspeed_stage_1_offload", + cls, + description="DeepSpeed with ZeRO Stage 1 and optimizer CPU Offload", + stage=1, + offload_optimizer=True, + ) + strategy_registry.register("deepspeed_stage_2", cls, description="DeepSpeed with ZeRO Stage 2 enabled", stage=2) + strategy_registry.register( + "deepspeed_stage_2_offload", + cls, + description="DeepSpeed ZeRO Stage 2 and CPU Offload", + stage=2, + offload_optimizer=True, + ) + strategy_registry.register("deepspeed_stage_3", cls, description="DeepSpeed ZeRO Stage 3", stage=3) + strategy_registry.register( + "deepspeed_stage_3_offload", + cls, + description="DeepSpeed ZeRO Stage 3 and CPU Offload", + stage=3, + offload_optimizer=True, + offload_parameters=True, + ) + strategy_registry.register( + "deepspeed_stage_3_offload_nvme", + cls, + description="DeepSpeed ZeRO Stage 3 and NVMe Offload", + stage=3, + offload_optimizer=True, + offload_parameters=True, + remote_device="nvme", + offload_params_device="nvme", + offload_optimizer_device="nvme", + ) + + def _initialize_engine( + self, model: Module, optimizer: Optional[Optimizer] = None, scheduler: Optional["_LRScheduler"] = None + ) -> tuple["DeepSpeedEngine", Optimizer, Any]: + """Initialize one model and one optimizer with an optional learning rate scheduler. + + This calls ``deepspeed.initialize`` internally. + + """ + import deepspeed + + model_parameters = filter(lambda p: p.requires_grad, model.parameters()) + deepspeed_engine, deepspeed_optimizer, _, deepspeed_scheduler = deepspeed.initialize( + args=argparse.Namespace(device_rank=self.root_device.index), + config=self.config, + model=model, + model_parameters=model_parameters, + optimizer=optimizer, + lr_scheduler=scheduler, + dist_init_required=False, + ) + return deepspeed_engine, deepspeed_optimizer, deepspeed_scheduler + + @override + def setup_environment(self) -> None: + if not isinstance(self.accelerator, CUDAAccelerator): + raise RuntimeError( + f"The DeepSpeed strategy is only supported on CUDA GPUs but `{self.accelerator.__class__.__name__}`" + " is used." + ) + super().setup_environment() + + @override + def _setup_distributed(self) -> None: + assert self.parallel_devices is not None + _validate_device_index_selection(self.parallel_devices) + reset_seed() + self._set_world_ranks() + self._init_deepspeed_distributed() + if not self._config_initialized: + self._format_config() + self._config_initialized = True + + def _init_deepspeed_distributed(self) -> None: + import deepspeed + + assert self.cluster_environment is not None + if platform.system() != "Windows": + # do not set env variables on windows, allow deepspeed to control setup + self._set_node_environment_variables() + log.info( + "initializing deepspeed distributed: " + f"GLOBAL_RANK: {self.global_rank}, " + f"MEMBER: {self.global_rank + 1}/{self.world_size}" + ) + self._process_group_backend = self._get_process_group_backend() + deepspeed.init_distributed( + self._process_group_backend, distributed_port=self.cluster_environment.main_port, timeout=self._timeout + ) + + def _set_node_environment_variables(self) -> None: + assert self.cluster_environment is not None + os.environ["MASTER_ADDR"] = self.cluster_environment.main_address + os.environ["MASTER_PORT"] = str(self.cluster_environment.main_port) + os.environ["RANK"] = str(self.global_rank) + os.environ["WORLD_SIZE"] = str(self.world_size) + os.environ["LOCAL_RANK"] = str(self.local_rank) + + def _set_deepspeed_activation_checkpointing(self) -> None: + import deepspeed + + assert isinstance(self.config, dict) + if self.config.get("activation_checkpointing"): + checkpoint_config = self.config["activation_checkpointing"] + deepspeed.checkpointing.configure( + mpu_=None, + partition_activations=checkpoint_config.get("partition_activations"), + contiguous_checkpointing=checkpoint_config.get("contiguous_memory_optimization"), + checkpoint_in_cpu=checkpoint_config.get("cpu_checkpointing"), + profile=checkpoint_config.get("profile"), + ) + + def _format_config(self) -> None: + if self.config is None: + raise ValueError( + "To use DeepSpeed you must pass in a DeepSpeed config dict, or a path to a JSON config." + " See: https://lightning.ai/docs/pytorch/stable/advanced/model_parallel.html#deepspeed" + ) + + self.config.setdefault("train_micro_batch_size_per_gpu", 1) + _format_precision_config( + config=self.config, + precision=self.precision.precision, + loss_scale=self.loss_scale, + loss_scale_window=self.loss_scale_window, + min_loss_scale=self.min_loss_scale, + initial_scale_power=self.initial_scale_power, + hysteresis=self.hysteresis, + ) + + def _create_default_config( + self, + zero_optimization: bool, + zero_allow_untested_optimizer: bool, + logging_batch_size_per_gpu: Optional[int], + partition_activations: bool, + cpu_checkpointing: bool, + contiguous_memory_optimization: bool, + synchronize_checkpoint_boundary: bool, + offload_optimizer: bool, + offload_parameters: bool, + nvme_path: str, + offload_params_device: str, + params_buffer_count: int, + params_buffer_size: int, + max_in_cpu: int, + offload_optimizer_device: str, + optimizer_buffer_count: int, + pin_memory: bool, + block_size: int, + queue_depth: int, + single_submit: bool, + overlap_events: bool, + thread_count: int, + **zero_kwargs: Any, + ) -> dict: + cfg = { + "activation_checkpointing": { + "partition_activations": partition_activations, + "cpu_checkpointing": cpu_checkpointing, + "contiguous_memory_optimization": contiguous_memory_optimization, + "synchronize_checkpoint_boundary": synchronize_checkpoint_boundary, + }, + "aio": { + "block_size": block_size, + "queue_depth": queue_depth, + "single_submit": single_submit, + "overlap_events": overlap_events, + "thread_count": thread_count, + }, + } + if zero_optimization: + zero_config = zero_kwargs + + if offload_optimizer: + zero_config["offload_optimizer"] = { + "device": offload_optimizer_device, + "nvme_path": nvme_path, + "buffer_count": optimizer_buffer_count, + "pin_memory": pin_memory, + } + if offload_parameters: + zero_config["offload_param"] = { + "device": offload_params_device, + "nvme_path": nvme_path, + "buffer_count": params_buffer_count, + "buffer_size": params_buffer_size, + "max_in_cpu": max_in_cpu, + "pin_memory": pin_memory, + } + cfg.update({ + "zero_allow_untested_optimizer": zero_allow_untested_optimizer, + "zero_optimization": zero_config, + }) + if logging_batch_size_per_gpu: + cfg["train_micro_batch_size_per_gpu"] = logging_batch_size_per_gpu + return cfg + + def _restore_zero_state(self, module: Module, ckpt: Mapping[str, Any]) -> None: + """Overrides the normal load_state_dict behaviour in PyTorch to ensure we gather parameters that may be sharded + across processes before loading the state dictionary when using ZeRO stage 3. This is then automatically synced + across processes. + + Args: + ckpt: The ckpt file. + + """ + import deepspeed + + def load(module: torch.nn.Module, prefix: str = "") -> None: + missing_keys: list[str] = [] + unexpected_keys: list[str] = [] + error_msgs: list[str] = [] + state_dict = ckpt["state_dict"] + + # copy state_dict so _load_from_state_dict can modify it + metadata = getattr(state_dict, "_metadata", None) + state_dict = state_dict.copy() + if metadata is not None: + state_dict._metadata = metadata + + local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {}) + # because zero3 puts placeholders in model params, this context + # manager gathers (unpartitions) the params of the current layer, then loads from + # the state dict and then re-partitions them again + with deepspeed.zero.GatheredParameters(list(module.parameters(recurse=False)), modifier_rank=0): + if self.is_global_zero: + module._load_from_state_dict( + state_dict=state_dict, + prefix=prefix, + local_metadata=local_metadata, + strict=True, + missing_keys=missing_keys, + unexpected_keys=unexpected_keys, + error_msgs=error_msgs, + ) + + for name, child in module._modules.items(): + if child is not None: + load(child, prefix + name + ".") + + load(module, prefix="") + + def _load_config(self, config: Optional[Union[_PATH, dict[str, Any]]]) -> Optional[dict[str, Any]]: + if config is None and self.DEEPSPEED_ENV_VAR in os.environ: + rank_zero_info(f"Loading DeepSpeed config from set {self.DEEPSPEED_ENV_VAR} environment variable") + config = os.environ[self.DEEPSPEED_ENV_VAR] + if isinstance(config, (str, Path)): + if not os.path.isfile(config): + raise FileNotFoundError( + f"You passed in a path to a DeepSpeed config but the path does not exist: {config}" + ) + with open(config) as f: + config = json.load(f) + assert isinstance(config, dict) or config is None + return config + + +def _get_deepspeed_engines_from_state(state: dict[str, Any]) -> list["DeepSpeedEngine"]: + from deepspeed import DeepSpeedEngine + + modules = chain(*(module.modules() for module in state.values() if isinstance(module, Module))) + return [engine for engine in modules if isinstance(engine, DeepSpeedEngine)] + + +def _validate_state_keys(state: dict[str, Any]) -> None: + # DeepSpeed merges the client state into its internal engine state when saving, but it does not check for + # colliding keys from the user. We explicitly check it here: + deepspeed_internal_keys = { + "module", + "buffer_names", + "optimizer", + "param_shapes", + "lr_scheduler", + "sparse_tensor_module_names", + "skipped_steps", + "global_steps", + "global_samples", + "dp_world_size", + "mp_world_size", + "ds_config", + "ds_version", + } + colliding_keys = deepspeed_internal_keys.intersection(state.keys()) + if colliding_keys: + rank_zero_warn( + "Your state has keys that collide with DeepSpeed's internal engine state. This could result in your" + " values being overwritten by DeepSpeed. Consider changing the name of these keys to something else: " + + ", ".join(colliding_keys) + ) + + +def _validate_device_index_selection(parallel_devices: list[torch.device]) -> None: + selected_device_indices = [device.index for device in parallel_devices] + expected_device_indices = list(range(len(parallel_devices))) + if selected_device_indices != expected_device_indices: + raise RuntimeError( + f"The selected device indices {selected_device_indices!r} don't match the local rank values of processes." + " If you need to select GPUs at a specific index, set the `CUDA_VISIBLE_DEVICES` environment variable" + f" instead. For example: `CUDA_VISIBLE_DEVICES={','.join(str(i) for i in selected_device_indices)}`." + ) + + +def _is_deepspeed_checkpoint(path: Path) -> bool: + """Heuristic check whether the path points to a top-level DeepSpeed checkpoint directory.""" + return path.is_dir() and (path / "checkpoint").is_dir() + + +def _validate_checkpoint_directory(path: _PATH) -> None: + """Validates that the path points to a DeepSpeed checkpoint directory and suggests fixes for user error.""" + # Example DeepSpeed checkpoint directory: + # + # epoch=5-step=10999.ckpt + # ├── checkpoint + # │ ├── zero_pp_rank_0_mp_rank_00_model_states.pt + # │ ├── zero_pp_rank_0_mp_rank_00_optim_states.pt + # │ ├── zero_pp_rank_1_mp_rank_00_model_states.pt + # │ └── zero_pp_rank_1_mp_rank_00_optim_states.pt + # ├── latest + # └── zero_to_fp32.py + + path = Path(path) + path_is_ds_checkpoint = _is_deepspeed_checkpoint(path) + default_message = f"The provided path is not a valid DeepSpeed checkpoint: {path}" + + if not path_is_ds_checkpoint: + # Case 1: User may have accidentally passed the subfolder "checkpoint" + parent_is_ds_checkpoint = _is_deepspeed_checkpoint(path.parent) + if parent_is_ds_checkpoint: + raise FileNotFoundError( + f"{default_message}. It looks like you passed the path to a subfolder." + f" Try to load using this parent directory instead: {path.parent}" + ) + # Case 2: User may have accidentally passed the path to a file inside the "checkpoint" subfolder + parent_parent_is_ds_checkpoint = path.is_file() and _is_deepspeed_checkpoint(path.parent.parent) + if parent_parent_is_ds_checkpoint: + raise FileNotFoundError( + f"{default_message}. It looks like you passed the path to a file inside a DeepSpeed checkpoint folder." + f" Try to load using this parent directory instead: {path.parent.parent}" + ) + raise FileNotFoundError(default_message) + + +def _format_precision_config( + config: dict[str, Any], + precision: str, + loss_scale: float, + loss_scale_window: int, + min_loss_scale: int, + initial_scale_power: int, + hysteresis: int, +) -> None: + if "fp16" not in config and precision in ("16-mixed", "16-true"): + # FP16 is a DeepSpeed standalone AMP implementation + rank_zero_info("Enabling DeepSpeed FP16. Model parameters and inputs will be cast to `float16`.") + config["fp16"] = { + "enabled": True, + "loss_scale": loss_scale, + "initial_scale_power": initial_scale_power, + "loss_scale_window": loss_scale_window, + "hysteresis": hysteresis, + "min_loss_scale": min_loss_scale, + } + elif "bf16" not in config and precision in ("bf16-mixed", "bf16-true"): + rank_zero_info("Enabling DeepSpeed BF16. Model parameters and inputs will be cast to `bfloat16`.") + config["bf16"] = {"enabled": True} diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/dp.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/dp.py new file mode 100644 index 0000000000000000000000000000000000000000..85e119e26860480ac270b8316b3bc366fce61360 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/dp.py @@ -0,0 +1,114 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional, Union + +import torch +from torch import Tensor +from torch.nn import DataParallel, Module +from typing_extensions import override + +from lightning_fabric.accelerators import Accelerator +from lightning_fabric.plugins.io.checkpoint_io import CheckpointIO +from lightning_fabric.plugins.precision import Precision +from lightning_fabric.strategies.parallel import ParallelStrategy +from lightning_fabric.strategies.registry import _StrategyRegistry +from lightning_fabric.strategies.strategy import TBroadcast, TReduce +from lightning_fabric.utilities.apply_func import apply_to_collection +from lightning_fabric.utilities.distributed import ReduceOp + + +class DataParallelStrategy(ParallelStrategy): + """Implements data-parallel training in a single process, i.e., the model gets replicated to each device and each + gets a split of the data.""" + + def __init__( + self, + accelerator: Optional[Accelerator] = None, + parallel_devices: Optional[list[torch.device]] = None, + checkpoint_io: Optional[CheckpointIO] = None, + precision: Optional[Precision] = None, + ): + super().__init__( + accelerator=accelerator, + parallel_devices=parallel_devices, + cluster_environment=None, + checkpoint_io=checkpoint_io, + precision=precision, + ) + + @property + @override + def root_device(self) -> torch.device: + assert self.parallel_devices is not None + return self.parallel_devices[0] + + @property + @override + def distributed_sampler_kwargs(self) -> None: + return None + + @override + def setup_module(self, module: Module) -> DataParallel: + """Wraps the given model into a :class:`~torch.nn.DataParallel` module.""" + return DataParallel(module=module, device_ids=self.parallel_devices) + + @override + def module_to_device(self, module: Module) -> None: + module.to(self.root_device) + + @override + def batch_to_device(self, batch: Any, device: Optional[torch.device] = None) -> Any: + # DataParallel handles the transfer of batch to the device + return batch + + @override + def all_reduce( + self, collection: TReduce, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean" + ) -> TReduce: + def mean(t: Tensor) -> Tensor: + original_dtype = t.dtype + return t.float().mean().to(original_dtype) + + return apply_to_collection(collection, Tensor, mean) + + @override + def barrier(self, *args: Any, **kwargs: Any) -> None: + pass + + @override + def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast: + return obj + + @override + def reduce_boolean_decision(self, decision: bool, all: bool = True) -> bool: + return decision + + @override + def get_module_state_dict(self, module: Module) -> dict[str, Union[Any, Tensor]]: + if isinstance(module, DataParallel): + module = module.module + return super().get_module_state_dict(module) + + @override + def load_module_state_dict( + self, module: Module, state_dict: dict[str, Union[Any, Tensor]], strict: bool = True + ) -> None: + if isinstance(module, DataParallel): + module = module.module + super().load_module_state_dict(module=module, state_dict=state_dict, strict=strict) + + @classmethod + @override + def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: + strategy_registry.register("dp", cls, description=cls.__name__) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/fsdp.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/fsdp.py new file mode 100644 index 0000000000000000000000000000000000000000..fa2ca145e00de074bc014122d743ef57ca123301 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/fsdp.py @@ -0,0 +1,894 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import shutil +import warnings +from collections.abc import Generator +from contextlib import AbstractContextManager, ExitStack, nullcontext +from datetime import timedelta +from functools import partial +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Literal, + Optional, + Union, +) + +import torch +from lightning_utilities.core.imports import RequirementCache +from lightning_utilities.core.rank_zero import rank_zero_only as utils_rank_zero_only +from torch import Tensor +from torch.nn import Module +from torch.optim import Optimizer +from typing_extensions import TypeGuard, override + +from lightning_fabric.accelerators import Accelerator +from lightning_fabric.plugins import CheckpointIO, ClusterEnvironment, Precision +from lightning_fabric.plugins.collectives.torch_collective import default_pg_timeout +from lightning_fabric.plugins.precision.fsdp import FSDPPrecision +from lightning_fabric.strategies.launchers.subprocess_script import _SubprocessScriptLauncher +from lightning_fabric.strategies.parallel import ParallelStrategy +from lightning_fabric.strategies.registry import _StrategyRegistry +from lightning_fabric.strategies.strategy import ( + TBroadcast, + _apply_filter, + _BackwardSyncControl, + _Sharded, + _validate_keys_for_strict_loading, +) +from lightning_fabric.utilities.distributed import ( + ReduceOp, + _distributed_is_initialized, + _get_default_process_group_backend_for_device, + _init_dist_connection, + _sync_ddp_if_available, +) +from lightning_fabric.utilities.distributed import group as _group +from lightning_fabric.utilities.imports import ( + _TORCH_GREATER_EQUAL_2_2, + _TORCH_GREATER_EQUAL_2_3, +) +from lightning_fabric.utilities.init import _has_meta_device_parameters_or_buffers +from lightning_fabric.utilities.load import _METADATA_FILENAME, _lazy_load, _materialize_tensors, _move_state_into +from lightning_fabric.utilities.rank_zero import rank_zero_deprecation, rank_zero_only, rank_zero_warn +from lightning_fabric.utilities.seed import reset_seed +from lightning_fabric.utilities.types import _PATH, _Stateful + +if TYPE_CHECKING: + from torch.distributed.device_mesh import DeviceMesh + from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload, MixedPrecision, ShardingStrategy + from torch.distributed.fsdp.wrap import ModuleWrapPolicy + from torch.optim.lr_scheduler import _LRScheduler + + _POLICY = Union[set[type[Module]], Callable[[Module, bool, int], bool], ModuleWrapPolicy] + _SHARDING_STRATEGY = Union[ShardingStrategy, Literal["FULL_SHARD", "SHARD_GRAD_OP", "NO_SHARD", "HYBRID_SHARD"]] + + +_FSDP_ALIASES = ("fsdp", "fsdp_cpu_offload") + +# TODO: Switch to new state-dict APIs +warnings.filterwarnings("ignore", category=FutureWarning, message=".*FSDP.state_dict_type.*") # from torch >= 2.4 + + +class FSDPStrategy(ParallelStrategy, _Sharded): + r"""Strategy for Fully Sharded Data Parallel provided by torch.distributed. + + Fully Sharded Training shards the entire model across all available GPUs, allowing you to scale model + size, whilst using efficient communication to reduce overhead. In practice, this means we can remain + at parity with PyTorch DDP, whilst scaling our model sizes dramatically. The technique is similar + to ZeRO-Stage 3. + + For more information check out + `this blogpost `__. + + Defaults have been set and options have been exposed, but may require configuration + based on your level of memory/speed efficiency. We suggest having a look at + `this tutorial `__ for more information. + + Arguments: + cpu_offload: See ``cpu_offload`` parameter in :class:`torch.distributed.fsdp.FullyShardedDataParallel`. + mixed_precision: See ``mixed_precision`` parameter in :class:`torch.distributed.fsdp.FullyShardedDataParallel`. + auto_wrap_policy: Same as ``auto_wrap_policy`` parameter in + :class:`torch.distributed.fsdp.FullyShardedDataParallel`. For convenience, this also accepts a set of the + layer classes to wrap. + activation_checkpointing: Deprecated. Use ``activation_checkpointing_policy``. + activation_checkpointing_policy: Same as ``auto_wrap_policy`` parameter in + :class:`torch.distributed.fsdp.FullyShardedDataParallel` but used when selecting the modules for which you + want to enable activation checkpointing. Enabling this can free up a significant amount of memory at the + cost of speed since activations in these layers need to be recomputed during backpropagation. For + convenience, this also accepts a set of the layer classes to wrap. + sharding_strategy: Select whether to shard model parameters, gradients, optimizer states, or a combination of + them. Available values are: + + - ``"FULL_SHARD"``: Shards model parameters, gradients, and optimizer states (default). + - ``"SHARD_GRAD_OP"``: Shards gradients and optimizer states only. Model parameters get replicated. + - ``"NO_SHARD"``: No sharding (identical to regular DDP). + - ``"HYBRID_SHARD"``: Shards model parameters, gradients, and optimizer states within a single machine, but + replicates across machines. See also the `device_mesh` parameter below. + + Also accepts a :class:`torch.distributed.fsdp.ShardingStrategy` enum value. + + device_mesh: A tuple `(replication size, sharding size)` that defines over how many devices to shard and + replicate the model. The product of the two numbers must equal the world size. Only valid in combination + with the `HYBRID_SHARD` sharding strategy. + + state_dict_type: The format in which the state of the model and optimizers gets saved into the checkpoint. + + - ``"full"``: The full weights and optimizer states get assembled on rank 0 and saved to a single file. + - ``"sharded"``: Each rank saves its shard of weights and optimizer states to a file. The checkpoint is + a folder with as many files as the world size. + + \**kwargs: See available parameters in :class:`torch.distributed.fsdp.FullyShardedDataParallel`. + + """ + + def __init__( + self, + accelerator: Optional[Accelerator] = None, + parallel_devices: Optional[list[torch.device]] = None, + cluster_environment: Optional[ClusterEnvironment] = None, + precision: Optional[Precision] = None, + process_group_backend: Optional[str] = None, + timeout: Optional[timedelta] = default_pg_timeout, + cpu_offload: Union[bool, "CPUOffload", None] = None, + mixed_precision: Optional["MixedPrecision"] = None, + auto_wrap_policy: Optional["_POLICY"] = None, + activation_checkpointing: Optional[Union[type[Module], list[type[Module]]]] = None, + activation_checkpointing_policy: Optional["_POLICY"] = None, + sharding_strategy: "_SHARDING_STRATEGY" = "FULL_SHARD", + state_dict_type: Literal["full", "sharded"] = "sharded", + device_mesh: Optional[Union[tuple[int, int], "DeviceMesh"]] = None, + **kwargs: Any, + ) -> None: + super().__init__( + accelerator=accelerator, + parallel_devices=parallel_devices, + cluster_environment=cluster_environment, + precision=precision, + ) + self._num_nodes = 1 + self._process_group_backend: Optional[str] = process_group_backend + self._timeout: Optional[timedelta] = timeout + self._backward_sync_control = _FSDPBackwardSyncControl() + self._fsdp_kwargs = _auto_wrap_policy_kwargs(auto_wrap_policy, kwargs) + + # Enables joint setup of model and optimizer, multiple optimizer param groups, and `torch.compile()` + self._fsdp_kwargs.setdefault("use_orig_params", True) + + if device_mesh is not None: + if not _TORCH_GREATER_EQUAL_2_2: + raise ValueError("The `device_mesh` argument is only supported in torch >= 2.2.") + self._fsdp_kwargs["device_mesh"] = device_mesh + + self._activation_checkpointing_kwargs = _activation_checkpointing_kwargs( + activation_checkpointing, activation_checkpointing_policy + ) + self._state_dict_type = state_dict_type + self.sharding_strategy = _init_sharding_strategy(sharding_strategy, self._fsdp_kwargs) + self.cpu_offload = _init_cpu_offload(cpu_offload) + self.mixed_precision = mixed_precision + + @property + @override + def checkpoint_io(self) -> CheckpointIO: + raise NotImplementedError(f"The `{type(self).__name__}` does not use the `CheckpointIO` plugin interface.") + + @checkpoint_io.setter + @override + def checkpoint_io(self, io: CheckpointIO) -> None: + raise NotImplementedError(f"The `{type(self).__name__}` does not support setting a `CheckpointIO` plugin.") + + @property + @override + def root_device(self) -> torch.device: + assert self.parallel_devices is not None + return self.parallel_devices[self.local_rank] + + @property + def num_nodes(self) -> int: + return self._num_nodes + + @num_nodes.setter + def num_nodes(self, num_nodes: int) -> None: + self._num_nodes = num_nodes + + @property + def num_processes(self) -> int: + return len(self.parallel_devices) if self.parallel_devices is not None else 0 + + @property + @override + def distributed_sampler_kwargs(self) -> dict[str, Any]: + return {"num_replicas": (self.num_nodes * self.num_processes), "rank": self.global_rank} + + @property + def process_group_backend(self) -> Optional[str]: + return self._process_group_backend + + @property + def mixed_precision_config(self) -> Optional["MixedPrecision"]: + if self.mixed_precision: + return self.mixed_precision + plugin = self.precision + if isinstance(plugin, FSDPPrecision): + return plugin.mixed_precision_config + return None + + @property + @override + def precision(self) -> FSDPPrecision: + plugin = self._precision + if plugin is not None: + assert isinstance(plugin, FSDPPrecision) + return plugin + return FSDPPrecision("32-true") + + @precision.setter + @override + def precision(self, precision: Optional[Precision]) -> None: + if precision is not None and not isinstance(precision, FSDPPrecision): + raise TypeError(f"The FSDP strategy can only work with the `FSDPPrecision` plugin, found {precision}") + self._precision = precision + + @override + def _configure_launcher(self) -> None: + assert self.cluster_environment is not None + if not self.cluster_environment.creates_processes_externally: + self._launcher = _SubprocessScriptLauncher(self.cluster_environment, self.num_processes, self.num_nodes) + + @override + def setup_environment(self) -> None: + super().setup_environment() + self._setup_distributed() + + # if 'device_mesh' in the `_fsdp_kwargs` is provided as a tuple, update it into the `DeviceMesh` object here + if isinstance(self._fsdp_kwargs.get("device_mesh"), tuple): + from torch.distributed.device_mesh import init_device_mesh + + self._fsdp_kwargs["device_mesh"] = init_device_mesh("cuda", self._fsdp_kwargs["device_mesh"]) + + @override + def setup_module_and_optimizers( + self, module: Module, optimizers: list[Optimizer], scheduler: Optional["_LRScheduler"] = None + ) -> tuple[Module, list[Optimizer], Optional["_LRScheduler"]]: + """Wraps the model into a :class:`~torch.distributed.fsdp.fully_sharded_data_parallel.FullyShardedDataParallel` + module and sets `use_orig_params=True` to keep the reference to the original parameters in the optimizer.""" + use_orig_params = self._fsdp_kwargs.get("use_orig_params") + if use_orig_params is False: + raise ValueError( + f"You set `{type(self).__name__}(use_orig_params=False)` but this is not supported when" + " setting the model and optimizer up jointly. Either set it to `True` or set the objects" + " up in this order: Create the model, call `setup_module`, create the optimizer," + " call `setup_optimizer`." + ) + module = self.setup_module(module) + return module, optimizers, scheduler + + @override + def setup_module(self, module: Module) -> Module: + """Wraps the model into a :class:`~torch.distributed.fsdp.fully_sharded_data_parallel.FullyShardedDataParallel` + module.""" + from torch.distributed.fsdp import FullyShardedDataParallel + + if any(isinstance(mod, FullyShardedDataParallel) for mod in module.modules()): + # The user has wrapped their submodules manually, don't apply the auto wrap policy. + if _has_meta_device_parameters_or_buffers(module): + rank_zero_warn( + "The model is already wrapped in `FSDP` but there are still parameters on the meta device." + ) + if "auto_wrap_policy" in self._fsdp_kwargs: + rank_zero_warn( + "A FSDP `auto_wrap_policy` is set, but the model is already wrapped. The policy will be ignored." + ) + del self._fsdp_kwargs["auto_wrap_policy"] + else: + module = FullyShardedDataParallel( + module=module, + cpu_offload=self.cpu_offload, + mixed_precision=self.mixed_precision_config, + sharding_strategy=self.sharding_strategy, + device_id=self.root_device.index, + **self._fsdp_kwargs, + ) + + _move_torchmetrics_to_device(module, self.root_device) + + # activation checkpointing needs to be set up after wrapping the model + _setup_activation_checkpointing(module, self._activation_checkpointing_kwargs) + + return module + + @override + def setup_optimizer(self, optimizer: Optimizer) -> Optimizer: + """Set up an optimizer for a model wrapped with FSDP. + + This setup method doesn't modify the optimizer or wrap the optimizer. The only thing it currently does is verify + that the optimizer was created after the model was wrapped with :meth:`setup_module` with a reference to the + flattened parameters. + + """ + if self._fsdp_kwargs.get("use_orig_params"): + return super().setup_optimizer(optimizer) + if not _optimizer_has_flat_params(optimizer): + # We avoid this limitation by setting `use_orig_params=True` + raise ValueError( + "The optimizer does not seem to reference any FSDP parameters. HINT: Make sure to create the optimizer" + " after setting up the model." + ) + return optimizer + + @override + def module_to_device(self, module: Module) -> None: + pass + + @override + def module_init_context(self, empty_init: Optional[bool] = None) -> AbstractContextManager: + precision_init_ctx = self.precision.module_init_context() + module_sharded_ctx = self.module_sharded_context() + stack = ExitStack() + if empty_init: + # Materialization happens in `setup`. When modules get wrapped by FSDP, the sequence of operations is: + # 1) materialize module 2) call `reset_parameters()` 3) shard the module. + # These operations are applied to each submodule 'bottom up' in the module hierarchy. + stack.enter_context(torch.device("meta")) + stack.enter_context(precision_init_ctx) + stack.enter_context(module_sharded_ctx) + return stack + + @override + def module_sharded_context(self) -> AbstractContextManager: + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel + from torch.distributed.fsdp.wrap import enable_wrap + + return enable_wrap( + wrapper_cls=FullyShardedDataParallel, + cpu_offload=self.cpu_offload, + mixed_precision=self.mixed_precision_config, + sharding_strategy=self.sharding_strategy, + device_id=self.root_device.index, + **self._fsdp_kwargs, + ) + + @override + def all_reduce( + self, tensor: Tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean" + ) -> Tensor: + if isinstance(tensor, Tensor): + return _sync_ddp_if_available(tensor, group, reduce_op=reduce_op) + return tensor + + @override + def barrier(self, *args: Any, **kwargs: Any) -> None: + if not _distributed_is_initialized(): + return + if torch.distributed.get_backend() == "nccl": + torch.distributed.barrier(device_ids=[self.root_device.index]) + else: + torch.distributed.barrier() + + @override + def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast: + if not _distributed_is_initialized(): + return obj + + obj = [obj] + torch.distributed.broadcast_object_list(obj, src, group=_group.WORLD) + return obj[0] + + @override + def clip_gradients_norm( + self, + module: Module, + optimizer: Optimizer, + max_norm: Union[float, int], + norm_type: Union[float, int] = 2.0, + error_if_nonfinite: bool = True, + ) -> Tensor: + """Clip gradients by norm.""" + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel + + if not isinstance(module, FullyShardedDataParallel): + # the root must be wrapped + raise TypeError( + "Gradient clipping with FSDP is only possible if the module passed to" + f" `{type(self).__name__}.clip_gradients_norm` is wrapped in `FullyShardedDataParallel`." + f" Got: {module.__class__.__name__}." + ) + self.precision.unscale_gradients(optimizer) + return module.clip_grad_norm_(max_norm=max_norm, norm_type=norm_type) + + @override + def save_checkpoint( + self, + path: _PATH, + state: dict[str, Union[Module, Optimizer, Any]], + storage_options: Optional[Any] = None, + filter: Optional[dict[str, Callable[[str, Any], bool]]] = None, + ) -> None: + """Save model, optimizer, and other state to a checkpoint on disk. + + If the state-dict-type is ``'full'``, the checkpoint will be written to a single file containing the weights, + optimizer state and other metadata. If the state-dict-type is ``'sharded'``, the checkpoint gets saved as a + directory containing one file per process, with model- and optimizer shards stored per file. Additionally, it + creates a metadata file `meta.pt` with the rest of the user's state (only saved from rank 0). + + """ + if storage_options is not None: + raise TypeError( + "`FSDPStrategy.save_checkpoint(..., storage_options=...)` is not supported because" + " `FSDPStrategy` does not use the `CheckpointIO`." + ) + if filter is not None and self._state_dict_type == "sharded": + # https://github.com/pytorch/pytorch/issues/105379 + raise NotImplementedError( + "FSDP doesn't support loading sharded filtered checkpoints, so saving them is disabled." + ) + + # broadcast the path from rank 0 to ensure all the states are saved in a common path + path = Path(self.broadcast(path)) + if path.is_dir() and self._state_dict_type == "full" and not _is_sharded_checkpoint(path): + raise IsADirectoryError(f"The checkpoint path exists and is a directory: {path}") + + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + + modules = [module for module in state.values() if _has_fsdp_modules(module)] + if len(modules) == 0: + raise ValueError( + "Could not find a FSDP model in the provided checkpoint state. Please provide the model as" + " part of the state like so: `save_checkpoint(..., state={'model': model, ...})`. Make sure" + " you set up the model (and optimizers if any) through the strategy before saving the checkpoint." + ) + if len(modules) > 1: + raise ValueError( + "Found multiple FSDP models in the given state. Saving checkpoints with FSDP is" + " currently limited to a single model per checkpoint. To save multiple models, call the" + " save method for each model separately with a different path." + ) + module = modules[0] + + if self._state_dict_type == "sharded": + if path.is_file(): + path.unlink() + path.mkdir(parents=True, exist_ok=True) + + state_dict_ctx = _get_sharded_state_dict_context(module) + + # replace the modules and optimizer objects in the state with their local state dict + # and separate the user's metadata + converted_state: dict[str, Any] = {} + metadata: dict[str, Any] = {} + with state_dict_ctx: + for key, obj in state.items(): + converted: Any + if isinstance(obj, Module): + converted = obj.state_dict() + target_dict = converted_state + elif isinstance(obj, Optimizer): + converted = FSDP.optim_state_dict(module, obj) + target_dict = converted_state + else: # everything not a module or optimizer is considered metadata + converted = obj.state_dict() if isinstance(obj, _Stateful) else obj + target_dict = metadata + _apply_filter(key, filter or {}, converted, target_dict) + + _distributed_checkpoint_save(converted_state, path) + + if self.global_rank == 0: + torch.save(metadata, path / _METADATA_FILENAME) + + elif self._state_dict_type == "full": + if _is_sharded_checkpoint(path): + shutil.rmtree(path) + + state_dict_ctx = _get_full_state_dict_context(module, world_size=self.world_size) + full_state: dict[str, Any] = {} + with state_dict_ctx: + for key, obj in state.items(): + if isinstance(obj, Module): + converted = obj.state_dict() + elif isinstance(obj, Optimizer): + converted = FSDP.optim_state_dict(module, obj) + else: # everything not a module or optimizer is considered metadata + converted = obj.state_dict() if isinstance(obj, _Stateful) else obj + _apply_filter(key, filter or {}, converted, full_state) + + if self.global_rank == 0: + torch.save(full_state, path) + else: + raise ValueError(f"Unknown state_dict_type: {self._state_dict_type}") + + @override + def load_checkpoint( + self, + path: _PATH, + state: Optional[Union[Module, Optimizer, dict[str, Union[Module, Optimizer, Any]]]] = None, + strict: bool = True, + weights_only: Optional[bool] = None, + ) -> dict[str, Any]: + """Load the contents from a checkpoint and restore the state of the given objects.""" + if not state: + raise ValueError( + f"Got FSDPStrategy.load_checkpoint(..., state={state!r}) but a state with at least " + f" a model instance to reload is required. Pass it in like so:" + " FSDPStrategy.load_checkpoint(..., state={'model': model, ...})" + ) + # broadcast the path from rank 0 to ensure all the states are loaded from a common path + path = Path(self.broadcast(path)) + + if isinstance(state, Module): + from lightning_fabric.strategies.model_parallel import _load_raw_module_state_from_path + + _load_raw_module_state_from_path(path, module=state, world_size=self.world_size, strict=strict) + return {} + + if isinstance(state, Optimizer): + raise NotImplementedError( + "Loading a single optimizer object from a checkpoint is not supported yet with the FSDP strategy." + ) + + from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + + modules = {key: module for key, module in state.items() if _has_fsdp_modules(module)} + if len(modules) == 0: + raise ValueError( + "Could not find a FSDP model in the provided checkpoint state. Please provide the model as" + " part of the state like so: `load_checkpoint(..., state={'model': model, ...})`. Make sure" + " you set up the model (and optimizers if any) through the strategy before loading the checkpoint." + ) + optimizers = {key: optim for key, optim in state.items() if isinstance(optim, Optimizer)} + if len(modules) > 1: + raise ValueError( + "Found multiple FSDP models in the given state. Loading checkpoints with FSDP is" + " currently limited to a single model per checkpoint. To load multiple models, call the" + " load method for each model separately with a different path." + ) + module_key, module = list(modules.items())[0] + + if _is_sharded_checkpoint(path): + state_dict_ctx = _get_sharded_state_dict_context(module) + + with state_dict_ctx: + module_state = {module_key: module.state_dict()} + _distributed_checkpoint_load(module_state, path) + module.load_state_dict(module_state[module_key], strict=strict) + + if optimizers: + from torch.distributed.checkpoint import FileSystemReader + + # TODO: replace with newer APIs + # https://github.com/pytorch/pytorch/issues/119800#issuecomment-1942156271 + reader = FileSystemReader(path=path) + # the optimizer states must be loaded separately + for optim_key, optim in optimizers.items(): + optim_state = load_sharded_optimizer_state_dict( + model_state_dict=module_state[module_key], + optimizer_key=optim_key, + storage_reader=reader, + ) + flattened_osd = FSDP.optim_state_dict_to_load( + optim_state_dict=optim_state[optim_key], + model=module, + optim=optim, + ) + optim.load_state_dict(flattened_osd) + + # Load metadata (anything not a module or optimizer) + metadata = torch.load(path / _METADATA_FILENAME, weights_only=weights_only) + requested_metadata_keys = state.keys() - modules.keys() - optimizers.keys() + _validate_keys_for_strict_loading(requested_metadata_keys, metadata.keys(), strict=strict) + for key in requested_metadata_keys: + if key not in metadata: + continue + state[key] = metadata.pop(key) + + # return the remaining metadata that wasn't requested as part of `state` + return metadata + + if _is_full_checkpoint(path): + checkpoint = _lazy_load(path) + + from lightning_fabric.strategies.model_parallel import ( + _load_raw_module_state, + _rekey_optimizer_state_if_needed, + ) + + _load_raw_module_state(checkpoint.pop(module_key), module=module, world_size=self.world_size, strict=strict) + + if isinstance(state, Module): + return {} + + # Materialize lazy tensors if there are any left in the checkpoint + # The `torch.Optimizer.load_state_dict` method can't load lazy tensors because of deepcopy pickle issues + checkpoint = _materialize_tensors(checkpoint) + + # Load optimizer states + for optim_key, optim in optimizers.items(): + # rank0_only should be false because we need to load the optimizer state on all ranks + with _get_full_state_dict_context(module, world_size=self.world_size, rank0_only=False): + temp_state_dict = _rekey_optimizer_state_if_needed(checkpoint.pop(optim_key), module) + optim_state_dict = FSDP.optim_state_dict_to_load( + optim_state_dict=temp_state_dict, + model=module, + optim=optim, + ) + optim.load_state_dict(optim_state_dict) + + requested_metadata_keys = state.keys() - modules.keys() - optimizers.keys() + _validate_keys_for_strict_loading(requested_metadata_keys, checkpoint.keys(), strict=strict) + + # Load metadata (anything not a module or optimizer) + _move_state_into(source=checkpoint, destination=state, keys=requested_metadata_keys) + + # return the remaining metadata that wasn't requested as part of `state` + return checkpoint + + raise ValueError( + f"The path {str(path)!r} does not point to a valid checkpoint. Make sure the path points to either a" + " directory with FSDP checkpoint shards, or a single file with a full checkpoint." + ) + + @classmethod + @override + def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: + if not torch.distributed.is_available(): + return + + strategy_registry.register( + "fsdp", + cls, + description="Fully Sharded Data Parallel (FSDP) training", + ) + strategy_registry.register( + "fsdp_cpu_offload", + cls, + description="Fully Sharded Data Parallel (FSDP) training with Full Sharding and CPU Offloading", + cpu_offload=True, + ) + + def _setup_distributed(self) -> None: + reset_seed() + self._set_world_ranks() + self._process_group_backend = self._get_process_group_backend() + assert self.cluster_environment is not None + kwargs: dict[str, Any] = {"timeout": self._timeout} + if _TORCH_GREATER_EQUAL_2_3: + kwargs["device_id"] = self.root_device if self.root_device.type != "cpu" else None + _init_dist_connection(self.cluster_environment, self._process_group_backend, **kwargs) + + def _get_process_group_backend(self) -> str: + return self._process_group_backend or _get_default_process_group_backend_for_device(self.root_device) + + def _set_world_ranks(self) -> None: + if self.cluster_environment is not None: + self.cluster_environment.set_global_rank(self.node_rank * self.num_processes + self.local_rank) + self.cluster_environment.set_world_size(self.num_nodes * self.num_processes) + # `LightningEnvironment.set_global_rank` will do this too, but we cannot rely on that implementation detail + # additionally, for some implementations, the setter is a no-op, so it's safer to access the getter + rank_zero_only.rank = utils_rank_zero_only.rank = self.global_rank + + +def _activation_checkpointing_kwargs( + activation_checkpointing: Optional[Union[type[Module], list[type[Module]]]], + activation_checkpointing_policy: Optional["_POLICY"], +) -> dict: + if activation_checkpointing is None and activation_checkpointing_policy is None: + return {} + if activation_checkpointing is not None and activation_checkpointing_policy is not None: + raise ValueError( + "You cannot set both `activation_checkpointing` and `activation_checkpointing_policy`. Use the latter." + ) + if activation_checkpointing is not None: + if isinstance(activation_checkpointing, list): + classes = tuple(activation_checkpointing) + else: + classes = (activation_checkpointing,) + rank_zero_deprecation( + f"`FSDPStrategy(activation_checkpointing={activation_checkpointing})` is deprecated, use " + f"`FSDPStrategy(activation_checkpointing_policy={set(classes)})` instead." + ) + return {"check_fn": lambda submodule: isinstance(submodule, classes)} + if isinstance(activation_checkpointing_policy, set): + return _auto_wrap_policy_kwargs(activation_checkpointing_policy, {}) + return {"auto_wrap_policy": activation_checkpointing_policy} + + +def _auto_wrap_policy_kwargs(policy: Optional["_POLICY"], kwargs: dict) -> dict: + if policy is None: + return kwargs + if isinstance(policy, set): + from torch.distributed.fsdp.wrap import ModuleWrapPolicy + + policy = ModuleWrapPolicy(policy) + + kwargs["auto_wrap_policy"] = policy + return kwargs + + +def _setup_activation_checkpointing(module: Module, activation_checkpointing_kwargs: dict) -> None: + if not activation_checkpointing_kwargs: + return + + from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointWrapper + + if any(isinstance(mod, CheckpointWrapper) for mod in module.modules()): + rank_zero_warn( + "FSDP checkpointing is configured, but the model already contains checkpointed layers." + " Checkpointing will be ignored." + ) + return + + from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + apply_activation_checkpointing, + checkpoint_wrapper, + ) + + if not _TORCH_GREATER_EQUAL_2_2: + checkpoint_wrapper = partial(checkpoint_wrapper, checkpoint_impl=CheckpointImpl.NO_REENTRANT) + apply_activation_checkpointing(module, checkpoint_wrapper_fn=checkpoint_wrapper, **activation_checkpointing_kwargs) + + +class _FSDPBackwardSyncControl(_BackwardSyncControl): + @override + def no_backward_sync(self, module: Module, enabled: bool) -> AbstractContextManager: + """Blocks gradient synchronization inside the :class:`~torch.distributed.fsdp.FullyShardedDataParallel` + wrapper.""" + if not enabled: + return nullcontext() + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel + + if not isinstance(module, FullyShardedDataParallel): + # the root must be wrapped + raise TypeError( + "Blocking backward sync is only possible if the module passed to" + f" `{type(self).__name__}.no_backward_sync` is wrapped in `FullyShardedDataParallel`." + f" Got: {module.__class__.__name__}." + ) + return module.no_sync() + + +def _init_cpu_offload(cpu_offload: Optional[Union[bool, "CPUOffload"]]) -> "CPUOffload": + from torch.distributed.fsdp import CPUOffload + + return cpu_offload if isinstance(cpu_offload, CPUOffload) else CPUOffload(offload_params=bool(cpu_offload)) + + +def _init_sharding_strategy(sharding_strategy: "_SHARDING_STRATEGY", kwargs: dict) -> "ShardingStrategy": + from torch.distributed.fsdp import ShardingStrategy + + if kwargs.get("process_group") is not None and kwargs.get("device_mesh") is not None: + raise ValueError( + "The arguments `FSDPStrategy(process_group=..., device_mesh=...)` are mutually exclusive." + "Pass only one of them." + ) + + strategy = ShardingStrategy[sharding_strategy.upper()] if isinstance(sharding_strategy, str) else sharding_strategy + if ( + "HYBRID" in strategy.name + and kwargs.get("auto_wrap_policy") is None + and kwargs.get("process_group") is None + and kwargs.get("device_mesh") is None + ): + raise RuntimeError( + "The hybrid sharding strategy requires you to pass at least one of the parameters: `auto_wrap_policy`," + " `process_group` tuple, or `device_mesh`." + ) + return strategy + + +def _optimizer_has_flat_params(optimizer: Optimizer) -> bool: + return any( + getattr(param, "_fsdp_flattened", False) for group in optimizer.param_groups for param in group["params"] + ) + + +def _get_sharded_state_dict_context(module: Module) -> Generator[None, None, None]: + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp.api import ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictType + + state_dict_config = ShardedStateDictConfig(offload_to_cpu=True) + optim_state_dict_config = ShardedOptimStateDictConfig(offload_to_cpu=True) + state_dict_type_context = FSDP.state_dict_type( + module=module, + state_dict_type=StateDictType.SHARDED_STATE_DICT, + state_dict_config=state_dict_config, + optim_state_dict_config=optim_state_dict_config, + ) + return state_dict_type_context # type: ignore[return-value] + + +def _get_full_state_dict_context( + module: Module, world_size: int, rank0_only: bool = True +) -> Generator[None, None, None]: + from torch.distributed.fsdp import FullStateDictConfig, StateDictType + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp.api import FullOptimStateDictConfig + + state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=rank0_only) + optim_state_dict_config = FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=rank0_only) + state_dict_type_context = FSDP.state_dict_type( + module=module, + state_dict_type=StateDictType.FULL_STATE_DICT, + state_dict_config=state_dict_config, + optim_state_dict_config=optim_state_dict_config, + ) + + return state_dict_type_context # type: ignore[return-value] + + +def _is_sharded_checkpoint(path: Path) -> bool: + """A heuristic check to determine whether the path points to a directory with checkpoint shards.""" + return path.is_dir() and (path / _METADATA_FILENAME).is_file() + + +def _is_full_checkpoint(path: Path) -> bool: + return path.is_file() + + +def _has_fsdp_modules(module: object) -> TypeGuard[Module]: + from torch.distributed.fsdp import FullyShardedDataParallel + + return isinstance(module, Module) and any(isinstance(m, FullyShardedDataParallel) for m in module.modules()) + + +def _move_torchmetrics_to_device(module: torch.nn.Module, device: torch.device) -> None: + # FSDP doesn't move modules without parameters (e.g. Metrics) to the device + # https://github.com/pytorch/pytorch/issues/113113 + if not RequirementCache("torchmetrics"): + return + + from torchmetrics import Metric + + for metric in (m for m in module.modules() if isinstance(m, Metric)): + metric.to(device) # `.to()` is in-place + + +def _distributed_checkpoint_save(converted_state: dict[str, Any], path: Path) -> None: + if _TORCH_GREATER_EQUAL_2_3: + from torch.distributed.checkpoint import save + + # let torch automatically infer the writer to use. This might also support fsspec paths in the future + # https://github.com/pytorch/pytorch/issues/118036 + save(converted_state, checkpoint_id=path) + else: # deprecated + from torch.distributed.checkpoint import FileSystemWriter + + if _TORCH_GREATER_EQUAL_2_2: + from torch.distributed.checkpoint import save + else: + from torch.distributed.checkpoint import save_state_dict as save + # FSDP's FileSystemWriter streams the tensors to disk to minimize memory peaks + writer = FileSystemWriter(path=path, single_file_per_rank=True) + save(converted_state, writer) + + +def _distributed_checkpoint_load(module_state: dict[str, Any], path: Path) -> None: + if _TORCH_GREATER_EQUAL_2_3: + from torch.distributed.checkpoint import load + + # let torch automatically infer the reader to use. This might also support fsspec paths in the future + # https://github.com/pytorch/pytorch/issues/118036 + load(module_state, checkpoint_id=path) + else: # deprecated + from torch.distributed.checkpoint import FileSystemReader + + if _TORCH_GREATER_EQUAL_2_2: + from torch.distributed.checkpoint import load + else: + from torch.distributed.checkpoint import load_state_dict as load + reader = FileSystemReader(path=path) + load(module_state, reader) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a198a35d95849f6f7176957ead6cdfc23559b9 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__init__.py @@ -0,0 +1,22 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from lightning_fabric.strategies.launchers.multiprocessing import _MultiProcessingLauncher +from lightning_fabric.strategies.launchers.subprocess_script import _SubprocessScriptLauncher +from lightning_fabric.strategies.launchers.xla import _XLALauncher + +__all__ = [ + "_MultiProcessingLauncher", + "_SubprocessScriptLauncher", + "_XLALauncher", +] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e42b717c61391ee525c2fb0e17f8921e61a0221c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/launcher.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/launcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9a474fe20c0b97e0c6f95a6b09c66805a14ff45 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/launcher.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/multiprocessing.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/multiprocessing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b7c57fc302800f1aa02d44d4b1cc48df8b1f682 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/multiprocessing.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/subprocess_script.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/subprocess_script.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bf90e89ed87a5dc9396a983b50e23406fab1a88 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/subprocess_script.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/xla.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/xla.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05e2873d36bdd7e4ec725ddeb6a9def0cbca00c5 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/__pycache__/xla.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/launcher.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..a8d668d1658a8b635cc0fcf1ccd0273ba7b320c1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/launcher.py @@ -0,0 +1,36 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from abc import ABC, abstractmethod +from typing import Any, Callable + + +class _Launcher(ABC): + r"""Abstract base class for all Launchers. + + Launchers are responsible for the creation and instrumentation of new processes so that the + :class:`~lightning_fabric.strategies.strategy.Strategy` can set up communication between all them. + + Subclass this class and override any of the relevant methods to provide a custom implementation depending on + cluster environment, hardware, strategy, etc. + + """ + + @property + @abstractmethod + def is_interactive_compatible(self) -> bool: + """Returns whether this launcher can work in interactive environments such as Jupyter notebooks.""" + + @abstractmethod + def launch(self, function: Callable, *args: Any, **kwargs: Any) -> Any: + """Launches the processes.""" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/multiprocessing.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/multiprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..c75ae23731e079f42d688f7c4ded1da32b0a5534 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/multiprocessing.py @@ -0,0 +1,261 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import itertools +import os +from dataclasses import dataclass +from multiprocessing.queues import SimpleQueue +from textwrap import dedent +from typing import TYPE_CHECKING, Any, Callable, Literal, Optional + +import torch +import torch.backends.cudnn +import torch.multiprocessing as mp +from lightning_utilities import apply_to_collection +from torch.nn import Module +from typing_extensions import override + +from lightning_fabric.accelerators.cpu import CPUAccelerator +from lightning_fabric.strategies.launchers.launcher import _Launcher +from lightning_fabric.utilities.apply_func import move_data_to_device +from lightning_fabric.utilities.distributed import _set_num_threads_if_needed +from lightning_fabric.utilities.imports import _IS_INTERACTIVE +from lightning_fabric.utilities.seed import _collect_rng_states, _set_rng_states + +if TYPE_CHECKING: + from lightning_fabric.strategies import ParallelStrategy + + +class _MultiProcessingLauncher(_Launcher): + r"""Launches processes that run a given function in parallel, and joins them all at the end. + + The main process in which this launcher is invoked creates N so-called worker processes (using + :func:`torch.multiprocessing.start_processes`) that run the given function. + Worker processes have a rank that ranges from 0 to N - 1. + + Note: + - This launcher requires all objects to be pickleable. + - It is important that the entry point to the program/script is guarded by ``if __name__ == "__main__"``. + - With start method 'fork' the user must ensure that no CUDA context gets created in the main process before + the launcher is invoked. E.g., one should avoid creating cuda tensors or calling ``torch.cuda.*`` functions + before calling ``Trainer.fit``. + + Args: + strategy: A reference to the strategy that is used together with this launcher. + start_method: The method how to start the processes. + - 'spawn': The default start method. Requires all objects to be pickleable. + - 'fork': Preferable for IPython/Jupyter environments where 'spawn' is not available. Not available on + the Windows platform for example. + - 'forkserver': Alternative implementation to 'fork'. + + """ + + def __init__( + self, + strategy: "ParallelStrategy", + start_method: Literal["spawn", "fork", "forkserver"] = "spawn", + ) -> None: + self._strategy = strategy + self._start_method = start_method + if start_method not in mp.get_all_start_methods(): + raise ValueError( + f"The start method '{self._start_method}' is not available on this platform. Available methods are:" + f" {', '.join(mp.get_all_start_methods())}" + ) + + @property + @override + def is_interactive_compatible(self) -> bool: + # The start method 'spawn' is not supported in interactive environments + # The start method 'fork' is the only one supported in Jupyter environments, with constraints around CUDA + # initialization. For more context, see https://github.com/Lightning-AI/pytorch-lightning/issues/7550 + return self._start_method == "fork" + + @override + def launch(self, function: Callable, *args: Any, **kwargs: Any) -> Any: + """Launches processes that run the given function in parallel. + + The function is allowed to have a return value. However, when all processes join, only the return value + of worker process 0 gets returned from this `launch` method in the main process. + + Arguments: + function: The entry point for all launched processes. + *args: Optional positional arguments to be passed to the given function. + **kwargs: Optional keyword arguments to be passed to the given function. + + """ + if self._start_method in ("fork", "forkserver"): + _check_bad_cuda_fork() + if self._start_method == "spawn": + _check_missing_main_guard() + + # The default cluster environment in Lightning chooses a random free port number + # This needs to be done in the main process here before starting processes to ensure each rank will connect + # through the same port + assert self._strategy.cluster_environment is not None + os.environ["MASTER_PORT"] = str(self._strategy.cluster_environment.main_port) + + context = mp.get_context(self._start_method) + return_queue = context.SimpleQueue() + + if self._start_method == "spawn": + global_states = _GlobalStateSnapshot.capture() + process_args = [function, args, kwargs, return_queue, global_states] + else: + process_args = [function, args, kwargs, return_queue] + + mp.start_processes( + self._wrapping_function, + args=process_args, + nprocs=self._strategy.num_processes, + start_method=self._start_method, + ) + return return_queue.get() + + def _wrapping_function( + self, + process_idx: int, + function: Callable, + args: Any, + kwargs: Any, + return_queue: SimpleQueue, + global_states: Optional["_GlobalStateSnapshot"] = None, + ) -> None: + if global_states: + global_states.restore() + if self._start_method == "spawn" and isinstance(self._strategy.accelerator, CPUAccelerator): + args, kwargs = _disable_module_memory_sharing((args, kwargs)) + + _set_num_threads_if_needed(num_processes=self._strategy.num_processes) + + os.environ["LOCAL_RANK"] = str(process_idx) + results = function(*args, **kwargs) + + if process_idx == 0: + return_queue.put(move_data_to_device(results, "cpu")) + + +@dataclass +class _GlobalStateSnapshot: + """Captures a hand-selected set of (global) variables in modules and provides a way to restore them. + + It facilitates and encapsulates the transfer of globals like PyTorch's deterministic flags or random generator state + across process boundaries when launching processes with :func:`torch.multiprocessing.spawn`. + + Example: + + .. code-block:: python + + # in main process + snapshot = _GlobalStateSnapshot.capture() + + # in worker process + snapshot.restore() + + """ + + use_deterministic_algorithms: bool + use_deterministic_algorithms_warn_only: bool + cudnn_benchmark: bool + rng_states: dict[str, Any] + + @classmethod + def capture(cls) -> "_GlobalStateSnapshot": + """Capture a few global states from torch, numpy, etc., that we want to restore in a spawned worker process.""" + return cls( + use_deterministic_algorithms=torch.are_deterministic_algorithms_enabled(), + use_deterministic_algorithms_warn_only=torch.is_deterministic_algorithms_warn_only_enabled(), + cudnn_benchmark=torch.backends.cudnn.benchmark, + rng_states=_collect_rng_states(), + ) + + def restore(self) -> None: + """Restores all globals to the values captured in the :meth:`capture` method.""" + torch.use_deterministic_algorithms( + self.use_deterministic_algorithms, warn_only=self.use_deterministic_algorithms_warn_only + ) + torch.backends.cudnn.benchmark = self.cudnn_benchmark + _set_rng_states(self.rng_states) + + +def _check_bad_cuda_fork() -> None: + """Checks whether it is safe to fork and initialize CUDA in the new processes, and raises an exception if not. + + The error message replaces PyTorch's 'Cannot re-initialize CUDA in forked subprocess' with helpful advice for + Lightning users. + + """ + # Use PyTorch's internal check for bad fork state, which is more accurate than just checking if CUDA + # is initialized. This allows passive CUDA initialization (e.g., from library imports or device queries) + # while still catching actual problematic cases where CUDA context was created before forking. + _is_in_bad_fork = getattr(torch.cuda, "_is_in_bad_fork", None) + if _is_in_bad_fork is not None and callable(_is_in_bad_fork) and _is_in_bad_fork(): + message = ( + "Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, " + "you must use the 'spawn' start method or avoid CUDA initialization in the main process." + ) + if _IS_INTERACTIVE: + message += " You will have to restart the Python kernel." + raise RuntimeError(message) + + # Fallback to the old check if _is_in_bad_fork is not available (older PyTorch versions) + if _is_in_bad_fork is None and torch.cuda.is_initialized(): + message = ( + "Lightning can't create new processes if CUDA is already initialized. Did you manually call" + " `torch.cuda.*` functions, have moved the model to the device, or allocated memory on the GPU any" + " other way? Please remove any such calls, or change the selected strategy." + ) + if _IS_INTERACTIVE: + message += " You will have to restart the Python kernel." + raise RuntimeError(message) + + +def _disable_module_memory_sharing(data: Any) -> Any: + """Disables memory sharing on parameters and buffers of `nn.Module`s contained in the given collection. + + Note: This is only required when running on CPU. + + """ + # PyTorch enables memory sharing automatically on all tensors that are passed through `mp.spawn`. + # For model weights and buffers, this is undesired and can lead to race conditions between processes. + # Hence, we copy the tensors in the entire module to ensure it doesn't share memory with other processes. + + @torch.no_grad() + def unshare(module: Module) -> Module: + for tensor in itertools.chain(module.parameters(), module.buffers()): + tensor.data = tensor.data.clone() + return module + + return apply_to_collection(data, function=unshare, dtype=Module) + + +def _check_missing_main_guard() -> None: + """Raises an exception if the ``__name__ == "__main__"`` guard is missing.""" + if not getattr(mp.current_process(), "_inheriting", False): + return + message = dedent( + """ + Launching multiple processes with the 'spawn' start method requires that your script guards the main + function with an `if __name__ == \"__main__\"` clause. For example: + + def main(): + # Put your code here + ... + + if __name__ == "__main__": + main() + + Alternatively, you can run with `strategy="ddp"` to avoid this error. + """ + ) + raise RuntimeError(message) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/subprocess_script.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/subprocess_script.py new file mode 100644 index 0000000000000000000000000000000000000000..029c640865a6172df21a831f23ced89eeb9dfc97 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/subprocess_script.py @@ -0,0 +1,234 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import logging +import os +import signal +import subprocess +import sys +import threading +import time +from collections.abc import Sequence +from typing import Any, Callable, Optional + +from lightning_utilities.core.imports import RequirementCache +from typing_extensions import override + +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment +from lightning_fabric.strategies.launchers.launcher import _Launcher +from lightning_fabric.utilities.distributed import _set_num_threads_if_needed +from lightning_fabric.utilities.rank_zero import rank_prefixed_message + +_logger = logging.getLogger(__name__) +_HYDRA_AVAILABLE = RequirementCache("hydra-core") + + +class _SubprocessScriptLauncher(_Launcher): + r"""A process launcher that invokes the current script as many times as desired in a single node. + + This launcher needs to be invoked on each node. + In its default behavior, the main process in each node then spawns N-1 child processes via :func:`subprocess.Popen`, + where N is the number of devices (e.g. GPU) per node. It is very similar to how :mod:`torch.distributed.run` + launches processes. + + For example, if the script gets invoked with the command + + .. code-block:: bash + + python train.py --devices 4 + + The launcher will create three additional subprocesses that get called like so: + + .. code-block:: bash + + LOCAL_RANK=1 python train.py --devices 4 + LOCAL_RANK=2 python train.py --devices 4 + LOCAL_RANK=3 python train.py --devices 4 + + It is implied that the main process which launched the others has ``LOCAL_RANK=0``. + Beside the local rank, the following other environment variables also get set, but unlike the local rank, these + get determined by the cluster environment: + + 1. `MASTER_ADDR`: The IP address of the main node. + 2. `MASTER_PORT`: The port number of the main node through which all processes communicate. + 3. `NODE_RANK`: The index of the node the current process is running on. Ranges from 0 to ``num_nodes - 1``. + 4. `WORLD_SIZE`: The total number of processes across all nodes, i.e., ``num_processes * num_nodes``. + + Arguments: + cluster_environment: A cluster environment that provides access to world size, node rank, etc. + num_processes: The number of processes to launch in the current node. + num_nodes: The total number of nodes that participate in this process group. + + """ + + def __init__( + self, + cluster_environment: "ClusterEnvironment", + num_processes: int, + num_nodes: int, + ) -> None: + super().__init__() + self.cluster_environment = cluster_environment + self.num_processes = num_processes + self.num_nodes = num_nodes + self.procs: list[subprocess.Popen] = [] # launched child subprocesses, does not include the launcher + + @property + @override + def is_interactive_compatible(self) -> bool: + return False + + @override + def launch(self, function: Callable, *args: Any, **kwargs: Any) -> Any: + """Creates new processes, then calls the given function. + + Arguments: + function: A callback function to execute after all processes have been created. + It is up to the implementation of this function to synchronize the processes, e.g., with barriers. + *args: Optional positional arguments to be passed to the given function. + **kwargs: Optional keyword arguments to be passed to the given function. + + """ + self.cluster_environment.validate_settings(num_devices=self.num_processes, num_nodes=self.num_nodes) + if not self.cluster_environment.creates_processes_externally: + self._call_children_scripts() + _launch_process_observer(self.procs) + + _set_num_threads_if_needed(num_processes=self.num_processes) + return function(*args, **kwargs) + + def _call_children_scripts(self) -> None: + # bookkeeping of spawned processes + self._check_can_spawn_children() + + # DDP Environment variables + os.environ["MASTER_ADDR"] = self.cluster_environment.main_address + os.environ["MASTER_PORT"] = str(self.cluster_environment.main_port) + + # allow the user to pass the node rank + os.environ["NODE_RANK"] = str(self.cluster_environment.node_rank()) + os.environ["LOCAL_RANK"] = str(self.cluster_environment.local_rank()) + os.environ["WORLD_SIZE"] = f"{self.num_processes * self.num_nodes}" + + for local_rank in range(1, self.num_processes): + env_copy = os.environ.copy() + env_copy["LOCAL_RANK"] = f"{local_rank}" + + # remove env var if global seed not set + if os.environ.get("PL_GLOBAL_SEED") is None and "PL_GLOBAL_SEED" in env_copy: + del env_copy["PL_GLOBAL_SEED"] + + # start process + # if hydra is available and initialized, make sure to set the cwd correctly + hydra_in_use = False + cwd: Optional[str] = None + if _HYDRA_AVAILABLE: + from hydra.core.hydra_config import HydraConfig + + hydra_in_use = HydraConfig.initialized() + if hydra_in_use: + command, cwd = _hydra_subprocess_cmd(local_rank=local_rank) + else: + command = _basic_subprocess_cmd() + + proc = subprocess.Popen(command, env=env_copy, cwd=cwd) + self.procs.append(proc) + + def _check_can_spawn_children(self) -> None: + if len(self.procs) > 0: + raise RuntimeError("The launcher can only create subprocesses once.") + if self.cluster_environment.local_rank() != 0: + raise RuntimeError( + "Lightning attempted to launch new distributed processes with `local_rank > 0`. This should not happen." + " Possible reasons: 1) LOCAL_RANK environment variable was incorrectly modified by the user," + " 2) `ClusterEnvironment.creates_processes_externally` incorrectly implemented." + ) + + +def _basic_subprocess_cmd() -> Sequence[str]: + import __main__ # local import to avoid https://github.com/Lightning-AI/pytorch-lightning/issues/15218 + + if __main__.__spec__ is None: # pragma: no-cover + return [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:] + return [sys.executable, "-m", __main__.__spec__.name] + sys.argv[1:] + + +def _hydra_subprocess_cmd(local_rank: int) -> tuple[Sequence[str], str]: + from hydra.core.hydra_config import HydraConfig + from hydra.utils import get_original_cwd, to_absolute_path + + import __main__ # local import to avoid https://github.com/Lightning-AI/pytorch-lightning/issues/15218 + + # when user is using hydra find the absolute path + if __main__.__spec__ is None: # pragma: no-cover + command = [sys.executable, to_absolute_path(sys.argv[0])] + else: + command = [sys.executable, "-m", __main__.__spec__.name] + + command += sys.argv[1:] + + cwd = get_original_cwd() + rundir = f'"{HydraConfig.get().run.dir}"' + # Set output_subdir null since we don't want different subprocesses trying to write to config.yaml + command += [f"hydra.run.dir={rundir}", f"hydra.job.name=train_ddp_process_{local_rank}", "hydra.output_subdir=null"] + return command, cwd + + +def _launch_process_observer(child_processes: list[subprocess.Popen]) -> None: + """Launches a thread that runs along the main process and monitors the health of all processes.""" + _ChildProcessObserver(child_processes=child_processes, main_pid=os.getpid()).start() + + +class _ChildProcessObserver(threading.Thread): + def __init__(self, main_pid: int, child_processes: list[subprocess.Popen], sleep_period: int = 5) -> None: + super().__init__(daemon=True, name="child-process-observer") # thread stops if the main process exits + self._main_pid = main_pid + self._child_processes = child_processes + self._sleep_period = sleep_period + # Note: SIGTERM is not aggressive enough to terminate processes hanging in collectives + self._termination_signal = signal.SIGTERM if sys.platform == "win32" else signal.SIGKILL + self._finished = False + + @override + def run(self) -> None: + while not self._finished: + time.sleep(self._sleep_period) + self._finished = self._run() + + def _run(self) -> bool: + """Runs once over all child processes to check whether they are still running.""" + for proc in self._child_processes: + proc.poll() + + return_codes = [proc.returncode for proc in self._child_processes] + if all(return_code == 0 for return_code in return_codes): + return True + + for i, proc in enumerate(self._child_processes): + if proc.returncode: + message = rank_prefixed_message( + f"Child process with PID {proc.pid} terminated with code {proc.returncode}." + f" Forcefully terminating all other processes to avoid zombies 🧟", + rank=(i + 1), + ) + _logger.info(message) + self._terminate_all() + return True + + return False + + def _terminate_all(self) -> None: + """Terminates the main process and all its children.""" + for p in self._child_processes: + p.send_signal(self._termination_signal) + os.kill(self._main_pid, self._termination_signal) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/xla.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/xla.py new file mode 100644 index 0000000000000000000000000000000000000000..091222dcb22476296c8e6434c0f29891bbd6d153 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/launchers/xla.py @@ -0,0 +1,128 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import queue +import time +from typing import TYPE_CHECKING, Any, Callable, Optional, Union + +import torch.multiprocessing as mp +from typing_extensions import override + +from lightning_fabric.accelerators.xla import _XLA_AVAILABLE +from lightning_fabric.strategies.launchers.launcher import _Launcher +from lightning_fabric.strategies.launchers.multiprocessing import _GlobalStateSnapshot +from lightning_fabric.utilities.apply_func import move_data_to_device + +if TYPE_CHECKING: + from lightning_fabric.strategies import XLAFSDPStrategy, XLAStrategy + + +class _XLALauncher(_Launcher): + r"""Launches processes that run a given function in parallel on XLA supported hardware, and joins them all at the + end. + + The main process in which this launcher is invoked creates N so-called worker processes (using the + `torch_xla` :func:`xmp.spawn`) that run the given function. + Worker processes have a rank that ranges from 0 to N - 1. + + Note: + - This launcher requires all objects to be pickleable. + - It is important that the entry point to the program/script is guarded by ``if __name__ == "__main__"``. + + Args: + strategy: A reference to the strategy that is used together with this launcher + + """ + + def __init__(self, strategy: Union["XLAStrategy", "XLAFSDPStrategy"]) -> None: + if not _XLA_AVAILABLE: + raise ModuleNotFoundError(str(_XLA_AVAILABLE)) + self._strategy = strategy + self._start_method = "fork" + + @property + @override + def is_interactive_compatible(self) -> bool: + return True + + @override + def launch(self, function: Callable, *args: Any, **kwargs: Any) -> Any: + """Launches processes that run the given function in parallel. + + The function is allowed to have a return value. However, when all processes join, only the return value + of worker process 0 gets returned from this `launch` method in the main process. + + Arguments: + function: The entry point for all launched processes. + *args: Optional positional arguments to be passed to the given function. + **kwargs: Optional keyword arguments to be passed to the given function. + + """ + return_queue: Union[queue.Queue, mp.SimpleQueue] + return_queue = mp.Manager().Queue() + + import torch_xla.distributed.xla_multiprocessing as xmp + + spawn_kwargs = {} + nprocs = self._strategy.num_processes + if nprocs == 1: + # avoid warning: "Unsupported nprocs". If it's 1, it will call the launched function directly. + # otherwise it will use all devices + spawn_kwargs["nprocs"] = nprocs + + xmp.spawn( + self._wrapping_function, + args=(function, args, kwargs, return_queue), + start_method=self._start_method, + **spawn_kwargs, + ) + return return_queue.get() + + def _wrapping_function( + self, + # XLA's multiprocessing returns the global index, not the local index as torch's multiprocessing + # https://github.com/pytorch/xla/blob/v1.13.0/torch_xla/distributed/xla_multiprocessing.py#L321 + process_idx: int, + function: Callable, + args: Any, + kwargs: Any, + return_queue: Union[mp.SimpleQueue, queue.Queue], + global_states: Optional[_GlobalStateSnapshot] = None, + ) -> None: + import torch_xla.core.xla_model as xm + + if len(xm.get_xla_supported_devices()) > 1: + # `get_xla_supported_devices` in the spawned process returns the logical devices (2 for v2/v3 and 1 for v4) + # so when there's more than one (multithreading), objects need to be deep-copied + import copy + + function, args, kwargs = copy.deepcopy((function, args, kwargs)) + + results = function(*args, **kwargs) + + if self._strategy.local_rank == 0: + return_queue.put(move_data_to_device(results, "cpu")) + + _rank_teardown(self._strategy.local_rank) + + +def _rank_teardown(rank: int) -> None: + import torch_xla.core.xla_model as xm + + # Make all processes wait for each other before joining + # https://github.com/pytorch/xla/issues/1801#issuecomment-602799542 + xm.rendezvous("end-process") + # Ensure that the rank 0 process is the one exiting last + # https://github.com/pytorch/xla/issues/2190#issuecomment-641665358 + if rank == 0: + time.sleep(1) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/model_parallel.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/model_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..dcfa48e3ee823682c704c11faa727dedd9f17682 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/model_parallel.py @@ -0,0 +1,599 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import itertools +import shutil +from collections.abc import Generator +from contextlib import AbstractContextManager, ExitStack +from datetime import timedelta +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, TypeVar, Union + +import torch +from lightning_utilities.core.rank_zero import rank_zero_only as utils_rank_zero_only +from torch import Tensor +from torch.nn import Module +from torch.optim import Optimizer +from typing_extensions import TypeGuard, override + +from lightning_fabric.plugins import CheckpointIO +from lightning_fabric.plugins.collectives.torch_collective import default_pg_timeout +from lightning_fabric.strategies.fsdp import ( + _distributed_checkpoint_load, + _distributed_checkpoint_save, + _get_full_state_dict_context, + _is_full_checkpoint, + _is_sharded_checkpoint, +) +from lightning_fabric.strategies.launchers.subprocess_script import _SubprocessScriptLauncher +from lightning_fabric.strategies.parallel import ParallelStrategy +from lightning_fabric.strategies.strategy import ( + TBroadcast, + _apply_filter, + _BackwardSyncControl, + _validate_keys_for_strict_loading, +) +from lightning_fabric.utilities.distributed import ( + ReduceOp, + _distributed_is_initialized, + _get_default_process_group_backend_for_device, + _init_dist_connection, + _sync_ddp_if_available, +) +from lightning_fabric.utilities.distributed import group as _group +from lightning_fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_3, _TORCH_GREATER_EQUAL_2_4 +from lightning_fabric.utilities.init import _materialize_distributed_module +from lightning_fabric.utilities.load import _METADATA_FILENAME, _lazy_load, _move_state_into +from lightning_fabric.utilities.rank_zero import rank_zero_only +from lightning_fabric.utilities.seed import reset_seed +from lightning_fabric.utilities.types import _PATH, _Stateful + +if TYPE_CHECKING: + from torch.distributed.device_mesh import DeviceMesh + +TModel = TypeVar("TModel", bound=Module) + + +class ModelParallelStrategy(ParallelStrategy): + """Enables user-defined parallelism applied to a model. + + .. warning:: This is an :ref:`experimental ` feature. + + Currently supports up to 2D parallelism. Specifically, it supports the combination of + Fully Sharded Data-Parallel 2 (FSDP2) with Tensor Parallelism (DTensor). These PyTorch APIs are currently still + experimental in PyTorch. Requires PyTorch 2.4 or newer. + + Arguments: + parallelize_fn: A function that applies parallelisms to a module. The strategy will provide the + model and device mesh as input. + data_parallel_size: The number of devices within a data-parallel group. Defaults to ``"auto"``, which + sets this size to the number of nodes in the cluster. + tensor_parallel_size: The number of devices within a tensor-parallel group. Defaults to ``"auto"``, which + sets this size to the number of GPUs in a single node. + save_distributed_checkpoint: If ``True``, each rank saves its shard of weights and optimizer states to a file. + The checkpoint is a folder with as many files as the world size. + If ``False``, the full weights and optimizer states get assembled on rank 0 and saved to a single file. + + """ + + def __init__( + self, + parallelize_fn: Callable[[TModel, "DeviceMesh"], TModel], + data_parallel_size: Union[Literal["auto"], int] = "auto", + tensor_parallel_size: Union[Literal["auto"], int] = "auto", + save_distributed_checkpoint: bool = True, + process_group_backend: Optional[str] = None, + timeout: Optional[timedelta] = default_pg_timeout, + ) -> None: + super().__init__() + if not _TORCH_GREATER_EQUAL_2_4: + raise ImportError(f"{type(self).__name__} requires PyTorch 2.4 or higher.") + self._parallelize_fn = parallelize_fn + self._data_parallel_size = data_parallel_size + self._tensor_parallel_size = tensor_parallel_size + self._num_nodes = 1 + self._save_distributed_checkpoint = save_distributed_checkpoint + self._process_group_backend: Optional[str] = process_group_backend + self._timeout: Optional[timedelta] = timeout + self._backward_sync_control = _ParallelBackwardSyncControl() + + self._device_mesh: Optional[DeviceMesh] = None + + @property + def device_mesh(self) -> "DeviceMesh": + if self._device_mesh is None: + raise RuntimeError("Accessing the device mesh before processes have initialized is not allowed.") + return self._device_mesh + + @property + @override + def checkpoint_io(self) -> CheckpointIO: + raise NotImplementedError(f"The `{type(self).__name__}` does not use the `CheckpointIO` plugin interface.") + + @checkpoint_io.setter + @override + def checkpoint_io(self, io: CheckpointIO) -> None: + raise NotImplementedError(f"The `{type(self).__name__}` does not support setting a `CheckpointIO` plugin.") + + @property + @override + def root_device(self) -> torch.device: + assert self.parallel_devices is not None + return self.parallel_devices[self.local_rank] + + @property + def num_nodes(self) -> int: + return self._num_nodes + + @num_nodes.setter + def num_nodes(self, num_nodes: int) -> None: + self._num_nodes = num_nodes + + @property + def num_processes(self) -> int: + return len(self.parallel_devices) if self.parallel_devices is not None else 0 + + @property + @override + def distributed_sampler_kwargs(self) -> dict[str, Any]: + assert self.device_mesh is not None + data_parallel_mesh = self.device_mesh["data_parallel"] + return {"num_replicas": data_parallel_mesh.size(), "rank": data_parallel_mesh.get_local_rank()} + + @property + def process_group_backend(self) -> Optional[str]: + return self._process_group_backend + + @override + def _configure_launcher(self) -> None: + assert self.cluster_environment is not None + if not self.cluster_environment.creates_processes_externally: + self._launcher = _SubprocessScriptLauncher(self.cluster_environment, self.num_processes, self.num_nodes) + + @override + def setup_environment(self) -> None: + super().setup_environment() + self._setup_distributed() + if self._data_parallel_size == "auto": + self._data_parallel_size = self.num_nodes + if self._tensor_parallel_size == "auto": + self._tensor_parallel_size = self.num_processes + self._device_mesh = _setup_device_mesh( + self._data_parallel_size, self._tensor_parallel_size, self.world_size, self.root_device + ) + + @override + def setup_module(self, module: Module) -> Module: + from torch.distributed.fsdp import FullyShardedDataParallel + + if any(isinstance(mod, FullyShardedDataParallel) for mod in module.modules()): + raise TypeError( + "Found modules that are wrapped with `torch.distributed.fsdp.FullyShardedDataParallel`." + f" The `{self.__class__.__name__}` only supports the new FSDP2 APIs in PyTorch >= 2.4." + ) + + module = self._parallelize_fn(module, self.device_mesh) # type: ignore[arg-type] + if not isinstance(module, Module): + raise TypeError( + f"The `parallelize_fn` must return a `nn.Module` instance, but got: {type(module).__name__}" + ) + _materialize_distributed_module(module, self.root_device) + return module + + @override + def module_to_device(self, module: Module) -> None: + pass + + @override + def module_init_context(self, empty_init: Optional[bool] = None) -> AbstractContextManager: + precision_init_ctx = self.precision.module_init_context() + stack = ExitStack() + if empty_init: + # Materializaton happens in `setup_module` + # TODO: Introduce `Fabric.materialize(module)` to give user control over materialization + stack.enter_context(torch.device("meta")) + stack.enter_context(precision_init_ctx) + return stack + + @override + def all_reduce( + self, tensor: Tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean" + ) -> Tensor: + if isinstance(tensor, Tensor): + return _sync_ddp_if_available(tensor, group, reduce_op=reduce_op) + return tensor + + @override + def barrier(self, *args: Any, **kwargs: Any) -> None: + if not _distributed_is_initialized(): + return + if torch.distributed.get_backend() == "nccl": + torch.distributed.barrier(device_ids=[self.root_device.index]) + else: + torch.distributed.barrier() + + @override + def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast: + if not _distributed_is_initialized(): + return obj + + obj = [obj] + torch.distributed.broadcast_object_list(obj, src, group=_group.WORLD) + return obj[0] + + @override + def save_checkpoint( + self, + path: _PATH, + state: dict[str, Union[Module, Optimizer, Any]], + storage_options: Optional[Any] = None, + filter: Optional[dict[str, Callable[[str, Any], bool]]] = None, + ) -> None: + """Save model, optimizer, and other state to a checkpoint on disk. + + If distributed checkpointing is enabled (default), the checkpoint gets saved as a directory containing one file + per process, with model- and optimizer shards stored per file. Additionally, it creates a metadata file + `meta.pt` with the rest of the user's state (only saved from rank 0). + If distributed checkpointing is disabled (``save_distributed_checkpoint=False``), the checkpoint will be + written to a single file containing the weights, optimizer state and other metadata. + + """ + if storage_options is not None: + raise TypeError( + f"`{type(self).__name__}.save_checkpoint(..., storage_options=...)` is not supported because" + f" `{type(self).__name__}` does not use the `CheckpointIO`." + ) + if filter is not None and self._save_distributed_checkpoint: + # https://github.com/pytorch/pytorch/issues/105379 + raise NotImplementedError( + f"{type(self).__name__} doesn't support loading distributed filtered checkpoints," + " so saving them is disabled." + ) + # broadcast the path from rank 0 to ensure all the states are saved in a common path + path = Path(self.broadcast(path)) + _save_checkpoint( + path=path, + state=state, + full_state_dict=(not self._save_distributed_checkpoint), + rank=self.global_rank, + filter=filter, + ) + + @override + def load_checkpoint( + self, + path: _PATH, + state: Optional[Union[Module, Optimizer, dict[str, Union[Module, Optimizer, Any]]]] = None, + strict: bool = True, + weights_only: Optional[bool] = None, + ) -> dict[str, Any]: + """Load the contents from a checkpoint and restore the state of the given objects.""" + if not state: + raise ValueError( + f"Got {type(self).__name__}.load_checkpoint(..., state={state!r}) but a state with at least " + " a model instance to reload is required. Pass it in like so:" + f" {type(self).__name__}.load_checkpoint(..., state={{'model': model, ...}})" + ) + # broadcast the path from rank 0 to ensure all the states are loaded from a common path + path = Path(self.broadcast(path)) + + if isinstance(state, Module): + _load_raw_module_state_from_path(path, module=state, world_size=self.world_size, strict=strict) + return {} + + if isinstance(state, Optimizer): + raise NotImplementedError( + f"Loading a single optimizer object from a checkpoint is not supported yet with {type(self).__name__}." + ) + + return _load_checkpoint(path=path, state=state, strict=strict, weights_only=weights_only) + + def _setup_distributed(self) -> None: + reset_seed() + self._set_world_ranks() + self._process_group_backend = self._get_process_group_backend() + assert self.cluster_environment is not None + kwargs: dict[str, Any] = {"timeout": self._timeout} + if _TORCH_GREATER_EQUAL_2_3: + kwargs["device_id"] = self.root_device if self.root_device.type != "cpu" else None + _init_dist_connection(self.cluster_environment, self._process_group_backend, **kwargs) + + def _get_process_group_backend(self) -> str: + return self._process_group_backend or _get_default_process_group_backend_for_device(self.root_device) + + def _set_world_ranks(self) -> None: + if self.cluster_environment is not None: + self.cluster_environment.set_global_rank(self.node_rank * self.num_processes + self.local_rank) + self.cluster_environment.set_world_size(self.num_nodes * self.num_processes) + # `LightningEnvironment.set_global_rank` will do this too, but we cannot rely on that implementation detail + # additionally, for some implementations, the setter is a no-op, so it's safer to access the getter + rank_zero_only.rank = utils_rank_zero_only.rank = self.global_rank + + +class _ParallelBackwardSyncControl(_BackwardSyncControl): + @override + def no_backward_sync(self, module: Module, enabled: bool) -> AbstractContextManager: + """Blocks gradient synchronization inside the FSDP2 modules.""" + return _FSDPNoSync(module=module, enabled=enabled) + + +class _FSDPNoSync(AbstractContextManager): + def __init__(self, module: Module, enabled: bool) -> None: + self._module = module + self._enabled = enabled + + def _set_requires_grad_sync(self, requires_grad_sync: bool) -> None: + from torch.distributed._composable.fsdp import FSDPModule + + for mod in self._module.modules(): + if isinstance(mod, FSDPModule): + mod.set_requires_gradient_sync(requires_grad_sync, recurse=False) + + def __enter__(self) -> None: + self._set_requires_grad_sync(not self._enabled) + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + self._set_requires_grad_sync(self._enabled) + + +def _save_checkpoint( + path: Path, + state: dict[str, Union[Module, Optimizer, Any]], + full_state_dict: bool, + rank: int, + filter: Optional[dict[str, Callable[[str, Any], bool]]] = None, +) -> None: + if path.is_dir() and full_state_dict and not _is_sharded_checkpoint(path): + raise IsADirectoryError(f"The checkpoint path exists and is a directory: {path}") + + modules = [module for module in state.values() if _has_dtensor_modules(module)] + if len(modules) == 0: + raise ValueError( + "Could not find a distributed model in the provided checkpoint state. Please provide the model as" + " part of the state like so: `save_checkpoint(..., state={'model': model, ...})`. Make sure" + " you set up the model (and optimizers if any) through the strategy before saving the checkpoint." + ) + if len(modules) > 1: + raise ValueError( + "Found multiple distributed models in the given state. Saving distributed checkpoints is" + " currently limited to a single model per checkpoint. To save multiple models, call the" + " save method for each model separately with a different path." + ) + module = modules[0] + + from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict, get_optimizer_state_dict + + state_dict_options = StateDictOptions(full_state_dict=full_state_dict, cpu_offload=True) + + # replace the modules and optimizer objects in the state with their local state dict + # and separate the user's metadata + converted_state: dict[str, Any] = {} + metadata: dict[str, Any] = {} + for key, obj in state.items(): + converted: Any + if isinstance(obj, Module): + converted = get_model_state_dict(obj, options=state_dict_options) + target_dict = converted_state + elif isinstance(obj, Optimizer): + converted = get_optimizer_state_dict(module, obj, options=state_dict_options) + target_dict = converted_state + else: # everything not a module or optimizer is considered metadata + converted = obj.state_dict() if isinstance(obj, _Stateful) else obj + target_dict = metadata + _apply_filter(key, filter or {}, converted, target_dict) + + if full_state_dict: + if _is_sharded_checkpoint(path): + shutil.rmtree(path) + converted_state.update(metadata) + if rank == 0: + torch.save(converted_state, path) + else: + if path.is_file(): + path.unlink() + path.mkdir(parents=True, exist_ok=True) + _distributed_checkpoint_save(converted_state, path) + if rank == 0: + torch.save(metadata, path / _METADATA_FILENAME) + + +def _load_checkpoint( + path: Path, + state: dict[str, Union[Module, Optimizer, Any]], + strict: bool = True, + optimizer_states_from_list: bool = False, + weights_only: Optional[bool] = None, +) -> dict[str, Any]: + from torch.distributed.checkpoint.state_dict import ( + StateDictOptions, + get_model_state_dict, + get_optimizer_state_dict, + set_optimizer_state_dict, + ) + + modules = {key: module for key, module in state.items() if _has_dtensor_modules(module)} + if len(modules) == 0: + raise ValueError( + "Could not find a distributed model in the provided checkpoint state. Please provide the model as" + " part of the state like so: `load_checkpoint(..., state={'model': model, ...})`. Make sure" + " you set up the model (and optimizers if any) through the strategy before loading the checkpoint." + ) + optimizers = {key: optim for key, optim in state.items() if isinstance(optim, Optimizer)} + if len(modules) > 1: + raise ValueError( + "Found multiple distributed models in the given state. Loading distributed checkpoints is" + " currently limited to a single model per checkpoint. To load multiple models, call the" + " load method for each model separately with a different path." + ) + module_key, module = list(modules.items())[0] + + if _is_sharded_checkpoint(path): + state_dict_options = StateDictOptions(cpu_offload=True) + + module_state = {module_key: get_model_state_dict(module)} + _distributed_checkpoint_load(module_state, path) + module.load_state_dict(module_state[module_key], strict=strict) + + # the optimizer states must be loaded separately + for optim_key, optim in optimizers.items(): + optim_state = {optim_key: get_optimizer_state_dict(module, optim)} + _distributed_checkpoint_load(optim_state, path) + set_optimizer_state_dict(module, optim, optim_state_dict=optim_state[optim_key], options=state_dict_options) + + # Load metadata (anything not a module or optimizer) + metadata = torch.load(path / _METADATA_FILENAME, weights_only=weights_only) + requested_metadata_keys = state.keys() - modules.keys() - optimizers.keys() + _validate_keys_for_strict_loading(requested_metadata_keys, metadata.keys(), strict=strict) + for key in requested_metadata_keys: + if key not in metadata: + continue + state[key] = metadata.pop(key) + + # return the remaining metadata that wasn't requested as part of `state` + return metadata + + if _is_full_checkpoint(path): + checkpoint = torch.load(path, mmap=True, map_location="cpu", weights_only=weights_only) + _load_raw_module_state(checkpoint.pop(module_key), module, strict=strict) + + state_dict_options = StateDictOptions( + broadcast_from_rank0=True, + full_state_dict=True, + strict=strict, + ) + for optimizer_idx, (optimizer_name, optimizer) in enumerate(optimizers.items()): + if optimizer_states_from_list: + # This code path is only used by `pytorch_lightning`, which saves optimizer states as a list + # rather than individual states at the top level. + optimizer_state = checkpoint["optimizer_states"][optimizer_idx] + else: + optimizer_state = checkpoint.pop(optimizer_name) + + optimizer_state = _rekey_optimizer_state_if_needed(optimizer_state, module) + set_optimizer_state_dict( + module, + optimizer, + optim_state_dict=optimizer_state, + options=state_dict_options, + ) + + requested_metadata_keys = state.keys() - modules.keys() - optimizers.keys() + _validate_keys_for_strict_loading(requested_metadata_keys, checkpoint.keys(), strict=strict) + + # Load metadata (anything not a module or optimizer) + _move_state_into(source=checkpoint, destination=state, keys=requested_metadata_keys) + + # return the remaining metadata that wasn't requested as part of `state` + return checkpoint + + raise ValueError( + f"The path {str(path)!r} does not point to a valid checkpoint. Make sure the path points to either a" + " directory with distributed checkpoint shards, or a single file with a full checkpoint." + ) + + +def _setup_device_mesh( + data_parallel_size: int, + tensor_parallel_size: int, + world_size: int, + device: torch.device, +) -> "DeviceMesh": + from torch.distributed.device_mesh import init_device_mesh + + if data_parallel_size * tensor_parallel_size != world_size: + raise RuntimeError( + f"The sizes `data_parallel_size={data_parallel_size}` and" + f" `tensor_parallel_size={tensor_parallel_size}` multiplied should equal the world size" + f" ({world_size})." + ) + return init_device_mesh( + device_type=device.type, + mesh_shape=(data_parallel_size, tensor_parallel_size), + mesh_dim_names=("data_parallel", "tensor_parallel"), + ) + + +def _has_dtensor_modules(module: object) -> TypeGuard[Module]: + from torch.distributed._tensor import DTensor + + return isinstance(module, Module) and any(isinstance(t, DTensor) for t in module.parameters()) + + +def _load_raw_module_state_from_path(path: Path, module: Module, world_size: int, strict: bool = True) -> None: + """Loads the state dict from a file path into the FSDP module.""" + if not _is_full_checkpoint(path): + raise ValueError( + "Failed to load checkpoint directly into the model. The given path must be a single file containing the" + f" full state dict: {path}" + ) + # Use `lazy_load`/`mmap` instead to avoid storing a copy of the full checkpoint per rank + state_dict = torch.load(path, mmap=True, map_location="cpu") if _TORCH_GREATER_EQUAL_2_3 else _lazy_load(path) + _load_raw_module_state(state_dict=state_dict, module=module, world_size=world_size, strict=strict) + + +def _load_raw_module_state( + state_dict: dict[str, Any], module: Module, world_size: int = 1, strict: bool = True +) -> None: + """Loads the state dict into the module by gathering all weights first and then and writing back to each shard.""" + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + + if _has_dtensor_modules(module): + from torch.distributed.checkpoint.state_dict import StateDictOptions, set_model_state_dict + + state_dict_options = StateDictOptions( + broadcast_from_rank0=True, + full_state_dict=True, + # must be set False to allow loading each param separately below + strict=False, + ) + + for submodule_name, submodule in module.named_modules(): + for param_name, _ in _named_parameters_and_buffers_to_load(submodule): + full_param_name = f"{submodule_name}{'.' if submodule_name else ''}{param_name}" + if full_param_name not in state_dict: + if not strict: + continue + raise KeyError( + f"The model contains a key '{full_param_name}' that does not exist in the loaded checkpoint." + " To disable strict loading, set `strict=False`." + ) + local_state_dict = {param_name: state_dict[full_param_name]} + set_model_state_dict(submodule, local_state_dict, options=state_dict_options) + + elif isinstance(module, FSDP): + with _get_full_state_dict_context(module, world_size=world_size, rank0_only=False): + module.load_state_dict(state_dict, strict=strict) + else: + module.load_state_dict(state_dict, strict=strict) + + +def _named_parameters_and_buffers_to_load(module: Module) -> Generator: + """Returns parameters and buffers, with non-persistent buffers excluded.""" + for param_name, param in itertools.chain( + module.named_buffers(recurse=False), + module.named_parameters(recurse=False), + ): + if param_name in module._non_persistent_buffers_set: + continue + yield param_name, param + + +def _rekey_optimizer_state_if_needed(optimizer_state_dict: dict[str, Any], module: Module) -> dict[str, Any]: + """Handles the case where the optimizer state is saved from a normal optimizer and converts the keys to parameter + names.""" + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp import OptimStateKeyType + + if isinstance(list(optimizer_state_dict["state"].keys())[0], int): + optimizer_state_dict = FSDP.rekey_optim_state_dict(optimizer_state_dict, OptimStateKeyType.PARAM_NAME, module) + return optimizer_state_dict diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/parallel.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..8764c13186c4652d4dc489712fc927dcefa5414f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/parallel.py @@ -0,0 +1,114 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from abc import ABC +from typing import Any, Optional + +import torch +from torch import Tensor +from typing_extensions import override + +from lightning_fabric.accelerators.accelerator import Accelerator +from lightning_fabric.plugins.environments.cluster_environment import ClusterEnvironment +from lightning_fabric.plugins.io.checkpoint_io import CheckpointIO +from lightning_fabric.plugins.precision import Precision +from lightning_fabric.strategies.strategy import Strategy +from lightning_fabric.utilities.distributed import _all_gather_ddp_if_available +from lightning_fabric.utilities.types import ReduceOp + + +class ParallelStrategy(Strategy, ABC): + """Strategy for training with multiple processes in parallel.""" + + def __init__( + self, + accelerator: Optional[Accelerator] = None, + parallel_devices: Optional[list[torch.device]] = None, + cluster_environment: Optional[ClusterEnvironment] = None, + checkpoint_io: Optional[CheckpointIO] = None, + precision: Optional[Precision] = None, + ): + super().__init__(accelerator=accelerator, checkpoint_io=checkpoint_io, precision=precision) + self.parallel_devices = parallel_devices + self.cluster_environment: Optional[ClusterEnvironment] = cluster_environment + + @property + def global_rank(self) -> int: + return self.cluster_environment.global_rank() if self.cluster_environment is not None else 0 + + @property + def local_rank(self) -> int: + return self.cluster_environment.local_rank() if self.cluster_environment is not None else 0 + + @property + def node_rank(self) -> int: + return self.cluster_environment.node_rank() if self.cluster_environment is not None else 0 + + @property + def world_size(self) -> int: + return self.cluster_environment.world_size() if self.cluster_environment is not None else 1 + + @property + @override + def is_global_zero(self) -> bool: + return self.global_rank == 0 + + @property + def parallel_devices(self) -> Optional[list[torch.device]]: + return self._parallel_devices + + @parallel_devices.setter + def parallel_devices(self, parallel_devices: Optional[list[torch.device]]) -> None: + self._parallel_devices = parallel_devices + + @property + def distributed_sampler_kwargs(self) -> Optional[dict[str, Any]]: + """Arguments for the ``DistributedSampler``. + + If this method is not defined, or it returns ``None``, then the ``DistributedSampler`` will not be used. + + """ + return {"num_replicas": self.world_size, "rank": self.global_rank} + + @override + def all_gather(self, tensor: Tensor, group: Optional[Any] = None, sync_grads: bool = False) -> Tensor: + """Perform a all_gather on all processes.""" + return _all_gather_ddp_if_available(tensor, group=group, sync_grads=sync_grads) + + @override + def reduce_boolean_decision(self, decision: bool, all: bool = True) -> bool: + """Reduces a boolean decision over distributed processes. By default is analogous to ``all`` from the standard + library, returning ``True`` only if all input decisions evaluate to ``True``. If ``all`` is set to ``False``, + it behaves like ``any`` instead. + + Args: + decision: A single input decision. + all: Whether to logically emulate ``all`` or ``any``. Defaults to True. + + Returns: + bool: The reduced boolean decision. + + """ + decision = torch.tensor(int(decision), device=self.root_device) + decision = self.all_reduce( + decision, + reduce_op=ReduceOp.SUM, # type: ignore[arg-type] + ) + decision = bool(decision == self.world_size) if all else bool(decision) + return decision + + @override + def teardown(self) -> None: + assert self.cluster_environment is not None + self.cluster_environment.teardown() + return super().teardown() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/registry.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..d2376463c3111a66c2096404eaf9ce7966d2caa9 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/registry.py @@ -0,0 +1,112 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Callable, Optional + +from typing_extensions import override + + +class _StrategyRegistry(dict): + """This class is a Registry that stores information about the Training Strategies. + + The Strategies are mapped to strings. These strings are names that identify + a strategy, e.g., "deepspeed". It also returns Optional description and + parameters to initialize the Strategy, which were defined durng the + registration. + + The motivation for having a StrategyRegistry is to make it convenient + for the Users to try different Strategies by passing just strings + to the strategy flag to the Trainer. + + Example:: + + @StrategyRegistry.register("lightning", description="Super fast", a=1, b=True) + class LightningStrategy: + def __init__(self, a, b): + ... + + or + + StrategyRegistry.register("lightning", LightningStrategy, description="Super fast", a=1, b=True) + + """ + + def register( + self, + name: str, + strategy: Optional[Callable] = None, + description: Optional[str] = None, + override: bool = False, + **init_params: Any, + ) -> Callable: + """Registers a strategy mapped to a name and with required metadata. + + Args: + name : the name that identifies a strategy, e.g. "deepspeed_stage_3" + strategy : strategy class + description : strategy description + override : overrides the registered strategy, if True + init_params: parameters to initialize the strategy + + """ + if not (name is None or isinstance(name, str)): + raise TypeError(f"`name` must be a str, found {name}") + + if name in self and not override: + raise ValueError(f"'{name}' is already present in the registry. HINT: Use `override=True`.") + + data: dict[str, Any] = {} + data["description"] = description if description is not None else "" + + data["init_params"] = init_params + + def do_register(strategy: Callable) -> Callable: + data["strategy"] = strategy + data["strategy_name"] = name + self[name] = data + return strategy + + if strategy is not None: + return do_register(strategy) + + return do_register + + @override + def get(self, name: str, default: Optional[Any] = None) -> Any: + """Calls the registered strategy with the required parameters and returns the strategy object. + + Args: + name (str): the name that identifies a strategy, e.g. "deepspeed_stage_3" + + """ + if name in self: + data = self[name] + return data["strategy"](**data["init_params"]) + + if default is not None: + return default + + err_msg = "'{}' not found in registry. Available names: {}" + available_names = ", ".join(sorted(self.keys())) or "none" + raise KeyError(err_msg.format(name, available_names)) + + def remove(self, name: str) -> None: + """Removes the registered strategy by name.""" + self.pop(name) + + def available_strategies(self) -> list: + """Returns a list of registered strategies.""" + return list(self.keys()) + + def __str__(self) -> str: + return "Registered Strategies: {}".format(", ".join(self.keys())) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/single_device.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/single_device.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4b1bc5a81e64b9ecafce839f7653d4fbcc2e5f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/single_device.py @@ -0,0 +1,88 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from typing import Any + +import torch +from torch.nn import Module +from typing_extensions import override + +from lightning_fabric.accelerators import Accelerator +from lightning_fabric.plugins.io.checkpoint_io import CheckpointIO +from lightning_fabric.plugins.precision import Precision +from lightning_fabric.strategies.strategy import Strategy, TBroadcast +from lightning_fabric.utilities.types import _DEVICE + + +class SingleDeviceStrategy(Strategy): + """Strategy that handles communication on a single device.""" + + def __init__( + self, + device: _DEVICE = "cpu", + accelerator: Accelerator | None = None, + checkpoint_io: CheckpointIO | None = None, + precision: Precision | None = None, + ): + super().__init__(accelerator=accelerator, checkpoint_io=checkpoint_io, precision=precision) + if not isinstance(device, torch.device): + device = torch.device(device) + self._root_device = device + self.global_rank = 0 + self.local_rank = 0 + self.world_size = 1 + + @property + @override + def root_device(self) -> torch.device: + return self._root_device + + @property + @override + def is_global_zero(self) -> bool: + return True + + @override + def module_to_device(self, module: Module) -> None: + module.to(self.root_device) + + @override + def all_reduce(self, tensor: Any | torch.Tensor, *args: Any, **kwargs: Any) -> Any | torch.Tensor: + """Reduces a tensor from several distributed processes to one aggregated tensor. As this plugin only operates + with a single device, the reduction is simply the identity. + + Args: + tensor: the tensor to sync and reduce + *args: ignored + **kwargs: ignored + + Return: + the unmodified input as reduction is not needed for single process operation + + """ + return tensor + + @override + def all_gather(self, tensor: torch.Tensor, group: Any | None = None, sync_grads: bool = False) -> torch.Tensor: + """Perform a ``all_gather`` on all processes.""" + return tensor + + @override + def barrier(self, *args: Any, **kwargs: Any) -> None: + pass + + @override + def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast: + return obj diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/single_xla.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/single_xla.py new file mode 100644 index 0000000000000000000000000000000000000000..fae03ab69fcc85d8a8b1b8db797310b11f1d27c8 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/single_xla.py @@ -0,0 +1,88 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Optional + +import torch +from typing_extensions import override + +from lightning_fabric.accelerators import Accelerator +from lightning_fabric.accelerators.xla import _XLA_AVAILABLE +from lightning_fabric.plugins import CheckpointIO, Precision, XLAPrecision +from lightning_fabric.plugins.io.xla import XLACheckpointIO +from lightning_fabric.strategies import _StrategyRegistry +from lightning_fabric.strategies.single_device import SingleDeviceStrategy +from lightning_fabric.utilities.types import _DEVICE + + +class SingleDeviceXLAStrategy(SingleDeviceStrategy): + """Strategy for training on a single XLA device.""" + + def __init__( + self, + device: _DEVICE, + accelerator: Optional[Accelerator] = None, + checkpoint_io: Optional[XLACheckpointIO] = None, + precision: Optional[XLAPrecision] = None, + ): + if not _XLA_AVAILABLE: + raise ModuleNotFoundError(str(_XLA_AVAILABLE)) + if isinstance(device, torch.device): + # unwrap the `torch.device` in favor of `xla_device` + device = device.index + + import torch_xla.core.xla_model as xm + + super().__init__( + accelerator=accelerator, + device=xm.xla_device(device), + checkpoint_io=checkpoint_io, + precision=precision, + ) + + @property + @override + def checkpoint_io(self) -> XLACheckpointIO: + plugin = self._checkpoint_io + if plugin is not None: + assert isinstance(plugin, XLACheckpointIO) + return plugin + return XLACheckpointIO() + + @checkpoint_io.setter + @override + def checkpoint_io(self, io: Optional[CheckpointIO]) -> None: + if io is not None and not isinstance(io, XLACheckpointIO): + raise TypeError(f"The XLA strategy can only work with the `XLACheckpointIO` plugin, found {io}") + self._checkpoint_io = io + + @property + @override + def precision(self) -> XLAPrecision: + plugin = self._precision + if plugin is not None: + assert isinstance(plugin, XLAPrecision) + return plugin + return XLAPrecision("32-true") + + @precision.setter + @override + def precision(self, precision: Optional[Precision]) -> None: + if precision is not None and not isinstance(precision, XLAPrecision): + raise TypeError(f"The XLA strategy can only work with the `XLAPrecision` plugin, found {precision}") + self._precision = precision + + @classmethod + @override + def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: + strategy_registry.register("single_xla", cls, description=cls.__name__) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/strategy.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..9a3ff5fe66f25c6baaba7236c716a546f4b3122c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/strategy.py @@ -0,0 +1,479 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import logging +from abc import ABC, abstractmethod +from collections.abc import Iterable +from contextlib import AbstractContextManager, ExitStack +from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union + +import torch +from torch import Tensor +from torch.nn import Module +from torch.optim import Optimizer +from torch.utils.data import DataLoader + +from lightning_fabric.accelerators import Accelerator +from lightning_fabric.plugins.io.checkpoint_io import CheckpointIO +from lightning_fabric.plugins.io.torch_io import TorchCheckpointIO +from lightning_fabric.plugins.precision import Precision +from lightning_fabric.strategies.launchers.launcher import _Launcher +from lightning_fabric.strategies.registry import _StrategyRegistry +from lightning_fabric.utilities.apply_func import move_data_to_device +from lightning_fabric.utilities.init import _EmptyInit +from lightning_fabric.utilities.types import _PATH, Optimizable, ReduceOp, _Stateful + +if TYPE_CHECKING: + from torch.optim.lr_scheduler import _LRScheduler + +TBroadcast = TypeVar("TBroadcast") +TReduce = TypeVar("TReduce") + +log = logging.getLogger(__name__) + + +class Strategy(ABC): + """Base class for all strategies that change the behaviour of the training, validation and test- loop.""" + + def __init__( + self, + accelerator: Optional[Accelerator] = None, + checkpoint_io: Optional[CheckpointIO] = None, + precision: Optional[Precision] = None, + ) -> None: + self._accelerator: Optional[Accelerator] = accelerator + self._checkpoint_io: Optional[CheckpointIO] = checkpoint_io + self._precision: Optional[Precision] = None + # Call the precision setter for input validation + self.precision = precision + self._launcher: Optional[_Launcher] = None + self._backward_sync_control: Optional[_BackwardSyncControl] = None + + @property + @abstractmethod + def root_device(self) -> torch.device: + """Returns the root device.""" + + @property + @abstractmethod + def is_global_zero(self) -> bool: + """Whether the current process is the rank zero process not only on the local node, but for all nodes.""" + + @property + def launcher(self) -> Optional[_Launcher]: + return self._launcher + + @property + def accelerator(self) -> Optional[Accelerator]: + return self._accelerator + + @accelerator.setter + def accelerator(self, accelerator: Accelerator) -> None: + self._accelerator = accelerator + + @property + def checkpoint_io(self) -> CheckpointIO: + if self._checkpoint_io is None: + self._checkpoint_io = TorchCheckpointIO() + return self._checkpoint_io + + @checkpoint_io.setter + def checkpoint_io(self, io: CheckpointIO) -> None: + self._checkpoint_io = io + + @property + def precision(self) -> Precision: + return self._precision if self._precision is not None else Precision() + + @precision.setter + def precision(self, precision: Optional[Precision]) -> None: + self._precision = precision + + def _configure_launcher(self) -> None: + """Attach the launcher based on Strategy.""" + + def setup_environment(self) -> None: + """Setup any processes or distributed connections. + + This must be called by the framework at the beginning of every process, before any distributed communication + takes place. + + """ + assert self.accelerator is not None + self.accelerator.setup_device(self.root_device) + + def process_dataloader(self, dataloader: DataLoader) -> DataLoader: + """Wraps the dataloader if necessary. + + Args: + dataloader: iterable. Ideally of type: :class:`torch.utils.data.DataLoader` + + """ + return dataloader + + def tensor_init_context(self) -> AbstractContextManager: + """Controls how tensors get created (device, dtype).""" + precision_init_ctx = self.precision.tensor_init_context() + stack = ExitStack() + stack.enter_context(self.root_device) + stack.enter_context(precision_init_ctx) + return stack + + def module_init_context(self, empty_init: Optional[bool] = None) -> AbstractContextManager: + """A context manager wrapping the model instantiation. + + Here, the strategy can control how the parameters of the model get created (device, dtype) and or apply other + patches to the model. + + Args: + empty_init: Whether to initialize the model with empty weights (uninitialized memory). + If ``None``, the strategy will decide. Some strategies may not support all options. + + """ + precision_module_ctx = self.precision.module_init_context() + stack = ExitStack() + stack.enter_context(self.root_device) + stack.enter_context(_EmptyInit(enabled=bool(empty_init))) + stack.enter_context(precision_module_ctx) + return stack + + def setup_module_and_optimizers( + self, module: Module, optimizers: list[Optimizer], scheduler: Optional["_LRScheduler"] = None + ) -> tuple[Module, list[Optimizer], Optional["_LRScheduler"]]: + """Set up a model and multiple optimizers together. + + The returned objects are expected to be in the same order they were passed in. The default implementation will + call :meth:`setup_module` and :meth:`setup_optimizer` on the inputs. + + """ + module = self.setup_module(module) + optimizers = [self.setup_optimizer(optimizer) for optimizer in optimizers] + return module, optimizers, scheduler + + def setup_module(self, module: Module) -> Module: + """Performs setup for the model, e.g., by wrapping it by another class.""" + return module + + def setup_optimizer(self, optimizer: Optimizer) -> Optimizer: + """Performs setup for the optimizer, e.g., by wrapping it by another class.""" + return optimizer + + @abstractmethod + def module_to_device(self, module: Module) -> None: + """Moves the model to the correct device.""" + + def batch_to_device(self, batch: Any, device: Optional[torch.device] = None) -> Any: + """Moves the batch to the correct device. + + The returned batch is of the same type as the input batch, just + having all tensors on the correct device. + + Args: + batch: The batch of samples to move to the correct device + device: The target device + + """ + device = device or self.root_device + return move_data_to_device(batch, device) + + def backward(self, tensor: Tensor, module: Optional[Module], *args: Any, **kwargs: Any) -> None: + r"""Forwards backward-calls to the precision plugin.""" + self.precision.pre_backward(tensor, module) + self.precision.backward(tensor, module, *args, **kwargs) + self.precision.post_backward(tensor, module) + + def optimizer_step( + self, + optimizer: Optimizable, + **kwargs: Any, + ) -> Any: + """Performs the actual optimizer step. + + Args: + optimizer: the optimizer performing the step + **kwargs: Any extra arguments to ``optimizer.step`` + + """ + return self.precision.optimizer_step(optimizer, **kwargs) + + @abstractmethod + def all_gather(self, tensor: Tensor, group: Optional[Any] = None, sync_grads: bool = False) -> Tensor: + """Perform an all_gather on all processes. + + Args: + tensor: the tensor to all_gather + group: the process group to gather results from + sync_grads: flag that allows users to synchronize gradients for all_gather op + + """ + + @abstractmethod + def all_reduce( + self, + tensor: Union[Tensor, Any], + group: Optional[Any] = None, + reduce_op: Optional[Union[ReduceOp, str]] = "mean", + ) -> Union[Tensor, Any]: + """Reduces the given tensor (e.g. across GPUs/processes). + + Args: + tensor: the tensor to sync and reduce + group: the process group to reduce + reduce_op: the reduction operation. Defaults to 'mean'. + Can also be a string 'sum' or ReduceOp. + + """ + + @abstractmethod + def barrier(self, name: Optional[str] = None) -> None: + """Synchronizes all processes which blocks processes until the whole group enters this function. + + Args: + name: an optional name to pass into barrier. + + """ + + @abstractmethod + def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast: + """Broadcasts an object to all processes. + + Args: + obj: the object to broadcast + src: source rank + + """ + + def reduce_boolean_decision(self, decision: bool, all: bool = True) -> bool: + """Reduce a boolean decision across all processes.""" + return decision + + def save_checkpoint( + self, + path: _PATH, + state: dict[str, Union[Module, Optimizer, Any]], + storage_options: Optional[Any] = None, + filter: Optional[dict[str, Callable[[str, Any], bool]]] = None, + ) -> None: + """Save model, optimizer, and other state as a checkpoint file. + + Args: + path: A path to where the file(s) should be saved + state: A dictionary with contents to be saved. If the dict contains modules or optimizers, their + state-dict will be retrieved and converted automatically. + storage_options: Additional options for the ``CheckpointIO`` plugin + filter: An optional dictionary containing filter callables that return a boolean indicating whether the + given item should be saved (``True``) or filtered out (``False``). Each filter key should match a + state key, where its filter will be applied to the ``state_dict`` generated. + + """ + state = self._convert_stateful_objects_in_state(state, filter=(filter or {})) + if self.is_global_zero: + self.checkpoint_io.save_checkpoint(checkpoint=state, path=path, storage_options=storage_options) + + def get_module_state_dict(self, module: Module) -> dict[str, Union[Any, Tensor]]: + """Returns model state.""" + return module.state_dict() + + def load_module_state_dict( + self, module: Module, state_dict: dict[str, Union[Any, Tensor]], strict: bool = True + ) -> None: + """Loads the given state into the model.""" + module.load_state_dict(state_dict, strict=strict) + + def get_optimizer_state(self, optimizer: Optimizer) -> dict[str, Tensor]: + """Returns state of an optimizer. + + Allows for syncing/collating optimizer state from processes in custom plugins. + + """ + if hasattr(optimizer, "consolidate_state_dict"): + # there are optimizers like PyTorch's ZeroRedundancyOptimizer that shard their + # states, and to avoid OOM we consolidate the full state on rank 0 only + optimizer.consolidate_state_dict() + return optimizer.state_dict() if self.is_global_zero else {} + + # for optimizers that are not sharded, we return the state dict on all ranks + return optimizer.state_dict() + + def load_checkpoint( + self, + path: _PATH, + state: Optional[Union[Module, Optimizer, dict[str, Union[Module, Optimizer, Any]]]] = None, + strict: bool = True, + weights_only: Optional[bool] = None, + ) -> dict[str, Any]: + """Load the contents from a checkpoint and restore the state of the given objects. + + Args: + path: A path to where the file is located + state: Can be one of: + + - A dictionary of objects whose state will be restored in-place from the checkpoint path. + - ``None`` or the empty dict: The loaded checkpoint will be returned in full. + - A :class:`~torch.nn.Module` instance, if the checkpoint file contains a raw module state dict. + - A :class:`~torch.optim.Optimizer` instance, if the checkpoint file contains a raw optimizer state. + + strict: Whether to enforce that the keys in `state` match the keys in the checkpoint. + weights_only: Defaults to ``None``. If ``True``, restricts loading to ``state_dicts`` of plain + ``torch.Tensor`` and other primitive types. If loading a checkpoint from a trusted source that contains + an ``nn.Module``, use ``weights_only=False``. If loading checkpoint from an untrusted source, we + recommend using ``weights_only=True``. For more information, please refer to the + `PyTorch Developer Notes on Serialization Semantics `_. + + Returns: + The remaining items that were not restored into the given state dictionary. If no state dictionary is + given, the full checkpoint will be returned. + + """ + torch.cuda.empty_cache() + checkpoint = self.checkpoint_io.load_checkpoint(path, weights_only=weights_only) + if not state: + return checkpoint + + if isinstance(state, Module): + self.load_module_state_dict(module=state, state_dict=checkpoint, strict=strict) + return {} + + if isinstance(state, Optimizer): + state.load_state_dict(checkpoint) + return {} + + _validate_keys_for_strict_loading(state.keys(), checkpoint.keys(), strict=strict) + for name, obj in state.copy().items(): + if name not in checkpoint: + continue + if isinstance(obj, _Stateful): + if isinstance(obj, Module): + self.load_module_state_dict(module=obj, state_dict=checkpoint.pop(name), strict=strict) + else: + obj.load_state_dict(checkpoint.pop(name)) + else: + state[name] = checkpoint.pop(name) + return checkpoint + + def teardown(self) -> None: + """This method is called to teardown the training process. + + It is the right place to release memory and free other resources. + + """ + self.precision.teardown() + assert self.accelerator is not None + self.accelerator.teardown() + self.checkpoint_io.teardown() + + def clip_gradients_norm( + self, + module: torch.nn.Module, + optimizer: Optimizer, + max_norm: Union[float, int], + norm_type: Union[float, int] = 2.0, + error_if_nonfinite: bool = True, + ) -> torch.Tensor: + """Clip gradients by norm.""" + self.precision.unscale_gradients(optimizer) + parameters = self.precision.main_params(optimizer) + return torch.nn.utils.clip_grad_norm_( + parameters, max_norm=max_norm, norm_type=norm_type, error_if_nonfinite=error_if_nonfinite + ) + + def clip_gradients_value(self, module: torch.nn.Module, optimizer: Optimizer, clip_val: Union[float, int]) -> None: + """Clip gradients by value.""" + self.precision.unscale_gradients(optimizer) + parameters = self.precision.main_params(optimizer) + return torch.nn.utils.clip_grad_value_(parameters, clip_value=clip_val) + + @classmethod + def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: + pass + + def _err_msg_joint_setup_required(self) -> str: + return ( + f"The `{type(self).__name__}` does not support setting up the module and optimizer(s) independently." + " Please call `setup_module_and_optimizers(model, [optimizer, ...])` to jointly set them up." + ) + + def _convert_stateful_objects_in_state( + self, state: dict[str, Union[Module, Optimizer, Any]], filter: dict[str, Callable[[str, Any], bool]] + ) -> dict[str, Any]: + converted_state: dict[str, Any] = {} + for key, obj in state.items(): + # convert the state + if isinstance(obj, Module): + converted = self.get_module_state_dict(module=obj) + elif isinstance(obj, Optimizer): + converted = self.get_optimizer_state(optimizer=obj) + elif isinstance(obj, _Stateful): + converted = obj.state_dict() + else: + converted = obj + _apply_filter(key, filter, converted, converted_state) + return converted_state + + +class _BackwardSyncControl(ABC): + """Interface for any :class:`Strategy` that wants to offer a functionality to enable or disable gradient + synchronization during/after back-propagation. + + The most common use-case is gradient accumulation. If a :class:`Strategy` implements this interface, the user can + implement their gradient accumulation loop very efficiently by disabling redundant gradient synchronization. + + """ + + @abstractmethod + def no_backward_sync(self, module: Module, enabled: bool) -> AbstractContextManager: + """Blocks the synchronization of gradients during the backward pass. + + This is a context manager. It is only effective if it wraps a call to `.backward()`. + + """ + + +class _Sharded(ABC): + """Mixin-interface for any :class:`Strategy` that wants to expose functionality for sharding model parameters.""" + + @abstractmethod + def module_sharded_context(self) -> AbstractContextManager: + """A context manager that goes over the instantiation of an :class:`torch.nn.Module` and handles sharding of + parameters on creation. + + By sharding layers directly on instantiation, one can reduce peak memory usage and initialization time. + + """ + + +def _validate_keys_for_strict_loading( + requested_keys: Iterable[str], checkpoint_keys: Iterable[str], strict: bool +) -> None: + invalid_keys = [k for k in requested_keys if k not in checkpoint_keys] + if strict and invalid_keys: + raise KeyError( + f"The requested state contains a key '{invalid_keys[0]}' that does not exist in the loaded checkpoint." + f" To disable strict loading, set `strict=False`." + ) + + +def _apply_filter( + key: str, filter: dict[str, Callable[[str, Any], bool]], source_dict: object, target_dict: dict[str, Any] +) -> None: + # filter out if necessary + if key in filter and isinstance(source_dict, dict): + filter_fn = filter[key] + for k, v in source_dict.items(): + if filter_fn(k, v): + # save the state + target_dict.setdefault(key, {}) + target_dict[key][k] = v + else: + # save the state + target_dict[key] = source_dict diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/xla.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/xla.py new file mode 100644 index 0000000000000000000000000000000000000000..8e984ca1dd101890758dfefca0d952d9fedacc21 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/xla.py @@ -0,0 +1,304 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import io +from typing import TYPE_CHECKING, Any, Callable, Optional, Union + +import torch +from torch import Tensor +from torch.nn import Module +from torch.optim import Optimizer +from torch.utils.data import DataLoader +from typing_extensions import override + +from lightning_fabric.accelerators import Accelerator +from lightning_fabric.accelerators.xla import _XLA_GREATER_EQUAL_2_1 +from lightning_fabric.plugins import CheckpointIO, Precision, XLAPrecision +from lightning_fabric.plugins.environments import XLAEnvironment +from lightning_fabric.plugins.io.xla import XLACheckpointIO +from lightning_fabric.strategies import ParallelStrategy, _StrategyRegistry +from lightning_fabric.strategies.launchers.xla import _XLALauncher +from lightning_fabric.strategies.strategy import TBroadcast +from lightning_fabric.utilities.rank_zero import rank_zero_only +from lightning_fabric.utilities.types import _PATH, ReduceOp + +if TYPE_CHECKING: + from torch_xla.distributed.parallel_loader import MpDeviceLoader + + +class XLAStrategy(ParallelStrategy): + """Strategy for training multiple TPU devices using the :func:`torch_xla.distributed.xla_multiprocessing.spawn` + method.""" + + def __init__( + self, + accelerator: Optional[Accelerator] = None, + parallel_devices: Optional[list[torch.device]] = None, + checkpoint_io: Optional[XLACheckpointIO] = None, + precision: Optional[XLAPrecision] = None, + sync_module_states: bool = True, + ) -> None: + super().__init__( + accelerator=accelerator, + parallel_devices=parallel_devices, + cluster_environment=XLAEnvironment(), + checkpoint_io=checkpoint_io, + precision=precision, + ) + self._backward_sync_control = None # XLA synchronizes gradients in the optimizer.step() call + self._launched = False + self._sync_module_states = sync_module_states + + @property + @override + def root_device(self) -> torch.device: + if not self._launched: + raise RuntimeError("Accessing the XLA device before processes have spawned is not allowed.") + import torch_xla.core.xla_model as xm + + return xm.xla_device() + + @property + def num_processes(self) -> int: + return len(self.parallel_devices) if self.parallel_devices is not None else 0 + + @property + @override + def checkpoint_io(self) -> XLACheckpointIO: + plugin = self._checkpoint_io + if plugin is not None: + assert isinstance(plugin, XLACheckpointIO) + return plugin + return XLACheckpointIO() + + @checkpoint_io.setter + @override + def checkpoint_io(self, io: Optional[CheckpointIO]) -> None: + if io is not None and not isinstance(io, XLACheckpointIO): + raise TypeError(f"The XLA strategy can only work with the `XLACheckpointIO` plugin, found {io}") + self._checkpoint_io = io + + @property + @override + def precision(self) -> XLAPrecision: + plugin = self._precision + if plugin is not None: + assert isinstance(plugin, XLAPrecision) + return plugin + return XLAPrecision("32-true") + + @precision.setter + @override + def precision(self, precision: Optional[Precision]) -> None: + if precision is not None and not isinstance(precision, XLAPrecision): + raise TypeError(f"The XLA strategy can only work with the `XLAPrecision` plugin, found {precision}") + self._precision = precision + + @property + @override + def global_rank(self) -> int: + return super().global_rank if self._launched else 0 + + @property + @override + def local_rank(self) -> int: + return super().local_rank if self._launched else 0 + + @property + @override + def node_rank(self) -> int: + return super().node_rank if self._launched else 0 + + @property + @override + def world_size(self) -> int: + return super().world_size if self._launched else 1 + + @override + def _configure_launcher(self) -> None: + self._launcher = _XLALauncher(self) + + @override + def setup_environment(self) -> None: + assert self.parallel_devices is not None + if len(self.parallel_devices) == 1: + # spawning only 1 device with PjRT is not supported: + # https://github.com/Lightning-AI/pytorch-lightning/pull/17408#discussion_r1170671732 + raise NotImplementedError( + f"The {type(self).__name__} does not support running on a single device with the PjRT runtime." + " Try using all devices or the `SingleDeviceXLAStrategy` strategy" + ) + + self._launched = True + rank_zero_only.rank = self.global_rank + super().setup_environment() + + @override + def setup_module(self, module: Module) -> Module: + if self._sync_module_states: + if _XLA_GREATER_EQUAL_2_1: + from torch_xla.core.xla_model import broadcast_master_param + else: + from torch_xla.experimental.pjrt import broadcast_master_param + + broadcast_master_param(module) + + return module + + @override + def module_to_device(self, module: Module) -> None: + module.to(self.root_device) + + @override + def process_dataloader(self, dataloader: DataLoader) -> "MpDeviceLoader": + from torch_xla.distributed.parallel_loader import MpDeviceLoader + + if isinstance(dataloader, MpDeviceLoader): + # dataloader is already wrapped by MpDeviceLoader + return dataloader + + dataloader = MpDeviceLoader(dataloader, self.root_device) + # Mimic interface to torch.utils.data.DataLoader + dataloader.dataset = dataloader._loader.dataset + dataloader.batch_sampler = getattr(dataloader._loader, "batch_sampler", None) + return dataloader + + @override + def all_gather(self, tensor: Tensor, group: Optional[Any] = None, sync_grads: bool = False) -> Tensor: + """Function to gather a tensor from several distributed processes. + + Args: + tensor: tensor to all-gather. + group: unused. + sync_grads: flag that allows users to synchronize gradients for the all-gather operation. + Return: + A tensor of shape (world_size, ...) + + """ + if not self._launched: + return tensor + if not isinstance(tensor, Tensor): + raise NotImplementedError( + f"`{type(self).__name__}.all_gather` is only implemented for tensors. Given {tensor}" + ) + if tensor.dim() == 0: + tensor = tensor.unsqueeze(0) + original_device = tensor.device + tensor = tensor.to(self.root_device) + + import torch_xla.core.functions as xf + import torch_xla.core.xla_model as xm + + tensor = xf.all_gather(tensor) if sync_grads else xm.all_gather(tensor) + tensor = tensor.to(original_device) + return tensor + + @override + def all_reduce( + self, output: Union[Tensor, Any], group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = None + ) -> Tensor: + if not isinstance(output, Tensor): + output = torch.tensor(output, device=self.root_device) + + invalid_reduce_op = isinstance(reduce_op, ReduceOp) and reduce_op != ReduceOp.SUM + invalid_reduce_op_str = isinstance(reduce_op, str) and reduce_op.lower() not in ("sum", "mean", "avg") + if invalid_reduce_op or invalid_reduce_op_str: + raise ValueError( + "Currently, the XLAStrategy only supports `sum`, `mean`, `avg` for the reduce operation, got:" + f" {reduce_op}" + ) + import torch_xla.core.xla_model as xm + + output = xm.mesh_reduce("reduce", output, sum) + + if isinstance(reduce_op, str) and reduce_op.lower() in ("avg", "mean"): + output = output / self.world_size + + return output + + @override + def barrier(self, name: Optional[str] = None, *args: Any, **kwargs: Any) -> None: + if not self._launched: + return + import torch_xla.core.xla_model as xm + + if name is None: + # `None` is not supported: "TypeError: _xla_rendezvous(): incompatible function arguments" + name = "" + xm.rendezvous(name) + + @override + def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast: + if not self._launched: + return obj + + import torch_xla.core.xla_model as xm + + is_tensor = isinstance(obj, Tensor) + if is_tensor: + if obj.dim() == 0: + obj = obj.unsqueeze(0) + original_device = obj.device + # XLA distributed requires that the data is on the XLA device + obj = obj.to(self.root_device) + else: + # support for arbitrary pickle-ables + buffer = io.BytesIO() + torch.save(obj, buffer) + obj = torch.tensor( # type: ignore[assignment] + bytearray(buffer.getbuffer()), device=self.root_device, dtype=torch.float + ) + + obj = [obj] + xm.collective_broadcast(obj, root_ordinal=src) + obj = obj[0] + + if not is_tensor: + # this will preserve the dtype and device of any tensors + buffer = io.BytesIO(obj.cpu().byte().numpy()) + obj = torch.load(buffer) + else: + obj = obj.to(original_device) + + return obj + + @override + def save_checkpoint( + self, + path: _PATH, + state: dict[str, Union[Module, Optimizer, Any]], + storage_options: Optional[Any] = None, + filter: Optional[dict[str, Callable[[str, Any], bool]]] = None, + ) -> None: + """Save model, optimizer, and other state as a checkpoint file. + + Args: + path: A path to where the file(s) should be saved + state: A dictionary with contents to be saved. If the dict contains modules or optimizers, their + state-dict will be retrieved and converted automatically. + storage_options: Additional options for the ``CheckpointIO`` plugin + filter: An optional dictionary of the same format as ``state`` mapping keys to callables that return a + boolean indicating whether the given parameter should be saved (``True``) or filtered out (``False``). + + """ + import torch_xla.core.xla_model as xm + + # sync any pending lazy tensors on all ranks before saving to prevent potential collective hangs + xm.mark_step() + # save on global rank zero only + super().save_checkpoint(path, state, storage_options=storage_options, filter=filter) + + @classmethod + @override + def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: + strategy_registry.register("xla", cls, description=cls.__name__) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/xla_fsdp.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/xla_fsdp.py new file mode 100644 index 0000000000000000000000000000000000000000..9103be127a60f0075a19db0711a39218ecc0f298 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/strategies/xla_fsdp.py @@ -0,0 +1,687 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import io +from contextlib import AbstractContextManager, ExitStack, nullcontext +from functools import partial +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union + +import torch +from torch import Tensor +from torch.nn import Module +from torch.optim import Optimizer +from torch.utils.data import DataLoader +from typing_extensions import override + +from lightning_fabric.accelerators import Accelerator +from lightning_fabric.accelerators.xla import _XLA_AVAILABLE +from lightning_fabric.plugins import CheckpointIO, Precision, XLAPrecision +from lightning_fabric.plugins.environments import XLAEnvironment +from lightning_fabric.plugins.io.xla import XLACheckpointIO +from lightning_fabric.strategies import ParallelStrategy, _StrategyRegistry +from lightning_fabric.strategies.fsdp import _apply_filter +from lightning_fabric.strategies.launchers.xla import _XLALauncher +from lightning_fabric.strategies.strategy import ( + TBroadcast, + _BackwardSyncControl, + _Sharded, + _validate_keys_for_strict_loading, +) +from lightning_fabric.utilities.cloud_io import get_filesystem +from lightning_fabric.utilities.init import _EmptyInit +from lightning_fabric.utilities.rank_zero import rank_zero_only, rank_zero_warn +from lightning_fabric.utilities.types import _PATH, Optimizable, ReduceOp + +if TYPE_CHECKING: + from torch.optim.lr_scheduler import _LRScheduler + from torch_xla.distributed.parallel_loader import MpDeviceLoader + +_POLICY_SET = set[type[Module]] +_POLICY = Union[_POLICY_SET, Callable[[Module, bool, int], bool]] + + +class XLAFSDPStrategy(ParallelStrategy, _Sharded): + r"""Strategy for training multiple XLA devices using the + :func:`torch_xla.distributed.xla_fully_sharded_data_parallel.XlaFullyShardedDataParallel` method. + + .. warning:: This is an :ref:`experimental ` feature. + + For more information check out https://github.com/pytorch/xla/blob/v2.5.0/docs/fsdp.md + + Args: + auto_wrap_policy: Same as ``auto_wrap_policy`` parameter in + :class:`torch_xla.distributed.fsdp.XlaFullyShardedDataParallel`. + For convenience, this also accepts a set of the layer classes to wrap. + activation_checkpointing_policy: Used when selecting the modules for + which you want to enable activation checkpointing. Enabling this can free up a significant amount of memory + at the cost of speed since activations in these layers need to be recomputed during backpropagation. + This accepts a set of the layer classes to wrap. + + state_dict_type: The format in which the state of the model and optimizers gets saved into the checkpoint. + + - ``"full"``: The full weights and optimizer states get assembled on rank 0 and saved to a single file. + - ``"sharded"``: Each rank saves its shard of weights and optimizer states to a file. The checkpoint is + a folder with files for each shard in the host. Note that TPU VM multihost does not have a shared + filesystem. + + sequential_save: With this enabled, individual ranks consecutively save their state dictionary shards, reducing + peak system RAM usage, although it elongates the saving process. + \**kwargs: See available parameters in :class:`torch_xla.distributed.fsdp.XlaFullyShardedDataParallel`. + + """ + + def __init__( + self, + accelerator: Optional[Accelerator] = None, + parallel_devices: Optional[list[torch.device]] = None, + checkpoint_io: Optional[XLACheckpointIO] = None, + precision: Optional[XLAPrecision] = None, + auto_wrap_policy: Optional[_POLICY] = None, + activation_checkpointing_policy: Optional[_POLICY_SET] = None, + state_dict_type: Literal["full", "sharded"] = "sharded", + sequential_save: bool = False, + **kwargs: Any, + ) -> None: + if not _XLA_AVAILABLE: + raise ModuleNotFoundError(str(_XLA_AVAILABLE)) + super().__init__( + accelerator=accelerator, + parallel_devices=parallel_devices, + cluster_environment=XLAEnvironment(), + checkpoint_io=checkpoint_io, + precision=precision, + ) + self._backward_sync_control = _XLAFSDPBackwardSyncControl() + + self._auto_wrap_policy = auto_wrap_policy + self._activation_checkpointing_policy = activation_checkpointing_policy + self._fsdp_kwargs = kwargs + self._state_dict_type = state_dict_type + self._sequential_save = sequential_save + self._launched = False + + @property + @override + def root_device(self) -> torch.device: + if not self._launched: + raise RuntimeError("Accessing the XLA device before processes have spawned is not allowed.") + import torch_xla.core.xla_model as xm + + return xm.xla_device() + + @property + def num_processes(self) -> int: + return len(self.parallel_devices) if self.parallel_devices is not None else 0 + + @property + @override + def checkpoint_io(self) -> XLACheckpointIO: + plugin = self._checkpoint_io + if plugin is not None: + assert isinstance(plugin, XLACheckpointIO) + return plugin + return XLACheckpointIO() + + @checkpoint_io.setter + @override + def checkpoint_io(self, io: Optional[CheckpointIO]) -> None: + if io is not None and not isinstance(io, XLACheckpointIO): + raise TypeError(f"The XLA strategy can only work with the `XLACheckpointIO` plugin, found {io}") + self._checkpoint_io = io + + @property + @override + def precision(self) -> XLAPrecision: + plugin = self._precision + if plugin is not None: + assert isinstance(plugin, XLAPrecision) + return plugin + return XLAPrecision("32-true") + + @precision.setter + @override + def precision(self, precision: Optional[Precision]) -> None: + if precision is not None and not isinstance(precision, XLAPrecision): + raise TypeError(f"The XLA FSDP strategy can only work with the `XLAPrecision` plugin, found {precision}") + self._precision = precision + + @property + @override + def global_rank(self) -> int: + return super().global_rank if self._launched else 0 + + @property + @override + def local_rank(self) -> int: + return super().local_rank if self._launched else 0 + + @property + @override + def node_rank(self) -> int: + return super().node_rank if self._launched else 0 + + @property + @override + def world_size(self) -> int: + return super().world_size if self._launched else 1 + + @override + def _configure_launcher(self) -> None: + self._launcher = _XLALauncher(self) + + @override + def setup_environment(self) -> None: + assert self.parallel_devices is not None + if len(self.parallel_devices) == 1: + # spawning only 1 device with PjRT is not supported: + # https://github.com/Lightning-AI/pytorch-lightning/pull/17408#discussion_r1170671732 + raise NotImplementedError( + f"The {type(self).__name__} does not support running on a single device with the PjRT runtime." + " Try using all devices or the `SingleDeviceXLAStrategy` strategy" + ) + + self._launched = True + rank_zero_only.rank = self.global_rank + super().setup_environment() + + @override + def setup_module_and_optimizers( + self, module: Module, optimizers: list[Optimizer], scheduler: Optional["_LRScheduler"] = None + ) -> tuple[Module, list[Optimizer], Optional["_LRScheduler"]]: + """Returns NotImplementedError since for XLAFSDP optimizer setup must happen after module setup.""" + raise NotImplementedError( + f"The `{type(self).__name__}` does not support the joint setup of module and optimizer(s)." + " Please do it in this order: Create the model, call `setup_module`, create the optimizer," + " call `setup_optimizer`." + ) + + @override + def setup_module(self, module: Module) -> Module: + from torch_xla.distributed.fsdp import XlaFullyShardedDataParallel as XLAFSDP + + kwargs = self._parse_fsdp_kwargs() + if any(isinstance(mod, XLAFSDP) for mod in module.modules()) and "auto_wrap_policy" in kwargs: + rank_zero_warn( + "A XLAFSDP `auto_wrap_policy` is set, but at least one submodule is already wrapped." + " The policy will be ignored." + ) + del kwargs["auto_wrap_policy"] + # XLA FSDP requires that the root is wrapped, even if submodules are already wrapped + if not isinstance(module, XLAFSDP): + module = XLAFSDP(module=module, **kwargs) + return module + + @override + def module_to_device(self, module: Module) -> None: + pass + + def module_init_context(self, empty_init: Optional[bool] = None) -> AbstractContextManager: + precision_init_ctx = self.precision.module_init_context() + module_sharded_ctx = self.module_sharded_context() + stack = ExitStack() + stack.enter_context(_EmptyInit(enabled=bool(empty_init))) + stack.enter_context(precision_init_ctx) + stack.enter_context(module_sharded_ctx) + return stack + + @override + def module_sharded_context(self) -> AbstractContextManager: + return nullcontext() + + @override + def process_dataloader(self, dataloader: DataLoader) -> "MpDeviceLoader": + from torch_xla.distributed.parallel_loader import MpDeviceLoader + + if isinstance(dataloader, MpDeviceLoader): + # dataloader is already wrapped by MpDeviceLoader + return dataloader + + dataloader = MpDeviceLoader(dataloader, self.root_device) + # Mimic interface to torch.utils.data.DataLoader + dataloader.dataset = dataloader._loader.dataset + dataloader.batch_sampler = getattr(dataloader._loader, "batch_sampler", None) + return dataloader + + @override + def setup_optimizer(self, optimizer: Optimizer) -> Optimizer: + """Set up an optimizer for a model wrapped with XLAFSDP. + + This setup method doesn't modify the optimizer or wrap the optimizer. The only thing it currently does is verify + that the optimizer was created after the model was wrapped with :meth:`setup_module` with a reference to the + flattened parameters. + + """ + if any(getattr(p, "_is_sharded", False) for group in optimizer.param_groups for p in group["params"]): + return optimizer + raise ValueError( + "The optimizer does not seem to reference any XLAFSDP parameters. HINT: Make sure to create the optimizer" + " after setting up the model." + ) + + @override + def optimizer_step(self, optimizer: Optimizable, **kwargs: Any) -> Any: + """Overrides default tpu optimizer_step since FSDP should not call `torch_xla.core.xla_model.optimizer_step`. + Performs the actual optimizer step. + + Args: + optimizer: the optimizer performing the step + **kwargs: Any extra arguments to ``optimizer.step`` + + """ + loss = optimizer.step(**kwargs) + import torch_xla.core.xla_model as xm + + xm.mark_step() + return loss + + @override + def clip_gradients_norm( + self, + module: Module, + optimizer: Optimizer, + max_norm: Union[float, int], + norm_type: Union[float, int] = 2.0, + error_if_nonfinite: bool = True, + ) -> Tensor: + """Clip gradients by norm.""" + self.precision.unscale_gradients(optimizer) + assert callable(module.clip_grad_norm_) + return module.clip_grad_norm_(max_norm=max_norm, norm_type=norm_type) + + @override + def clip_gradients_value(self, module: Module, optimizer: Optimizer, clip_val: Union[float, int]) -> None: + """Clip gradients by value.""" + raise NotImplementedError( + "XLA's FSDP strategy does not support to clip gradients by value." + " Consider clipping by norm instead or choose another strategy!" + ) + + @override + def all_gather(self, tensor: Tensor, group: Optional[Any] = None, sync_grads: bool = False) -> Tensor: + """Function to gather a tensor from several distributed processes. + + Args: + tensor: tensor to all-gather. + group: unused. + sync_grads: flag that allows users to synchronize gradients for the all-gather operation. + Return: + A tensor of shape (world_size, ...) + + """ + if not self._launched: + return tensor + if not isinstance(tensor, Tensor): + raise NotImplementedError( + f"`{type(self).__name__}.all_gather` is only implemented for tensors. Given {tensor}" + ) + if tensor.dim() == 0: + tensor = tensor.unsqueeze(0) + original_device = tensor.device + tensor = tensor.to(self.root_device) + + import torch_xla.core.functions as xf + import torch_xla.core.xla_model as xm + + tensor = xf.all_gather(tensor) if sync_grads else xm.all_gather(tensor) + tensor = tensor.to(original_device) + return tensor + + @override + def all_reduce( + self, output: Union[Tensor, Any], group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = None + ) -> Tensor: + if not isinstance(output, Tensor): + output = torch.tensor(output, device=self.root_device) + + invalid_reduce_op = isinstance(reduce_op, ReduceOp) and reduce_op != ReduceOp.SUM + invalid_reduce_op_str = isinstance(reduce_op, str) and reduce_op.lower() not in ("sum", "mean", "avg") + if invalid_reduce_op or invalid_reduce_op_str: + raise ValueError( + "Currently, the XLAFSDPStrategy only supports `sum`, `mean`, `avg` for the reduce operation, got:" + f" {reduce_op}" + ) + import torch_xla.core.xla_model as xm + + output = xm.mesh_reduce("reduce", output, sum) + + if isinstance(reduce_op, str) and reduce_op.lower() in ("avg", "mean"): + output = output / self.world_size + + return output + + @override + def barrier(self, name: Optional[str] = None, *args: Any, **kwargs: Any) -> None: + if not self._launched: + return + import torch_xla.core.xla_model as xm + + if name is None: + # `None` is not supported: "TypeError: _xla_rendezvous(): incompatible function arguments" + name = "" + xm.rendezvous(name) + + @override + def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast: + if not self._launched: + return obj + + import torch_xla.core.xla_model as xm + + is_tensor = isinstance(obj, Tensor) + if is_tensor: + if obj.dim() == 0: + obj = obj.unsqueeze(0) + original_device = obj.device + # XLA distributed requires that the data is on the XLA device + obj = obj.to(self.root_device) + else: + # support for arbitrary pickle-ables + buffer = io.BytesIO() + torch.save(obj, buffer) + obj = torch.tensor( # type: ignore[assignment] + bytearray(buffer.getbuffer()), device=self.root_device, dtype=torch.float + ) + + obj = [obj] + xm.collective_broadcast(obj, root_ordinal=src) + obj = obj[0] + + if not is_tensor: + # this will preserve the dtype and device of any tensors + buffer = io.BytesIO(obj.cpu().byte().numpy()) + obj = torch.load(buffer) + else: + obj = obj.to(original_device) + + return obj + + @override + def save_checkpoint( + self, + path: _PATH, + state: dict[str, Union[Module, Optimizer, Any]], + storage_options: Optional[Any] = None, + filter: Optional[dict[str, Callable[[str, Any], bool]]] = None, + ) -> None: + """Save model, optimizer, and other state in the provided checkpoint directory. + + If the user specifies sharded checkpointing, the directory will contain one file per process, with model- and + optimizer shards stored per file. If the user specifies full checkpointing, the directory will contain a + consolidated checkpoint combining all of the sharded checkpoints. + + """ + # broadcast the path from rank 0 to ensure all the states are saved in a common path + path = Path(self.broadcast(path)) + if path.is_dir() and any(path.iterdir()): + raise FileExistsError(f"The checkpoint directory already exists and is not empty: {path}") + from torch_xla.distributed.fsdp import XlaFullyShardedDataParallel as XLAFSDP + + modules = [module for module in state.values() if isinstance(module, XLAFSDP)] + if len(modules) == 0: + raise ValueError( + "Could not find a XLAFSDP model in the provided checkpoint state. Please provide the model as" + " part of the state like so: `save_checkpoint(..., state={'model': model, ...})`. Make sure" + " you set up the model (and optimizers if any) through the strategy before saving the checkpoint." + ) + if len(modules) > 1: + raise ValueError( + "Found multiple XLAFSDP modules in the given state. Saving checkpoints with FSDP is" + " currently limited to a single model per checkpoint. To save multiple models, call the" + " save method for each model separately with a different path." + ) + import torch_xla.core.xla_model as xm + + # ensure model parameters are updated + xm.mark_step() + + parallel_devices = self.parallel_devices + assert parallel_devices is not None + if self._sequential_save: + # each host runs this in parallel, but the ranks in the host run it sequentially + for rank in range(len(parallel_devices)): + if rank == self.local_rank: + self._save_checkpoint_shard(path, state, storage_options, filter) + self.barrier(f"wait-for-{rank}-save") + else: + self._save_checkpoint_shard(path, state, storage_options, filter) + + if self._state_dict_type == "full": + ckpt_prefix = str(path / "checkpoint") + ckpt_suffix = "_rank-*-of-*.pth" + if len(parallel_devices) != self.world_size: # multihost + raise OSError( + "Multihost setups do not have a shared filesystem, so the checkpoint shards cannot be consolidated" + " into a single checkpoint after saving them. Please switch to" + " `XLAFSDPStrategy(state_dict_type='sharded')`. TIP: You can consolidate them manually by getting" + " them together into a single directory and running `python -m" + f" torch_xla.distributed.fsdp.consolidate_sharded_ckpts --ckpt_prefix {ckpt_prefix!r} --ckpt_suffix" + f" {ckpt_suffix!r} --save_path 'path/to/consolidated.ckpt'`." + ) + + from torch_xla.distributed.fsdp import consolidate_sharded_model_checkpoints + + self.barrier("before_ckpt_consolidation") + if self.is_global_zero: + save_path = path.parent / "consolidated.ckpt" + # save consolidated checkpoint separate to the shards + consolidate_sharded_model_checkpoints(ckpt_prefix, ckpt_suffix, str(save_path)) + # remove the shards directory + self.checkpoint_io.remove_checkpoint(path) + # mv the consolidated checkpoint where the user would expect it + get_filesystem(save_path).mv(str(save_path), str(path)) + self.barrier("after_ckpt_consolidation") + + def _save_checkpoint_shard( + self, + path: Path, + state: dict[str, Union[Module, Optimizer, Any]], + storage_options: Optional[Any], + filter: Optional[dict[str, Callable[[str, Any], bool]]], + ) -> None: + from torch_xla.distributed.fsdp import XlaFullyShardedDataParallel as XLAFSDP + + converted_state: dict[str, Any] = {} + for key, obj in state.items(): + # convert the state + if isinstance(obj, Module) and isinstance(obj, XLAFSDP): + converted = obj.state_dict() + # add shard_metadata to state + converted_state["shard_metadata"] = obj.get_shard_metadata() + elif isinstance(obj, Optimizer): + converted = obj.state_dict() + else: + converted = obj + _apply_filter(key, filter or {}, converted, converted_state) + + self.checkpoint_io.save_checkpoint( + converted_state, + path / f"checkpoint_rank-{self.global_rank:08d}-of-{self.world_size:08d}.pth", + storage_options=storage_options, + ) + + @override + def load_checkpoint( + self, + path: _PATH, + state: Optional[Union[Module, Optimizer, dict[str, Union[Module, Optimizer, Any]]]] = None, + strict: bool = True, + weights_only: Optional[bool] = None, + ) -> dict[str, Any]: + """Given a folder, load the contents from a checkpoint and restore the state of the given objects. + + The strategy currently only supports saving and loading sharded checkpoints which are stored in form of a + directory of multiple files rather than a single file. + + """ + if not state: + raise ValueError( + f"Got `XLAFSDPStrategy.load_checkpoint(..., state={state!r})` but a state with at least " + " a model instance to reload is required. Pass it in like so:" + " `FSDPStrategy.load_checkpoint(..., state={'model': model, ...})`" + ) + + # broadcast the path from rank 0 to ensure all the states are loaded from a common path + path = Path(self.broadcast(path)) + + if isinstance(state, (Module, Optimizer)): + raise NotImplementedError( + "Loading a single module or optimizer object from a checkpoint" + " is not supported yet with the XLAFSDP strategy." + ) + + from torch_xla.distributed.fsdp import XlaFullyShardedDataParallel as XLAFSDP + + modules = {key: module for key, module in state.items() if isinstance(module, XLAFSDP)} + optimizers = {key: optim for key, optim in state.items() if isinstance(optim, Optimizer)} + if self._state_dict_type == "sharded": + file = path / f"checkpoint_rank-{self.global_rank:08d}-of-{self.world_size:08d}.pth" + if not file.is_file(): + raise ValueError( + f"The path {str(file)!r} does not point to valid sharded checkpoints. Make sure the path points to" + " a directory with XLAFSDP checkpoint shards." + ) + if len(modules) == 0: + raise ValueError( + "Could not find a XLAFSDP model in the provided checkpoint state. Please provide the model as" + " part of the state like so: `load_checkpoint(..., state={'model': model, ...})`. Make sure" + " you set up the model (and optimizers if any) through the strategy before loading the checkpoint." + ) + if len(modules) > 1: + raise ValueError( + "Found multiple XLAFSDP modules in the given state. Loading checkpoints with FSDP is" + " currently limited to a single model per checkpoint. To load multiple models, call the" + " load method for each model separately with a different path." + ) + + _, module = list(modules.items())[0] + sharded_ckpt = torch.load(file) + + module.load_state_dict(sharded_ckpt["model"], strict=strict) + for opt_key, opt in optimizers.items(): + opt.load_state_dict(sharded_ckpt[opt_key]) + + # Load anything leftover from sharded_ckpt + loaded_metadata_keys = sharded_ckpt.keys() - modules.keys() - optimizers.keys() + requested_metadata_keys = state.keys() - modules.keys() - optimizers.keys() + _validate_keys_for_strict_loading(requested_metadata_keys, loaded_metadata_keys, strict=strict) + for key in requested_metadata_keys: + if key in loaded_metadata_keys: + state[key] = sharded_ckpt[key] + loaded_metadata_keys.remove(key) + + metadata = {} + if len(loaded_metadata_keys): + for key in loaded_metadata_keys: + metadata[key] = sharded_ckpt[key] + + # remove "shard_metadata" that is loaded in + if "shard_metadata" in metadata: + metadata.pop("shard_metadata") + + return metadata + + if self._state_dict_type == "full": + if not path.is_file(): + raise ValueError( + f"The path {str(path)!r} does not point to a valid full checkpoint. Make sure the path points to a" + " directory with a full XLAFSDP checkpoint." + ) + if len(optimizers) > 0 or len(state.keys() - modules.keys() - optimizers.keys()) > 0: + rank_zero_warn( + "Loading a full checkpoint will only load the full model." + " The optimizer and any additional metadata are not included." + ) + if len(modules) > 0: + raise ValueError( + "Found a XLAFSDP model in the provided checkpoint state." + " Please provide the model without any XLAFSDP wrapper." + ) + if "model" not in state or not isinstance(model := state["model"], torch.nn.Module): + raise NotImplementedError("XLAFSDP only supports a single model instance with 'model' as the key.") + full_ckpt = torch.load(path, weights_only=weights_only) + model.load_state_dict(full_ckpt.pop("model"), strict=strict) + return full_ckpt + + raise ValueError(f"Unknown state_dict_type: {self._state_dict_type}") + + @classmethod + @override + def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: + strategy_registry.register("xla_fsdp", cls, description=cls.__name__) + + def _parse_fsdp_kwargs(self) -> dict: + # this needs to be delayed because `self.precision` isn't available at init + kwargs = self._fsdp_kwargs.copy() + precision = self.precision + if isinstance(precision, XLAPrecision): + # the `compute_dtype` will be passed to the `auto_wrapper_callable` automatically, so we don't need to pass + # it when creating it + kwargs.setdefault("compute_dtype", precision._desired_dtype) + kwargs = _auto_wrap_policy_kwargs(self._auto_wrap_policy, kwargs) + return _activation_checkpointing_kwargs(self._activation_checkpointing_policy, kwargs) + + +def _auto_wrap_policy_kwargs(policy: Optional["_POLICY"], kwargs: dict) -> dict: + if policy is None: + return kwargs + if isinstance(policy, set): + from torch_xla.distributed.fsdp.wrap import transformer_auto_wrap_policy + + # this is not transformer specific despite the name + policy = partial(transformer_auto_wrap_policy, transformer_layer_cls=policy) + kwargs["auto_wrap_policy"] = policy + return kwargs + + +def _activation_checkpointing_auto_wrapper(policy: _POLICY_SET, module: Module, *args: Any, **kwargs: Any) -> Module: + from torch_xla.distributed.fsdp import XlaFullyShardedDataParallel as XLAFSDP + from torch_xla.distributed.fsdp import checkpoint_module + + module = checkpoint_module(module) if isinstance(module, tuple(policy)) else module + return XLAFSDP(module, *args, **kwargs) + + +def _activation_checkpointing_kwargs(policy: Optional[_POLICY_SET], kwargs: dict) -> dict: + if not policy: + return kwargs + if "auto_wrapper_callable" in kwargs: + raise ValueError( + "You cannot set both `auto_wrapper_callable` and `activation_checkpointing_policy`. Choose one" + ) + if not isinstance(policy, set): + raise TypeError( + f"`activation_checkpointing_policy` must be a set, found {policy}. You can try defining and" + " passing `auto_wrapper_callable` instead." + ) + auto_wrapper_callable = partial(_activation_checkpointing_auto_wrapper, policy) + kwargs["auto_wrapper_callable"] = auto_wrapper_callable + return kwargs + + +class _XLAFSDPBackwardSyncControl(_BackwardSyncControl): + @override + def no_backward_sync(self, module: Module, enabled: bool) -> AbstractContextManager: + """Blocks gradient synchronization inside the :class:`~torch_xla.distributed.fsdp.XlaFullyShardedDataParallel` + wrapper.""" + if not enabled: + return nullcontext() + from torch_xla.distributed.fsdp import XlaFullyShardedDataParallel as XLAFSDP + + if not isinstance(module, XLAFSDP): + raise TypeError( + "Blocking backward sync is only possible if the module passed to" + f" `{self.__class__.__name__}.no_backward_sync` is wrapped in `XlaFullyShardedDataParallel`." + f" Got: {module.__class__.__name__}." + ) + return module.no_sync() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..862465c776166e42f01427117d90817dac627bb9 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__init__.py @@ -0,0 +1,43 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""General utilities.""" + +from lightning_fabric.utilities.apply_func import move_data_to_device +from lightning_fabric.utilities.data import AttributeDict, suggested_max_num_workers +from lightning_fabric.utilities.distributed import is_shared_filesystem +from lightning_fabric.utilities.enums import LightningEnum +from lightning_fabric.utilities.rank_zero import ( + rank_zero_deprecation, + rank_zero_info, + rank_zero_only, + rank_zero_warn, +) +from lightning_fabric.utilities.throughput import Throughput, ThroughputMonitor, measure_flops +from lightning_fabric.utilities.warnings import disable_possible_user_warnings + +__all__ = [ + "disable_possible_user_warnings", + "is_shared_filesystem", + "LightningEnum", + "measure_flops", + "move_data_to_device", + "rank_zero_deprecation", + "rank_zero_info", + "rank_zero_only", + "rank_zero_warn", + "suggested_max_num_workers", + "AttributeDict", + "Throughput", + "ThroughputMonitor", +] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99f76f350c03597d0a2cb61dd8e8a0e57aa04d50 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/apply_func.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/apply_func.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffe889f29e6c176066684f3761b6c61fad68ed2a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/apply_func.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/cloud_io.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/cloud_io.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cc7d0232a4a88760b13b17dc80848a934184123 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/cloud_io.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/consolidate_checkpoint.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/consolidate_checkpoint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2c028ab6bd9d15a6fe3576e2d6563c5859e9189 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/consolidate_checkpoint.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/data.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae48ba5fa0bcf0a202fc06e844548efad088d396 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/data.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/device_dtype_mixin.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/device_dtype_mixin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8da594e597462bb2a52004b5b4525bc60b5fcb5 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/device_dtype_mixin.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/device_parser.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/device_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d77a0ae2313af0e97ea511e27a5bd3279134f595 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/device_parser.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/distributed.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/distributed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10edda52cb6b8632ff55df05bea2696844802741 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/distributed.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/enums.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/enums.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b33f53c346ad26a8672dd0ef937308cb8513551 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/enums.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/exceptions.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bc5433ae175487086eae3fbda584ebd2329d19c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/exceptions.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/imports.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/imports.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fecb82b758dea1dbc0003b8d170744ed0570d0a1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/imports.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/init.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/init.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38a9301f1edfc7bdc03768fe6d0f1a28809c1346 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/init.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/load.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/load.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05b20171514baa100135d4e4ce997cebccb16177 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/load.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/logger.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f37faee4a4ca4b7eb512cf465cba23dcf15cd301 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/logger.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/optimizer.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/optimizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e083e67e3f44fcaa994c92502c17dada77256cc Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/optimizer.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/rank_zero.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/rank_zero.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06fb4cd484d472c2f174c73a508046a0b99bb195 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/rank_zero.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/registry.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..065d76878af6b21de5e33af18f2370a07c06e578 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/registry.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/seed.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/seed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2df8e4951f648416f067151679d200834a8ce3e7 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/seed.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/spike.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/spike.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de65111e283abb2c84d40c47b67875b5391247bf Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/spike.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/throughput.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/throughput.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b2af0f73b0c6b42f17c2769183274d1debbedc5 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/throughput.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/types.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..550fa0daf5aff49d84522d834b4c06ff51848d82 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/types.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/warnings.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/warnings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efe361f95ec5d73c3a313f2d682db5b6ca8438de Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/__pycache__/warnings.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/apply_func.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/apply_func.py new file mode 100644 index 0000000000000000000000000000000000000000..a2537367a43e41d3b77e2e5dfa60d50ab146d19f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/apply_func.py @@ -0,0 +1,136 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Utilities used for collections.""" + +from abc import ABC +from functools import partial +from typing import TYPE_CHECKING, Any, Callable, Union + +import torch +from lightning_utilities.core.apply_func import apply_to_collection +from torch import Tensor + +from lightning_fabric.utilities.imports import _NUMPY_AVAILABLE +from lightning_fabric.utilities.types import _DEVICE + +if TYPE_CHECKING: + import numpy as np + +_BLOCKING_DEVICE_TYPES = ("cpu", "mps") + + +def _from_numpy(value: "np.ndarray", device: _DEVICE) -> Tensor: + return torch.from_numpy(value).to(device) + + +CONVERSION_DTYPES: list[tuple[Any, Callable[[Any, Any], Tensor]]] = [ + # bool -> uint8 as bool -> torch.bool triggers RuntimeError: Unsupported data type for NCCL process group + (bool, partial(torch.tensor, dtype=torch.uint8)), + (int, partial(torch.tensor, dtype=torch.int)), + (float, partial(torch.tensor, dtype=torch.float)), +] + +if _NUMPY_AVAILABLE: + import numpy as np + + CONVERSION_DTYPES.append((np.ndarray, _from_numpy)) + + +class _TransferableDataType(ABC): + """A custom type for data that can be moved to a torch device via ``.to(...)``. + + Example: + + >>> isinstance(dict, _TransferableDataType) + False + >>> isinstance(torch.rand(2, 3), _TransferableDataType) + True + >>> class CustomObject: + ... def __init__(self): + ... self.x = torch.rand(2, 2) + ... def to(self, device): + ... self.x = self.x.to(device) + ... return self + >>> isinstance(CustomObject(), _TransferableDataType) + True + + """ + + @classmethod + def __subclasshook__(cls, subclass: Any) -> Union[bool, Any]: + if cls is _TransferableDataType: + to = getattr(subclass, "to", None) + return callable(to) + return NotImplemented + + +def move_data_to_device(batch: Any, device: _DEVICE) -> Any: + """Transfers a collection of data to the given device. Any object that defines a method ``to(device)`` will be + moved and all other objects in the collection will be left untouched. + + Args: + batch: A tensor or collection of tensors or anything that has a method ``.to(...)``. + See :func:`apply_to_collection` for a list of supported collection types. + device: The device to which the data should be moved + + Return: + the same collection but with all contained tensors residing on the new device. + + See Also: + - :meth:`torch.Tensor.to` + - :class:`torch.device` + + """ + if isinstance(device, str): + device = torch.device(device) + + def batch_to(data: Any) -> Any: + kwargs = {} + # Don't issue non-blocking transfers to CPU + # Same with MPS due to a race condition bug: https://github.com/pytorch/pytorch/issues/83015 + if isinstance(data, Tensor) and isinstance(device, torch.device) and device.type not in _BLOCKING_DEVICE_TYPES: + kwargs["non_blocking"] = True + data_output = data.to(device, **kwargs) + if data_output is not None: + return data_output + # user wrongly implemented the `_TransferableDataType` and forgot to return `self`. + return data + + return apply_to_collection(batch, dtype=_TransferableDataType, function=batch_to) + + +def convert_to_tensors(data: Any, device: _DEVICE) -> Any: + # convert non-tensors + for src_dtype, conversion_func in CONVERSION_DTYPES: + data = apply_to_collection(data, src_dtype, conversion_func, device=device) + return move_data_to_device(data, device) + + +def convert_tensors_to_scalars(data: Any) -> Any: + """Recursively walk through a collection and convert single-item tensors to scalar values. + + Raises: + ValueError: + If tensors inside ``metrics`` contains multiple elements, hence preventing conversion to a scalar. + + """ + + def to_item(value: Tensor) -> Union[int, float, bool]: + if value.numel() != 1: + raise ValueError( + f"The metric `{value}` does not contain a single element, thus it cannot be converted to a scalar." + ) + return value.item() + + return apply_to_collection(data, Tensor, to_item) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/cloud_io.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/cloud_io.py new file mode 100644 index 0000000000000000000000000000000000000000..ba7c507df8e04ac832d885667ecc8be355b7fc78 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/cloud_io.py @@ -0,0 +1,178 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Utilities related to data saving/loading.""" + +import errno +import io +import logging +from pathlib import Path +from typing import IO, Any, Optional, Union + +import fsspec +import fsspec.utils +import torch +from fsspec.core import url_to_fs +from fsspec.implementations.local import AbstractFileSystem +from lightning_utilities.core.imports import module_available + +from lightning_fabric.utilities.types import _MAP_LOCATION_TYPE, _PATH + +log = logging.getLogger(__name__) + + +def _load( + path_or_url: Union[IO, _PATH], + map_location: _MAP_LOCATION_TYPE = None, + weights_only: Optional[bool] = None, +) -> Any: + """Loads a checkpoint. + + Args: + path_or_url: Path or URL of the checkpoint. + map_location: a function, ``torch.device``, string or a dict specifying how to remap storage locations. + weights_only: If ``True``, restricts loading to ``state_dicts`` of plain ``torch.Tensor`` and other primitive + types. If loading a checkpoint from a trusted source that contains an ``nn.Module``, use + ``weights_only=False``. If loading checkpoint from an untrusted source, we recommend using + ``weights_only=True``. For more information, please refer to the + `PyTorch Developer Notes on Serialization Semantics `_. + + """ + if not isinstance(path_or_url, (str, Path)): + # any sort of BytesIO or similar + return torch.load( + path_or_url, + map_location=map_location, # type: ignore[arg-type] # upstream annotation is not correct + weights_only=weights_only, + ) + if str(path_or_url).startswith("http"): + if weights_only is None: + weights_only = False + log.debug( + f"Defaulting to `weights_only=False` for remote checkpoint: {path_or_url}." + f" If loading a checkpoint from an untrustted source, we recommend using `weights_only=True`." + ) + + return torch.hub.load_state_dict_from_url( + str(path_or_url), + map_location=map_location, # type: ignore[arg-type] + weights_only=weights_only, + ) + fs = get_filesystem(path_or_url) + with fs.open(path_or_url, "rb") as f: + return torch.load( + f, + map_location=map_location, # type: ignore[arg-type] + weights_only=weights_only, + ) + + +def get_filesystem(path: _PATH, **kwargs: Any) -> AbstractFileSystem: + fs, _ = url_to_fs(str(path), **kwargs) + return fs + + +def _atomic_save(checkpoint: dict[str, Any], filepath: _PATH) -> None: + """Saves a checkpoint atomically, avoiding the creation of incomplete checkpoints. + + Args: + checkpoint: The object to save. + Built to be used with the ``dump_checkpoint`` method, but can deal with anything which ``torch.save`` + accepts. + filepath: The path to which the checkpoint will be saved. + This points to the file that the checkpoint will be stored in. + + """ + bytesbuffer = io.BytesIO() + log.debug(f"Saving checkpoint: {filepath}") + torch.save(checkpoint, bytesbuffer) + + try: + # We use a transaction here to avoid file corruption if the save gets interrupted + fs, urlpath = fsspec.core.url_to_fs(str(filepath)) + with fs.transaction: + is_azure = False + if module_available("adlfs"): + from adlfs import AzureBlobFileSystem + + is_azure = isinstance(fs, AzureBlobFileSystem) + + if _is_object_storage(fs) and not is_azure: + # Use fs.pipe() for S3/GCS where it triggers parallel multipart uploads, + # giving 4-5x throughput improvement for checkpoints >= 500 MB. + # Azure is excluded because adlfs stages blocks sequentially, making pipe() slower. + fs.pipe(urlpath, bytesbuffer.getvalue()) + else: + with fs.open(urlpath, "wb") as f: + f.write(bytesbuffer.getvalue()) + except PermissionError as e: + if isinstance(e.__context__, OSError) and getattr(e.__context__, "errno", None) == errno.EXDEV: + raise RuntimeError( + 'Upgrade fsspec to enable cross-device local checkpoints: pip install "fsspec[http]>=2025.5.0"', + ) from e + + +def _is_object_storage(fs: AbstractFileSystem) -> bool: + if module_available("adlfs"): + from adlfs import AzureBlobFileSystem + + if isinstance(fs, AzureBlobFileSystem): + return True + + if module_available("gcsfs"): + from gcsfs import GCSFileSystem + + if isinstance(fs, GCSFileSystem): + return True + + if module_available("s3fs"): + from s3fs import S3FileSystem + + if isinstance(fs, S3FileSystem): + return True + + return False + + +def _is_dir(fs: AbstractFileSystem, path: Union[str, Path], strict: bool = False) -> bool: + """Check if a path is directory-like. + + This function determines if a given path is considered directory-like, taking into account the behavior + specific to object storage platforms. For other filesystems, it behaves similarly to the standard `fs.isdir` + method. + + Args: + fs: The filesystem to check the path against. + path: The path or URL to be checked. + strict: A flag specific to Object Storage platforms. If set to ``False``, any non-existing path is considered + as a valid directory-like path. In such cases, the directory (and any non-existing parent directories) + will be created on the fly. Defaults to False. + + """ + # Object storage fsspec's are inconsistent with other file systems because they do not have real directories, + # see for instance https://gcsfs.readthedocs.io/en/latest/api.html?highlight=makedirs#gcsfs.core.GCSFileSystem.mkdir + # In particular, `fs.makedirs` is a no-op so we use `strict=False` to consider any path as valid, except if the + # path already exists but is a file + if _is_object_storage(fs): + if strict: + return fs.isdir(path) + + # Check if the path is not already taken by a file. If not, it is considered a valid directory-like path + # because the directory (and all non-existing parent directories) will be created on the fly. + return not fs.isfile(path) + + return fs.isdir(path) + + +def _is_local_file_protocol(path: _PATH) -> bool: + return fsspec.utils.get_protocol(str(path)) == "file" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/consolidate_checkpoint.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/consolidate_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..846ab3808fb8457e892f2426a56fea54c3a72149 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/consolidate_checkpoint.py @@ -0,0 +1,80 @@ +import logging +import sys +from argparse import ArgumentParser, Namespace +from pathlib import Path + +import torch + +from lightning_fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_3 +from lightning_fabric.utilities.load import _METADATA_FILENAME, _load_distributed_checkpoint + +_log = logging.getLogger(__name__) + + +def _parse_cli_args() -> Namespace: + parser = ArgumentParser( + description=( + "Converts a distributed/sharded checkpoint into a single file that can be loaded with `torch.load()`." + " Only supports FSDP sharded checkpoints at the moment." + ), + ) + parser.add_argument( + "checkpoint_folder", + type=str, + help=( + "Path to a checkpoint folder, containing the sharded checkpoint files saved using the" + " `torch.distributed.checkpoint` API." + ), + ) + parser.add_argument( + "--output_file", + type=str, + help=( + "Path to the file where the converted checkpoint should be saved. The file should not already exist." + " If no path is provided, the file will be saved next to the input checkpoint folder with the same name" + " and a '.consolidated' suffix." + ), + ) + return parser.parse_args() + + +def _process_cli_args(args: Namespace) -> Namespace: + if not _TORCH_GREATER_EQUAL_2_3: + _log.error("Processing distributed checkpoints requires PyTorch >= 2.3.") + sys.exit(1) + + checkpoint_folder = Path(args.checkpoint_folder) + if not checkpoint_folder.exists(): + _log.error(f"The provided checkpoint folder does not exist: {checkpoint_folder}") + sys.exit(1) + if not checkpoint_folder.is_dir(): + _log.error( + f"The provided checkpoint path must be a folder, containing the checkpoint shards: {checkpoint_folder}" + ) + sys.exit(1) + if not (checkpoint_folder / _METADATA_FILENAME).is_file(): + _log.error( + "Only FSDP-sharded checkpoints saved with Lightning are supported for consolidation. The provided folder" + f" is not in that format: {checkpoint_folder}" + ) + sys.exit(1) + + if args.output_file is None: + output_file = checkpoint_folder.with_suffix(checkpoint_folder.suffix + ".consolidated") + else: + output_file = Path(args.output_file) + if output_file.exists(): + _log.error( + "The path for the converted checkpoint already exists. Choose a different path by providing" + f" `--output_file` or move/delete the file first: {output_file}" + ) + sys.exit(1) + + return Namespace(checkpoint_folder=checkpoint_folder, output_file=output_file) + + +if __name__ == "__main__": + args = _parse_cli_args() + config = _process_cli_args(args) + checkpoint = _load_distributed_checkpoint(config.checkpoint_folder) + torch.save(checkpoint, config.output_file) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/data.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/data.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f94a25c4d0cad05b56629bd86d0e5306ab80f6 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/data.py @@ -0,0 +1,506 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import functools +import inspect +import os +from collections import OrderedDict +from collections.abc import Generator, Iterable, Sized +from contextlib import contextmanager +from functools import partial +from typing import Any, Callable, Optional, Union + +from lightning_utilities.core.inheritance import get_all_subclasses +from torch.utils.data import BatchSampler, DataLoader, IterableDataset, Sampler +from typing_extensions import TypeGuard + +from lightning_fabric.utilities.enums import LightningEnum +from lightning_fabric.utilities.exceptions import MisconfigurationException +from lightning_fabric.utilities.rank_zero import rank_zero_warn +from lightning_fabric.utilities.seed import pl_worker_init_function + + +class _WrapAttrTag(LightningEnum): + SET = "set" + DEL = "del" + + def __call__(self, *args: Any) -> None: + fn: Union[Callable[[object, str], None], Callable[[object, str, Any], None]] + fn = setattr if self == self.SET else delattr + return fn(*args) + + +def has_iterable_dataset(dataloader: object) -> bool: + return hasattr(dataloader, "dataset") and isinstance(dataloader.dataset, IterableDataset) + + +def sized_len(dataloader: object) -> Optional[int]: + """Try to get the length of an object, return ``None`` otherwise.""" + try: + # try getting the length + length = len(dataloader) # type: ignore [arg-type] + except (TypeError, NotImplementedError): + length = None + return length + + +def has_len(dataloader: object) -> TypeGuard[Sized]: + """Checks if a given object has ``__len__`` method implemented.""" + length = sized_len(dataloader) + if length == 0: + rank_zero_warn( + f"`{dataloader.__class__.__name__}` returned 0 length. Please make sure this was your intention." + ) + if length is not None and has_iterable_dataset(dataloader): + rank_zero_warn( + "Your `IterableDataset` has `__len__` defined." + " In combination with multi-process data loading (when num_workers > 1)," + " `__len__` could be inaccurate if each worker is not configured independently" + " to avoid having duplicate data." + ) + return length is not None + + +def _update_dataloader(dataloader: DataLoader, sampler: Union[Sampler, Iterable]) -> DataLoader: + dl_args, dl_kwargs = _get_dataloader_init_args_and_kwargs(dataloader, sampler) + return _reinstantiate_wrapped_cls(dataloader, *dl_args, **dl_kwargs) + + +def _get_dataloader_init_args_and_kwargs( + dataloader: DataLoader, + sampler: Union[Sampler, Iterable], +) -> tuple[tuple[Any], dict[str, Any]]: + if not isinstance(dataloader, DataLoader): + raise ValueError(f"The dataloader {dataloader} needs to subclass `torch.utils.data.DataLoader`") + + was_wrapped = hasattr(dataloader, "__pl_saved_args") + if was_wrapped: + dl_args = dataloader.__pl_saved_args + dl_kwargs = dataloader.__pl_saved_kwargs + arg_names = dataloader.__pl_saved_arg_names + original_dataset = dataloader.__dataset # we have this saved from _wrap_init + else: + # get the dataloader instance attributes + attrs = {k: v for k, v in vars(dataloader).items() if not k.startswith("_")} + # We cannot be 100% sure the class sets dataset argument. Let's set it to None to be safe + # and hope we can get it from the instance attributes + original_dataset = None + # not part of `vars` + attrs["multiprocessing_context"] = dataloader.multiprocessing_context + arg_names = () + + # get the dataloader instance `__init__` parameters + params = dict(inspect.signature(dataloader.__init__).parameters) # type: ignore[misc] + has_variadic_kwargs = any(p.kind is p.VAR_KEYWORD for p in params.values()) + if has_variadic_kwargs: + # if the signature takes **kwargs, assume they will be passed down with `super().__init__(**kwargs)` + + if was_wrapped: + # if the dataloader was wrapped in a hook, only take arguments with default values + # and assume user passes their kwargs correctly + params.update({ + k: v for k, v in inspect.signature(DataLoader.__init__).parameters.items() if v.default is not v.empty + }) + else: + params.update(inspect.signature(DataLoader.__init__).parameters) + params.pop("self", None) + + if not was_wrapped: + # keep only the params whose default is different to the current attr value + non_defaults = {name for name, p in params.items() if name in attrs and p.default is not attrs[name]} + + # add `dataset` as it might have been replaced with `*args` + non_defaults.add("dataset") + # kwargs to re-construct the dataloader + dl_kwargs = {k: v for k, v in attrs.items() if k in non_defaults} + dl_args = () + + dataset = dl_kwargs.get("dataset", original_dataset) + if isinstance(dataset, IterableDataset): + dl_kwargs["batch_sampler"] = None + dl_kwargs["sampler"] = None + else: + dl_kwargs.update(_dataloader_init_kwargs_resolve_sampler(dataloader, sampler)) + + required_args = { + p.name + for p in params.values() + if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) + and p.default is p.empty + and p.name not in dl_kwargs + and p.name not in arg_names + } + # the dataloader has required args which we could not extract from the existing attributes + if required_args: + sorted_required_args = sorted(required_args) + dataloader_cls_name = dataloader.__class__.__name__ + missing_args_message = ", ".join(f"`self.{arg_name}`" for arg_name in sorted_required_args) + raise MisconfigurationException( + f"Trying to inject custom `Sampler` into the `{dataloader_cls_name}` instance. " + "This would fail as some of the `__init__` arguments are not available as instance attributes. " + f"The missing attributes are {sorted_required_args}. If you instantiate your `{dataloader_cls_name}` " + "inside a `*_dataloader` hook of your module, we will do this for you." + f" Otherwise, define {missing_args_message} inside your `__init__`." + ) + + if not has_variadic_kwargs: + # the dataloader signature does not allow keyword arguments that need to be passed + missing_kwargs = (set(dl_kwargs) | set(arg_names)) - params.keys() + if missing_kwargs: + sorted_missing_kwargs = sorted(missing_kwargs) + dataloader_cls_name = dataloader.__class__.__name__ + raise TypeError( + f"Trying to inject parameters into the `{dataloader_cls_name}` instance. " + "This would fail as it doesn't expose all its attributes in the `__init__` signature. " + f"The missing arguments are {sorted_missing_kwargs}. HINT: If you wrote the `{dataloader_cls_name}` " + "class, add the `__init__` arguments or allow passing `**kwargs`" + ) + + return dl_args, dl_kwargs + + +def _dataloader_init_kwargs_resolve_sampler( + dataloader: DataLoader, + sampler: Union[Sampler, Iterable], +) -> dict[str, Any]: + """This function is used to handle the sampler, batch_sampler arguments associated within a DataLoader for its re- + instantiation.""" + batch_sampler = getattr(dataloader, "batch_sampler") + + if batch_sampler is not None and type(batch_sampler) is not BatchSampler: + batch_sampler_cls = type(batch_sampler) + if hasattr(batch_sampler, "__pl_saved_args"): + # This is a PyTorch `BatchSampler` subclass for which we captured the init args + args = batch_sampler.__pl_saved_args + kwargs = batch_sampler.__pl_saved_kwargs + default_kwargs = batch_sampler.__pl_saved_default_kwargs + arg_names = batch_sampler.__pl_saved_arg_names + + success, args, kwargs = _replace_value_in_saved_args( + "sampler", sampler, args, kwargs, default_kwargs, arg_names + ) + if not success: + raise TypeError( + "Trying to inject a modified sampler into the batch sampler; however, it seems the class " + f"`{batch_sampler_cls.__qualname__}` does not have an argument called `sampler.` To mitigate " + "this, expose an argument `sampler` in the `__init__` method of your custom class." + ) + + batch_sampler = _reinstantiate_wrapped_cls(batch_sampler, *args, **kwargs) + elif hasattr(batch_sampler, "batch_size") and hasattr(batch_sampler, "drop_last"): + # This is a sampler for which we could not capture the init args, but it kinda looks like a batch sampler + # even if it does not inherit from PyTorch's interface. + try: + batch_sampler = batch_sampler_cls( + sampler, + batch_size=batch_sampler.batch_size, + drop_last=batch_sampler.drop_last, + ) + except TypeError as ex: + import re + + match = re.match(r".*__init__\(\) (got multiple values)|(missing \d required)", str(ex)) + if not match: + # an unexpected `TypeError`, continue failure + raise + + # There could either be too few or too many arguments. Customizing the message based on this doesn't + # make much sense since our MisconfigurationException is going to be raised from the original one. + raise TypeError( + " Lightning can't inject a (distributed) sampler into your batch sampler, because it doesn't" + " subclass PyTorch's `BatchSampler`. To mitigate this, either follow the API of `BatchSampler`" + " or set`.setup_dataloaders(..., use_distributed_sampler=False)`. If you choose the latter, you" + " will be responsible for handling the distributed sampling within your batch sampler." + ) from ex + else: + # The sampler is not a PyTorch `BatchSampler`, we don't know how to inject a custom sampler + raise TypeError( + " Lightning can't inject a (distributed) sampler into your batch sampler, because it doesn't" + " subclass PyTorch's `BatchSampler`. To mitigate this, either follow the API of `BatchSampler`" + " or set`.setup_dataloaders(..., use_distributed_sampler=False)`. If you choose the latter, you" + " will be responsible for handling the distributed sampling within your batch sampler." + ) + + return { + "sampler": None, + "shuffle": False, + "batch_sampler": batch_sampler, + "batch_size": 1, + "drop_last": False, + } + + return {"sampler": sampler, "shuffle": False, "batch_sampler": None} + + +def _auto_add_worker_init_fn(dataloader: object, rank: int) -> None: + if not hasattr(dataloader, "worker_init_fn"): + return + if int(os.environ.get("PL_SEED_WORKERS", 0)) and dataloader.worker_init_fn is None: + dataloader.worker_init_fn = partial(pl_worker_init_function, rank=rank) + + +def _reinstantiate_wrapped_cls(orig_object: Any, *args: Any, explicit_cls: Optional[type] = None, **kwargs: Any) -> Any: + constructor = type(orig_object) if explicit_cls is None else explicit_cls + + try: + result = constructor(*args, **kwargs) + except TypeError as ex: + # improve exception message due to an incorrect implementation of the `DataLoader` where multiple subclass + # `__init__` arguments map to one `DataLoader.__init__` argument + import re + + match = re.match(r".*__init__\(\) got multiple values .* '(\w+)'", str(ex)) + if not match: + # an unexpected `TypeError`, continue failure + raise + argument = match.groups()[0] + message = ( + f"The {constructor.__name__} implementation has an error where more than one `__init__` argument" + f" can be passed to its parent's `{argument}=...` `__init__` argument. This is likely caused by allowing" + f" passing both a custom argument that will map to the `{argument}` argument as well as `**kwargs`." + f" `kwargs` should be filtered to make sure they don't contain the `{argument}` key." + " This argument was automatically passed to your object by PyTorch Lightning." + ) + raise MisconfigurationException(message) from ex + + attrs_record = getattr(orig_object, "__pl_attrs_record", []) + for args, fn in attrs_record: + fn(result, *args) + + return result + + +def _wrap_init_method(init: Callable, store_explicit_arg: Optional[str] = None) -> Callable: + """Wraps the ``__init__`` method of classes (currently :class:`~torch.utils.data.DataLoader` and + :class:`~torch.utils.data.BatchSampler`) in order to enable re-instantiation of custom subclasses.""" + + @functools.wraps(init) + def wrapper(obj: Any, *args: Any, **kwargs: Any) -> None: + # We need to inspect `init`, as inspecting `obj.__init__` + # can lead to inspecting the wrong function with multiple inheritance + old_inside_init = getattr(obj, "__pl_inside_init", False) + object.__setattr__(obj, "__pl_inside_init", True) + params = inspect.signature(init).parameters + + parameters_defaults = OrderedDict( + (param.name, param.default) + for param in params.values() + if param.name != "self" and param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD) + ) + + param_names = tuple(parameters_defaults)[: len(args)] + + default_kwargs = { + name: value + for name, value in parameters_defaults.items() + if name not in kwargs and name not in param_names and value != inspect.Parameter.empty + } + + if not hasattr(obj, "__pl_saved_args"): + object.__setattr__(obj, "__pl_saved_args", args) + object.__setattr__(obj, "__pl_saved_kwargs", kwargs) + object.__setattr__(obj, "__pl_saved_arg_names", param_names) + object.__setattr__(obj, "__pl_saved_default_kwargs", default_kwargs) + + # We want to use the latest possible value for explicit argument (i.e. ideally what gets passed to base class) + # so that we can be sure, that it will not get changed anymore. + # That is why we are setting this in every `__init__` + if store_explicit_arg is not None: + if store_explicit_arg in param_names: + object.__setattr__(obj, f"__{store_explicit_arg}", args[param_names.index(store_explicit_arg)]) + elif store_explicit_arg in kwargs: + object.__setattr__(obj, f"__{store_explicit_arg}", kwargs[store_explicit_arg]) + + init(obj, *args, **kwargs) + object.__setattr__(obj, "__pl_inside_init", old_inside_init) + + return wrapper + + +def _wrap_attr_method(method: Callable, tag: _WrapAttrTag) -> Callable: + """Wraps the ``__setattr__`` or ``__delattr__`` method of classes (currently :class:`~torch.utils.data.DataLoader` + and :class:`~torch.utils.data.BatchSampler`) in order to enable re- instantiation of custom subclasses.""" + + @functools.wraps(method) + def wrapper(obj: Any, *args: Any) -> None: + # First, let's find out if we're the first in inheritance chain calling the patched method. + name, *_ = args + prev_call_name, prev_call_method = getattr(obj, "__pl_current_call", (None, "method")) + first_call = not (prev_call_name == name and prev_call_method == tag) + + # Then mark the current called method + object.__setattr__(obj, "__pl_current_call", (name, tag)) + + # call original method + method(obj, *args) + if first_call and not getattr(obj, "__pl_inside_init", True): + # and save the value it was called with to the internal list, + # if we're outside of __init__ and the original call did not fail and we're the first call + attrs_record = getattr(obj, "__pl_attrs_record", []) + attrs_record.append((args, tag)) + object.__setattr__(obj, "__pl_attrs_record", attrs_record) + object.__setattr__(obj, "__pl_current_call", (prev_call_name, prev_call_method)) + + return wrapper + + +@contextmanager +def _replace_dunder_methods(base_cls: type, store_explicit_arg: Optional[str] = None) -> Generator[None, None, None]: + """This context manager is used to add support for re-instantiation of custom (subclasses) of `base_cls`. + + It patches the ``__init__``, ``__setattr__`` and ``__delattr__`` methods. + + """ + classes = get_all_subclasses(base_cls) | {base_cls} + for cls in classes: + # Check that __init__ belongs to the class + # https://stackoverflow.com/a/5253424 + if "__init__" in cls.__dict__: + cls.__old__init__ = cls.__init__ # type: ignore[misc] + cls.__init__ = _wrap_init_method(cls.__init__, store_explicit_arg) # type: ignore[misc] + + # we want at least one setattr/delattr in the chain to be patched and it can happen, that none of the subclasses + # implement `__setattr__`/`__delattr__`. Therefore, we are always patching the `base_cls` + for patch_fn_name, tag in (("__setattr__", _WrapAttrTag.SET), ("__delattr__", _WrapAttrTag.DEL)): + if patch_fn_name in cls.__dict__ or cls is base_cls: + saved_name = f"__old{patch_fn_name}" + setattr(cls, saved_name, getattr(cls, patch_fn_name)) + setattr(cls, patch_fn_name, _wrap_attr_method(getattr(cls, patch_fn_name), tag)) + yield + for cls in classes: + for patched_name in ("__setattr__", "__delattr__", "__init__"): + # Check that __old__{init,setattr,delattr} belongs to the class + # https://stackoverflow.com/a/5253424 + if f"__old{patched_name}" in cls.__dict__: + setattr(cls, patched_name, getattr(cls, f"__old{patched_name}")) + delattr(cls, f"__old{patched_name}") + + +def _replace_value_in_saved_args( + replace_key: str, + replace_value: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any], + default_kwargs: dict[str, Any], + arg_names: tuple[str, ...], +) -> tuple[bool, tuple[Any, ...], dict[str, Any]]: + """Tries to replace an argument value in a saved list of args and kwargs. + + Returns a tuple indicating success of the operation and modified saved args and kwargs + + """ + + if replace_key in arg_names: + replace_index = arg_names.index(replace_key) + args = args[:replace_index] + (replace_value,) + args[replace_index + 1 :] + return True, args, kwargs + if replace_key in kwargs or replace_key in default_kwargs: + kwargs[replace_key] = replace_value + return True, args, kwargs + + return False, args, kwargs + + +def _set_sampler_epoch(dataloader: object, epoch: int) -> None: + """Calls the ``set_epoch`` method on either the sampler of the given dataloader. + + Every PyTorch dataloader has either a sampler or a batch sampler. If the sampler is wrapped by a + :class:`~torch.utils.data.distributed.DistributedSampler`, ``set_epoch`` must be called at the beginning + of every epoch to ensure shuffling applies a new ordering. This has no effect if shuffling is off. + + """ + # cannot use a set because samplers might be unhashable: use a dict based on the id to drop duplicates + objects: dict[int, Any] = {} + # check dataloader.sampler + if (sampler := getattr(dataloader, "sampler", None)) is not None: + objects[id(sampler)] = sampler + # check dataloader.batch_sampler.sampler + if (batch_sampler := getattr(dataloader, "batch_sampler", None)) is not None and ( + sampler := getattr(batch_sampler, "sampler", None) + ) is not None: + objects[id(sampler)] = sampler + for obj in objects.values(): + set_epoch = getattr(obj, "set_epoch", None) + if callable(set_epoch): + set_epoch(epoch) + + +def suggested_max_num_workers(local_world_size: int) -> int: + """Suggests an upper bound of ``num_workers`` to use in a PyTorch :class:`~torch.utils.data.DataLoader` based on + the number of CPU cores available on the system and the number of distributed processes in the current machine. + + Args: + local_world_size: The number of distributed processes running on the current machine. Set this to the number + of devices configured in Fabric/Trainer. + + """ + if local_world_size < 1: + raise ValueError(f"`local_world_size` should be >= 1, got {local_world_size}.") + cpu_count = _num_cpus_available() + return max(1, cpu_count // local_world_size - 1) # -1 to leave some resources for main process + + +def _num_cpus_available() -> int: + if hasattr(os, "sched_getaffinity"): + return len(os.sched_getaffinity(0)) + + cpu_count = os.cpu_count() + return 1 if cpu_count is None else cpu_count + + +class AttributeDict(dict): + """A container to store state variables of your program. + + This is a drop-in replacement for a Python dictionary, with the additional functionality to access and modify keys + through attribute lookup for convenience. + + Use this to define the state of your program, then pass it to + :meth:`~lightning_fabric.fabric.Fabric.save` and :meth:`~lightning_fabric.fabric.Fabric.load`. + + Example: + >>> import torch + >>> model = torch.nn.Linear(2, 2) + >>> state = AttributeDict(model=model, iter_num=0) + >>> state.model + Linear(in_features=2, out_features=2, bias=True) + >>> state.iter_num += 1 + >>> state.iter_num + 1 + >>> state + "iter_num": 1 + "model": Linear(in_features=2, out_features=2, bias=True) + + """ + + def __getattr__(self, key: str) -> Any: + try: + return self[key] + except KeyError as e: + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{key}'") from e + + def __setattr__(self, key: str, val: Any) -> None: + self[key] = val + + def __delattr__(self, item: str) -> None: + if item not in self: + raise KeyError(item) + del self[item] + + def __repr__(self) -> str: + if not len(self): + return "" + max_key_length = max(len(str(k)) for k in self) + tmp_name = "{:" + str(max_key_length + 3) + "s} {}" + rows = [tmp_name.format(f'"{n}":', self[n]) for n in sorted(self.keys())] + return "\n".join(rows) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/device_dtype_mixin.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/device_dtype_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..c07b3d55ae8958b9b04b92f5c0b74f1ec1570fdc --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/device_dtype_mixin.py @@ -0,0 +1,124 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Optional, Union + +import torch +from torch.nn import Module +from typing_extensions import Self, override + +from lightning_fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_3 + + +class _DeviceDtypeModuleMixin(Module): + __jit_unused_properties__: list[str] = ["device", "dtype"] + + def __init__(self) -> None: + super().__init__() + self._dtype: Union[str, torch.dtype] = torch.get_default_dtype() + # Workarounds from the original pytorch issue: + # https://github.com/pytorch/pytorch/issues/115333#issuecomment-1848449687 + self._device = torch.get_default_device() if _TORCH_GREATER_EQUAL_2_3 else torch.empty(0).device + + @property + def dtype(self) -> Union[str, torch.dtype]: + return self._dtype + + @dtype.setter + def dtype(self, new_dtype: Union[str, torch.dtype]) -> None: + # necessary to avoid infinite recursion + raise RuntimeError("Cannot set the dtype explicitly. Please use module.to(new_dtype).") + + @property + def device(self) -> torch.device: + device = self._device + + # make this more explicit to always include the index + if device.type == "cuda" and device.index is None: + return torch.device(f"cuda:{torch.cuda.current_device()}") + + return device + + @override + def to(self, *args: Any, **kwargs: Any) -> Self: + """See :meth:`torch.nn.Module.to`.""" + # this converts `str` device to `torch.device` + device, dtype = torch._C._nn._parse_to(*args, **kwargs)[:2] + _update_properties(self, device=device, dtype=dtype) + return super().to(*args, **kwargs) + + @override + def cuda(self, device: Optional[Union[torch.device, int]] = None) -> Self: + """Moves all model parameters and buffers to the GPU. This also makes associated parameters and buffers + different objects. So it should be called before constructing optimizer if the module will live on GPU while + being optimized. + + Arguments: + device: If specified, all parameters will be copied to that device. If `None`, the current CUDA device + index will be used. + + Returns: + Module: self + + """ + if device is None: + device = torch.device("cuda", torch.cuda.current_device()) + elif isinstance(device, int): + device = torch.device("cuda", index=device) + _update_properties(self, device=device) + return super().cuda(device=device) + + @override + def cpu(self) -> Self: + """See :meth:`torch.nn.Module.cpu`.""" + _update_properties(self, device=torch.device("cpu")) + return super().cpu() + + @override + def type(self, dst_type: Union[str, torch.dtype]) -> Self: + """See :meth:`torch.nn.Module.type`.""" + _update_properties(self, dtype=dst_type) + return super().type(dst_type=dst_type) + + @override + def float(self) -> Self: + """See :meth:`torch.nn.Module.float`.""" + _update_properties(self, dtype=torch.float) + return super().float() + + @override + def double(self) -> Self: + """See :meth:`torch.nn.Module.double`.""" + _update_properties(self, dtype=torch.double) + return super().double() + + @override + def half(self) -> Self: + """See :meth:`torch.nn.Module.half`.""" + _update_properties(self, dtype=torch.half) + return super().half() + + +def _update_properties( + root: torch.nn.Module, device: Optional[torch.device] = None, dtype: Optional[Union[str, torch.dtype]] = None +) -> None: + for module in root.modules(): + if not isinstance(module, _DeviceDtypeModuleMixin): + continue + # cannot use `module.to()` because we don't actually want to move the model in case there are multiple + # devices types (such as partial meta parameters) + if device is not None: + module._device = device + if dtype is not None: + module._dtype = dtype diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/device_parser.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/device_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..3f933bfde59f10e03268a7463d29d16a5c881d70 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/device_parser.py @@ -0,0 +1,221 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections.abc import MutableSequence +from typing import Optional, Union + +import torch + +from lightning_fabric.utilities.exceptions import MisconfigurationException +from lightning_fabric.utilities.types import _DEVICE + + +def _determine_root_gpu_device(gpus: list[_DEVICE]) -> Optional[_DEVICE]: + """ + Args: + gpus: Non-empty list of ints representing which GPUs to use + + Returns: + Designated root GPU device id + + Raises: + TypeError: + If ``gpus`` is not a list + AssertionError: + If GPU list is empty + """ + if gpus is None: + return None + + if not isinstance(gpus, list): + raise TypeError("GPUs should be a list") + + assert len(gpus) > 0, "GPUs should be a non-empty list" + + # set root gpu + return gpus[0] + + +def _parse_gpu_ids( + gpus: Optional[Union[int, str, list[int]]], + include_cuda: bool = False, + include_mps: bool = False, +) -> Optional[list[int]]: + """Parses the GPU IDs given in the format as accepted by the :class:`~pytorch_lightning.trainer.trainer.Trainer`. + + Args: + gpus: An int -1 or string '-1' indicate that all available GPUs should be used. + A list of unique ints or a string containing a list of comma separated unique integers + indicates specific GPUs to use. + An int of 0 means that no GPUs should be used. + Any int N > 0 indicates that GPUs [0..N) should be used. + include_cuda: A boolean value indicating whether to include CUDA devices for GPU parsing. + include_mps: A boolean value indicating whether to include MPS devices for GPU parsing. + + Returns: + A list of GPUs to be used or ``None`` if no GPUs were requested + + Raises: + MisconfigurationException: + If no GPUs are available but the value of gpus variable indicates request for GPUs + + .. note:: + ``include_cuda`` and ``include_mps`` default to ``False`` so that you only + have to specify which device type to use and all other devices are not disabled. + + """ + # Check that gpus param is None, Int, String or Sequence of Ints + _check_data_type(gpus) + + # Handle the case when no GPUs are requested + if gpus is None or (isinstance(gpus, int) and gpus == 0) or str(gpus).strip() in ("0", "[]"): + return None + + # We know the user requested GPUs therefore if some of the + # requested GPUs are not available an exception is thrown. + gpus = _normalize_parse_gpu_string_input(gpus) + gpus = _normalize_parse_gpu_input_to_list(gpus, include_cuda=include_cuda, include_mps=include_mps) + if not gpus: + raise MisconfigurationException("GPUs requested but none are available.") + + if ( + torch.distributed.is_available() + and torch.distributed.is_torchelastic_launched() + and len(gpus) != 1 + and len(_get_all_available_gpus(include_cuda=include_cuda, include_mps=include_mps)) == 1 + ): + # Omit sanity check on torchelastic because by default it shows one visible GPU per process + return gpus + + # Check that GPUs are unique. Duplicate GPUs are not supported by the backend. + _check_unique(gpus) + + return _sanitize_gpu_ids(gpus, include_cuda=include_cuda, include_mps=include_mps) + + +def _normalize_parse_gpu_string_input(s: Union[int, str, list[int]]) -> Union[int, list[int]]: + if not isinstance(s, str): + return s + if s == "-1": + return -1 + if "," in s: + return [int(x.strip()) for x in s.split(",") if len(x) > 0] + return int(s.strip()) + + +def _sanitize_gpu_ids(gpus: list[int], include_cuda: bool = False, include_mps: bool = False) -> list[int]: + """Checks that each of the GPUs in the list is actually available. Raises a MisconfigurationException if any of the + GPUs is not available. + + Args: + gpus: List of ints corresponding to GPU indices + + Returns: + Unmodified gpus variable + + Raises: + MisconfigurationException: + If machine has fewer available GPUs than requested. + + """ + if sum((include_cuda, include_mps)) == 0: + raise ValueError("At least one gpu type should be specified!") + all_available_gpus = _get_all_available_gpus(include_cuda=include_cuda, include_mps=include_mps) + for gpu in gpus: + if gpu not in all_available_gpus: + raise MisconfigurationException( + f"You requested gpu: {gpus}\n But your machine only has: {all_available_gpus}" + ) + return gpus + + +def _normalize_parse_gpu_input_to_list( + gpus: Union[int, list[int], tuple[int, ...]], include_cuda: bool, include_mps: bool +) -> Optional[list[int]]: + assert gpus is not None + if isinstance(gpus, (MutableSequence, tuple)): + return list(gpus) + + # must be an int + if not gpus: # gpus==0 + return None + if gpus == -1: + return _get_all_available_gpus(include_cuda=include_cuda, include_mps=include_mps) + + return list(range(gpus)) + + +def _get_all_available_gpus(include_cuda: bool = False, include_mps: bool = False) -> list[int]: + """ + Returns: + A list of all available GPUs + """ + from lightning_fabric.accelerators.cuda import _get_all_visible_cuda_devices + from lightning_fabric.accelerators.mps import _get_all_available_mps_gpus + + cuda_gpus = _get_all_visible_cuda_devices() if include_cuda else [] + mps_gpus = _get_all_available_mps_gpus() if include_mps else [] + return cuda_gpus + mps_gpus + + +def _check_unique(device_ids: list[int]) -> None: + """Checks that the device_ids are unique. + + Args: + device_ids: List of ints corresponding to GPUs indices + + Raises: + MisconfigurationException: + If ``device_ids`` of GPUs aren't unique + + """ + if len(device_ids) != len(set(device_ids)): + raise MisconfigurationException("Device ID's (GPU) must be unique.") + + +def _check_data_type(device_ids: object) -> None: + """Checks that the device_ids argument is one of the following: int, string, or sequence of integers. + + Args: + device_ids: gpus/tpu_cores parameter as passed to the Trainer + + Raises: + TypeError: + If ``device_ids`` of GPU/TPUs aren't ``int``, ``str`` or sequence of ``int``` + + """ + msg = "Device IDs (GPU/TPU) must be an int, a string, a sequence of ints, but you passed" + if device_ids is None: + raise TypeError(f"{msg} None") + if isinstance(device_ids, (MutableSequence, tuple)): + for id_ in device_ids: + id_type = type(id_) # because `isinstance(False, int)` -> True + if id_type is not int: + raise TypeError(f"{msg} a sequence of {type(id_).__name__}.") + elif type(device_ids) not in (int, str): + raise TypeError(f"{msg} {device_ids!r}.") + + +def _select_auto_accelerator() -> str: + """Choose the accelerator type (str) based on availability.""" + from lightning_fabric.accelerators.cuda import CUDAAccelerator + from lightning_fabric.accelerators.mps import MPSAccelerator + from lightning_fabric.accelerators.xla import XLAAccelerator + + if XLAAccelerator.is_available(): + return "tpu" + if MPSAccelerator.is_available(): + return "mps" + if CUDAAccelerator.is_available(): + return "cuda" + return "cpu" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/distributed.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..47120646efb78c03f5cbcf3698cfaad00184e79d --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/distributed.py @@ -0,0 +1,438 @@ +import atexit +import contextlib +import logging +import os +import signal +import time +from collections.abc import Iterable, Iterator, Sized +from contextlib import nullcontext +from datetime import timedelta +from pathlib import Path +from typing import TYPE_CHECKING, Any, Optional, Union + +import torch +import torch.nn.functional as F +from torch import Tensor +from torch.utils.data import Dataset, DistributedSampler, Sampler +from typing_extensions import Self, TypeGuard, override + +from lightning_fabric.utilities.cloud_io import _is_local_file_protocol +from lightning_fabric.utilities.data import _num_cpus_available +from lightning_fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_4 +from lightning_fabric.utilities.rank_zero import rank_zero_info +from lightning_fabric.utilities.types import _PATH, ReduceOp + +if torch.distributed.is_available(): + from torch.distributed import group +else: + + class group: # type: ignore + WORLD = None + + +if TYPE_CHECKING: + from torch.distributed._tensor import DTensor + + from lightning_fabric.plugins import ClusterEnvironment + from lightning_fabric.strategies import Strategy + + +log = logging.getLogger(__name__) + + +def is_shared_filesystem(strategy: "Strategy", path: Optional[_PATH] = None, timeout: int = 3) -> bool: + """Checks whether the filesystem under the given path is shared across all processes. + + This function should only be used in a context where distributed is initialized. + + Args: + strategy: The strategy being used, either from Fabric (``fabric.strategy``) or from Trainer + (``trainer.strategy``). + path: The path to check. Defaults to the current working directory. The user must have permissions to write + to this path or the parent folder, and the filesystem must be writable. + timeout: If any of the processes can't list the file created by rank 0 within this many seconds, the + filesystem is determined to be not shared. + + """ + # Fast path: Any non-local filesystem is considered shared (e.g., S3) + if path is not None and not _is_local_file_protocol(path): + return True + + path = Path(Path.cwd() if path is None else path).resolve() + + # Fast path: Only distributed strategies can detect shared filesystems + if not hasattr(strategy, "world_size") or strategy.world_size == 1: + return True + + # Fast path: If the path is not the same on all ranks we know it's not a shared filesystem + rank_zero_path = strategy.broadcast(path) + if not strategy.reduce_boolean_decision(rank_zero_path == path, all=True): + return False + + if not strategy.reduce_boolean_decision(path.exists(), all=True): + raise FileNotFoundError( + f"Unable to determine if the path belongs to a shared filesystem. The path does not exist: {path}" + ) + + path = path.parent if path.is_file() else path + check_file = path / ".lightning_shared_fs_check" + check_file.unlink(missing_ok=True) + + strategy.barrier() + if strategy.is_global_zero: + # Rank 0 creates the file + check_file.touch() + found = True + else: + # All other ranks will wait until they find the file or timeout + start = time.perf_counter() + found = False + while not found and (time.perf_counter() - start) < timeout: + found = check_file.exists() + strategy.barrier() + + all_found = strategy.reduce_boolean_decision(found, all=True) + + with contextlib.suppress(OSError): # handle race condition on deletion + check_file.unlink() + + return all_found + + +def _gather_all_tensors(result: Tensor, group: Optional[Any] = None) -> list[Tensor]: + """Function to gather all tensors from several DDP processes onto a list that is broadcasted to all processes. + + Works on tensors that have the same number of dimensions, but where each dimension may differ. In this case + tensors are padded, gathered and then trimmed to secure equal workload for all processes. + + Args: + result: The value to sync + group: The process group to gather results from. Defaults to all processes (world) + + Return: + gathered_result: List with size equal to the process group where + gathered_result[i] corresponds to result tensor from process i + + """ + if group is None: + group = torch.distributed.group.WORLD + + # Convert tensors to contiguous format + result = result.contiguous() + + world_size = torch.distributed.get_world_size(group) + torch.distributed.barrier(group=group) + + # If the tensor is scalar, things are easy + if result.ndim == 0: + return _simple_gather_all_tensors(result, group, world_size) + + # 1. Gather sizes of all tensors + local_size = torch.tensor(result.shape, device=result.device) + local_sizes = [torch.zeros_like(local_size) for _ in range(world_size)] + torch.distributed.all_gather(local_sizes, local_size, group=group) + max_size = torch.stack(local_sizes).max(dim=0).values + all_sizes_equal = all(all(ls == max_size) for ls in local_sizes) + + # 2. If shapes are all the same, then do a simple gather: + if all_sizes_equal: + return _simple_gather_all_tensors(result, group, world_size) + + # 3. If not, we need to pad each local tensor to maximum size, gather and then truncate + pad_dims = [] + pad_by = (max_size - local_size).detach().cpu() + for val in reversed(pad_by): + pad_dims.append(0) + pad_dims.append(val.item()) + result_padded = F.pad(result, pad_dims) + gathered_result = [torch.zeros_like(result_padded) for _ in range(world_size)] + torch.distributed.all_gather(gathered_result, result_padded, group) + for idx, item_size in enumerate(local_sizes): + slice_param = [slice(dim_size) for dim_size in item_size] + gathered_result[idx] = gathered_result[idx][slice_param] + return gathered_result + + +def _simple_gather_all_tensors(result: Tensor, group: Any, world_size: int) -> list[Tensor]: + gathered_result = [torch.zeros_like(result) for _ in range(world_size)] + torch.distributed.all_gather(gathered_result, result, group) + return gathered_result + + +def _sync_ddp_if_available( + result: Tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = None +) -> Tensor: + """Function to reduce a tensor across worker processes during distributed training. + + Args: + result: The value to sync and reduce (typically tensor or number) + group: The process group to gather results from. Defaults to all processes (world) + reduce_op: The reduction operation. Defaults to sum. + Can also be a string of 'avg', 'mean' to calculate the mean during reduction. + + Return: + reduced value + + """ + if _distributed_is_initialized(): + return _sync_ddp(result, group=group, reduce_op=reduce_op) + return result + + +def _sync_ddp(result: Tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = None) -> Tensor: + """Reduces a tensor across several distributed processes. + + This operation is performed in-place, meaning the result will be placed back into the input tensor on all processes. + + Args: + result: The value to sync and reduce (typically tensor or number) + group: The process group to gather results from. Defaults to all processes (world) + reduce_op: The reduction operation. Defaults to sum. + Can also be a string of 'avg', 'mean' to calculate the mean during reduction. + + Return: + The reduced value. + + """ + divide_by_world_size = False + group = torch.distributed.group.WORLD if group is None else group + + op: Optional[ReduceOp] + if isinstance(reduce_op, str): + reduce_op = "avg" if reduce_op == "mean" else reduce_op + if reduce_op.lower() == "avg" and torch.distributed.get_backend(group) == "gloo": + # The GLOO backend does not support the `ReduceOp.AVG` operation + op = ReduceOp.SUM # type: ignore[assignment] + divide_by_world_size = True + else: + op = getattr(ReduceOp, reduce_op.upper()) + else: + op = reduce_op + + # Sync all processes before reduction + torch.distributed.barrier(group=group) + torch.distributed.all_reduce(result, op=op, group=group, async_op=False) + world_size = torch.distributed.get_world_size(group) + + if not divide_by_world_size: + return result + # `torch.distributed.all_reduce` is in-place, so we should do the division in-place to leave the modified tensors + # with the expected value + if not torch.is_floating_point(result): + return result.copy_(result / world_size) + return result.div_(world_size) + + +def _all_gather_ddp_if_available( + tensor: Tensor, group: Optional["torch.distributed.ProcessGroup"] = None, sync_grads: bool = False +) -> Tensor: + """Function to gather a tensor from several distributed processes. + + Args: + tensor: Tensor of shape (batch, ...) + group: The process group to gather results from. Defaults to all processes (world) + sync_grads: Flag that allows users to synchronize gradients for all_gather op + + Return: + A tensor of shape (world_size, batch, ...) + + """ + if not _distributed_is_initialized(): + return tensor + + from torch.distributed.nn.functional import all_gather + + tensor = tensor.contiguous() # https://github.com/pytorch/pytorch/issues/73515 + with nullcontext() if sync_grads else torch.no_grad(): + gathered_tensors = all_gather(tensor, group) + return torch.stack(gathered_tensors) + + +def _init_dist_connection( + cluster_environment: "ClusterEnvironment", + torch_distributed_backend: str, + global_rank: Optional[int] = None, + world_size: Optional[int] = None, + **kwargs: Any, +) -> None: + """Utility function to initialize distributed connection by setting env variables and initializing the distributed + process group. + + Args: + cluster_environment: ``ClusterEnvironment`` instance + torch_distributed_backend: Backend to use (includes `nccl` and `gloo`) + global_rank: Rank of the current process + world_size: Number of processes in the group + kwargs: Kwargs for ``init_process_group`` + + Raises: + RuntimeError: + If ``torch.distributed`` is not available + + """ + if not torch.distributed.is_available(): + raise RuntimeError("torch.distributed is not available. Cannot initialize distributed process group") + if torch.distributed.is_initialized(): + log.debug("torch.distributed is already initialized. Exiting early") + return + global_rank = global_rank if global_rank is not None else cluster_environment.global_rank() + world_size = world_size if world_size is not None else cluster_environment.world_size() + os.environ["MASTER_ADDR"] = cluster_environment.main_address + os.environ["MASTER_PORT"] = str(cluster_environment.main_port) + log.info(f"Initializing distributed: GLOBAL_RANK: {global_rank}, MEMBER: {global_rank + 1}/{world_size}") + torch.distributed.init_process_group(torch_distributed_backend, rank=global_rank, world_size=world_size, **kwargs) + + if torch_distributed_backend == "nccl": + # PyTorch >= 2.4 warns about undestroyed NCCL process group, so we need to do it at program exit + atexit.register(_destroy_dist_connection) + + # On rank=0 let everyone know training is starting + rank_zero_info( + f"{'-' * 100}\n" + f"distributed_backend={torch_distributed_backend}\n" + f"All distributed processes registered. Starting with {world_size} processes\n" + f"{'-' * 100}\n" + ) + + +def _destroy_dist_connection() -> None: + # Don't allow Ctrl+C to interrupt this handler + signal.signal(signal.SIGINT, signal.SIG_IGN) + if _distributed_is_initialized(): + torch.distributed.destroy_process_group() + signal.signal(signal.SIGINT, signal.SIG_DFL) + + +def _get_default_process_group_backend_for_device(device: torch.device) -> str: + """Return corresponding distributed backend for a given device.""" + device_backend_map = torch.distributed.Backend.default_device_backend_map + if device.type in device_backend_map: + return device_backend_map[device.type] + return "gloo" + + +class _DatasetSamplerWrapper(Dataset): + """Dataset to create indexes from `Sampler` or `Iterable`""" + + def __init__(self, sampler: Union[Sampler, Iterable]) -> None: + if not isinstance(sampler, Sized): + raise TypeError( + "You seem to have configured a sampler in your DataLoader which" + " does not provide `__len__` method. The sampler was about to be" + " replaced by `DistributedSamplerWrapper` since `use_distributed_sampler`" + " is True and you are using distributed training. Either provide `__len__`" + " method in your sampler, remove it from DataLoader or set `use_distributed_sampler=False`" + " if you want to handle distributed sampling yourself." + ) + if len(sampler) == float("inf"): + raise TypeError( + "You seem to have configured a sampler in your DataLoader which" + " does not provide finite `__len__` method. The sampler was about to be" + " replaced by `DistributedSamplerWrapper` since `use_distributed_sampler`" + " is True and you are using distributed training. Either provide `__len__`" + " method in your sampler which returns a finite number, remove it from DataLoader" + " or set `use_distributed_sampler=False` if you want to handle distributed sampling yourself." + ) + self._sampler = sampler + # defer materializing an iterator until it is necessary + self._sampler_list: Optional[list[Any]] = None + + @override + def __getitem__(self, index: int) -> Any: + if self._sampler_list is None: + self._sampler_list = list(self._sampler) + return self._sampler_list[index] + + def __len__(self) -> int: + return len(self._sampler) + + def reset(self) -> None: + """Reset the sampler list in order to get new sampling.""" + self._sampler_list = list(self._sampler) + + +class DistributedSamplerWrapper(DistributedSampler): + """Wrapper over ``Sampler`` for distributed training. + + Allows you to use any sampler in distributed mode. It will be automatically used by Lightning in distributed mode if + sampler replacement is enabled. + + Note: + The purpose of this wrapper is to take care of sharding the sampler indices. It is up to the underlying + sampler to handle randomness and shuffling. The ``shuffle`` and ``seed`` arguments on this wrapper won't + have any effect. + + """ + + def __init__(self, sampler: Union[Sampler, Iterable], *args: Any, **kwargs: Any) -> None: + super().__init__(_DatasetSamplerWrapper(sampler), *args, **kwargs) + + @override + def __iter__(self) -> Iterator: + self.dataset.reset() + return (self.dataset[index] for index in super().__iter__()) + + @override + def set_epoch(self, epoch: int) -> None: + super().set_epoch(epoch) + # Forward set_epoch to the original sampler if it supports it + original_sampler = self.dataset._sampler + if hasattr(original_sampler, "set_epoch") and callable(original_sampler.set_epoch): + original_sampler.set_epoch(epoch) + + +def _suggested_max_num_threads(num_processes: int = 1) -> int: + if num_processes < 1: + raise ValueError(f"`num_processes` should be >= 1, got {num_processes}.") + return max(1, _num_cpus_available() // num_processes) + + +def _set_num_threads_if_needed(num_processes: int = 1) -> None: + if "OMP_NUM_THREADS" not in os.environ: + num_threads = _suggested_max_num_threads(num_processes) + torch.set_num_threads(num_threads) + os.environ["OMP_NUM_THREADS"] = str(num_threads) + + +def _distributed_is_initialized() -> bool: + # `is_initialized` is only defined conditionally + # https://github.com/pytorch/pytorch/blob/v2.1.0/torch/distributed/__init__.py#L25 + # this might happen to MacOS builds from source (default) or any build from source that sets `USE_DISTRIBUTED=0` + return torch.distributed.is_available() and torch.distributed.is_initialized() + + +class _InfiniteBarrier: + """A barrier with an infinite timeout. + + Creates a new process group with the GLOO backend with a very high timeout that makes the barrier effectively wait + forever. This is useful in cases where you want to execute a long-running operation on a subset of ranks that should + not be subject to the regular collective timeout. + + """ + + def __init__(self) -> None: + self.group = None + self.barrier = lambda: None + + def __call__(self) -> None: + self.barrier() + + def __enter__(self) -> Self: + if _distributed_is_initialized(): + # Create a barrier with an 'infinite' timeout (only reliably possible over the GLOO backend) + self.group = torch.distributed.new_group(backend="gloo", timeout=timedelta(days=10000)) + self.barrier = self.group.monitored_barrier + return self + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + self.barrier() + if self.group is not None: + torch.distributed.destroy_process_group(self.group) + + +def _is_dtensor(tensor: Tensor) -> TypeGuard["DTensor"]: + if _TORCH_GREATER_EQUAL_2_4: + from torch.distributed._tensor import DTensor + + return isinstance(tensor, DTensor) + return False diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/enums.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..107b9bd1a13e0abd0ecbe832c24158df72d853fa --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/enums.py @@ -0,0 +1,16 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Enumerated utilities.""" + +from lightning_utilities.core.enums import StrEnum as LightningEnum # noqa: F401 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/exceptions.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..74c9770a2c220f61de4578ff9bb976dd92a8c666 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/exceptions.py @@ -0,0 +1,17 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +class MisconfigurationException(Exception): + """Exception used to inform users of misuse with Lightning.""" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/imports.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/imports.py new file mode 100644 index 0000000000000000000000000000000000000000..ac706cc403a5deb0821ddd8e3cb3bfec6607759a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/imports.py @@ -0,0 +1,42 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""General utilities.""" + +import operator +import platform +import sys + +from lightning_utilities.core.imports import RequirementCache, compare_version + +_NUMPY_AVAILABLE = RequirementCache("numpy") + + +_IS_WINDOWS = platform.system() == "Windows" + +# There are two types of interactive mode we detect +# 1. The interactive Python shell: https://stackoverflow.com/a/64523765 +# 2. The inspection mode via `python -i`: https://stackoverflow.com/a/6879085/1162383 +_IS_INTERACTIVE = hasattr(sys, "ps1") or bool(sys.flags.interactive) + +_TORCH_GREATER_EQUAL_2_2 = compare_version("torch", operator.ge, "2.2.0") +_TORCH_GREATER_EQUAL_2_3 = compare_version("torch", operator.ge, "2.3.0") +_TORCH_EQUAL_2_4_0 = compare_version("torch", operator.eq, "2.4.0") +_TORCH_GREATER_EQUAL_2_4 = compare_version("torch", operator.ge, "2.4.0") +_TORCH_GREATER_EQUAL_2_4_1 = compare_version("torch", operator.ge, "2.4.1") +_TORCH_GREATER_EQUAL_2_5 = compare_version("torch", operator.ge, "2.5.0") +_TORCH_GREATER_EQUAL_2_6 = compare_version("torch", operator.ge, "2.6.0") +_TORCH_LESS_EQUAL_2_6 = compare_version("torch", operator.le, "2.6.0") +_TORCH_GREATER_EQUAL_2_6 = compare_version("torch", operator.ge, "2.6.0") +_TORCHMETRICS_GREATER_EQUAL_1_0_0 = compare_version("torchmetrics", operator.ge, "1.0.0") +_PYTHON_GREATER_EQUAL_3_10_0 = (sys.version_info.major, sys.version_info.minor) >= (3, 10) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/init.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/init.py new file mode 100644 index 0000000000000000000000000000000000000000..748ff637ece99b54d57b561a32afc952fc72db2f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/init.py @@ -0,0 +1,115 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import itertools +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import torch +from torch.nn import Module, Parameter +from torch.optim import Optimizer +from torch.overrides import TorchFunctionMode +from typing_extensions import override + +from lightning_fabric.utilities.rank_zero import rank_zero_warn +from lightning_fabric.utilities.types import _DEVICE + + +# From https://lernapparat.de/faster-model-init by Thomas Viehmann +class _EmptyInit(TorchFunctionMode): + """Initialize `nn.Module` with empty tensors, i.e., uninitialized memory. + + Example:: + + with _EmptyInit(): + model = BigModel() + model.load_state_dict(torch.load("checkpoint.pt")) + + """ + + def __init__(self, enabled: bool = True) -> None: + super().__init__() + self.enabled = enabled + + @override + def __torch_function__( + self, + func: Callable, + types: Sequence, + args: Sequence[Any] = (), + kwargs: Optional[dict] = None, + ) -> Any: + kwargs = kwargs or {} + if not self.enabled: + return func(*args, **kwargs) + if getattr(func, "__module__", None) == "torch.nn.init": + if "tensor" in kwargs: + return kwargs["tensor"] + return args[0] + return func(*args, **kwargs) + + +def _materialize(module: Module, device: _DEVICE) -> None: + """Materialize a module.""" + module.to_empty(device=device, recurse=False) + if not hasattr(module, "reset_parameters"): + raise TypeError( + f"Materialization requires that the `{type(module).__name__}.reset_parameters` method is implemented." + " This method is used to initialize any children parameters or buffers in this module." + ) + if callable(module.reset_parameters): + module.reset_parameters() + + +def _materialize_meta_tensors(module: Module, device: _DEVICE) -> None: + """Materialize all tensors in a given module.""" + for module in module.modules(): + if _has_meta_device_parameters_or_buffers(module, recurse=False): + _materialize(module, device) + + +def _materialize_distributed_module(module: Module, device: torch.device) -> None: + # Reference: https://github.com/pytorch/torchtitan/blob/main/docs/fsdp.md#meta-device-initialization + # TODO: Introduce `Fabric.materialize(module)` to give user control when materialization should happen + # TODO: Make `torchmetrics.Metric` compatible with the `to_empty()` + `reset_parameters()` semantics + if not _has_meta_device_parameters_or_buffers(module): + return + + module.to_empty(device=device) # has to be called on the root module + + uninitialized_modules = set() + for submodule in module.modules(): + if all(False for _ in itertools.chain(submodule.parameters(recurse=False), submodule.buffers(recurse=False))): + # module has no parameters or buffers + continue + if callable(reset_method := getattr(submodule, "reset_parameters", None)): + reset_method() + else: + uninitialized_modules.add(type(submodule).__name__) + + if uninitialized_modules: + rank_zero_warn( + "Parameter initialization incomplete. The following modules have parameters or buffers with uninitialized" + " memory because they don't define a `reset_parameters()` method for re-initialization:" + f" {', '.join(uninitialized_modules)}" + ) + + +def _has_meta_device_parameters_or_buffers(obj: Union[Module, Optimizer], recurse: bool = True) -> bool: + if isinstance(obj, Optimizer): + return any( + t.is_meta for param_group in obj.param_groups for t in param_group["params"] if isinstance(t, Parameter) + ) + if isinstance(obj, Module): + return any(t.is_meta for t in itertools.chain(obj.parameters(recurse=recurse), obj.buffers(recurse=recurse))) + raise TypeError(f"Expected `torch.nn.Module` or `torch.optim.Optimizer`, got: {type(obj).__name__}") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/load.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/load.py new file mode 100644 index 0000000000000000000000000000000000000000..f58b59200b27314e5cac8c030542a8919cab8afa --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/load.py @@ -0,0 +1,266 @@ +# Copyright 2023 MathInf GmbH +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this files from this repository except in compliance +# with the License reproduced below (also at +# http://www.apache.org/licenses/LICENSE-2.0). +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import os +import pickle +import warnings +from collections import OrderedDict +from collections.abc import Sequence +from functools import partial +from io import BytesIO +from pathlib import Path +from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union + +import torch +from lightning_utilities.core.apply_func import apply_to_collection +from torch import Tensor +from torch._C import _TensorMeta +from torch.nn import Parameter +from typing_extensions import override + +from lightning_fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_3 +from lightning_fabric.utilities.types import _PATH, _Stateful + +_METADATA_FILENAME = "meta.pt" + + +if TYPE_CHECKING: + from torch.storage import TypedStorage + + +# Modified from https://github.com/lernapparat/torchhacks by Thomas Viehmann +class _NotYetLoadedTensor: + def __init__( + self, + metatensor: Tensor, + archiveinfo: "_LazyLoadingUnpickler", + storageinfo: tuple, + rebuild_args: tuple, + ) -> None: + self.metatensor = metatensor + self.archiveinfo = archiveinfo + self.storageinfo = storageinfo + self.rebuild_args = rebuild_args + + @classmethod + def rebuild_from_type_v2( + cls, + func: Callable, + new_type: _TensorMeta, + args: tuple, + state: dict, + *, + archiveinfo: Optional["_LazyLoadingUnpickler"] = None, + ) -> Any: + ret = func(*args) + if isinstance(ret, _NotYetLoadedTensor): + old_lt = ret._load_tensor + + def _load_tensor() -> Any: + t = old_lt() + return torch._tensor._rebuild_from_type_v2(lambda: t, new_type, (), state) + + ret._load_tensor = _load_tensor # type: ignore[method-assign] + return ret + return torch._tensor._rebuild_from_type_v2(func, new_type, args, state) + + @classmethod + def rebuild_parameter( + cls, + data: Any, + requires_grad: bool, + backward_hooks: OrderedDict, + *, + archiveinfo: Optional["_LazyLoadingUnpickler"] = None, + ) -> Union[Tensor, "_NotYetLoadedTensor"]: + if isinstance(data, _NotYetLoadedTensor): + old_lt = data._load_tensor + + def _load_tensor() -> Parameter: + t = old_lt() + return torch._utils._rebuild_parameter(t, requires_grad, backward_hooks) + + data._load_tensor = _load_tensor # type: ignore[method-assign] + return data + return torch._utils._rebuild_parameter(data, requires_grad, backward_hooks) + + @classmethod + def rebuild_tensor_v2( + cls, + storage: "TypedStorage", + storage_offset: int, + size: tuple, + stride: tuple, + requires_grad: bool, + backward_hooks: OrderedDict, + metadata: Optional[Any] = None, + *, + archiveinfo: "_LazyLoadingUnpickler", + ) -> "_NotYetLoadedTensor": + rebuild_args = (storage_offset, size, stride, requires_grad, backward_hooks, metadata) + metatensor = torch._utils._rebuild_tensor_v2( + storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata + ) + storageinfo = storage.archiveinfo + return _NotYetLoadedTensor(metatensor, archiveinfo, storageinfo, rebuild_args) + + def _load_tensor(self) -> Tensor: + from torch.storage import TypedStorage, UntypedStorage + + _, _, fn, _, size = self.storageinfo + dtype = self.metatensor.dtype + + storage = self.archiveinfo.file_reader.get_storage_from_record( + f"data/{fn}", size * torch._utils._element_size(dtype), UntypedStorage + ) + uts = storage._typed_storage()._untyped_storage + + with warnings.catch_warnings(): + # The TypedStorage APIs have heavy deprecations in torch, suppress all these warnings for now + warnings.simplefilter("ignore") + storage = TypedStorage(wrap_storage=uts, dtype=dtype, _internal=True) + return torch._utils._rebuild_tensor_v2(storage, *self.rebuild_args) + + @classmethod + def __torch_function__( + cls, + func: Callable, + types: Sequence, + args: Sequence[Any] = (), + kwargs: Optional[dict] = None, + ) -> Any: + kwargs = kwargs or {} + loaded_args = [(arg._load_tensor() if isinstance(arg, _NotYetLoadedTensor) else arg) for arg in args] + return func(*loaded_args, **kwargs) + + @property + def device(self) -> torch.device: + return torch.device(self.storageinfo[3]) + + def __getattr__(self, name: str) -> Any: + # These properties don't require materialization and can be accessed through the meta tensor directly + if name in { + "dtype", + "grad", + "grad_fn", + "is_meta", + "layout", + "names", + "ndim", + "output_nr", + "requires_grad", + "retains_grad", + "size", + "shape", + "volatile", + }: + return getattr(self.metatensor, name) + + # materializing these is needed for quantization (see lit-gpt) + if name in {"contiguous", "cuda", "half", "data", "to"}: + return getattr(self._load_tensor(), name) + + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({repr(self.metatensor)})" + + +# Modified from https://github.com/lernapparat/torchhacks by Thomas Viehmann +class _LazyLoadingUnpickler(pickle.Unpickler): + def __init__(self, file: IO, file_reader: torch.PyTorchFileReader) -> None: + super().__init__(file) + self.file_reader = file_reader + + @override + def find_class(self, module: str, name: str) -> Any: + if module == "torch._utils" and name == "_rebuild_tensor_v2": + return partial(_NotYetLoadedTensor.rebuild_tensor_v2, archiveinfo=self) + if module == "torch._tensor" and name == "_rebuild_from_type_v2": + return partial(_NotYetLoadedTensor.rebuild_from_type_v2, archiveinfo=self) + if module == "torch._utils" and name == "_rebuild_parameter": + return partial(_NotYetLoadedTensor.rebuild_parameter, archiveinfo=self) + return super().find_class(module, name) + + @override + def persistent_load(self, pid: tuple) -> "TypedStorage": + from torch.storage import TypedStorage + + _, cls, _, _, _ = pid + with warnings.catch_warnings(): + # The TypedStorage APIs have heavy deprecations in torch, suppress all these warnings for now + warnings.simplefilter("ignore") + storage = TypedStorage(dtype=cls().dtype, device="meta") + storage.archiveinfo = pid + return storage + + +def _lazy_load(filename: _PATH) -> Any: + if not os.path.isfile(filename): + raise FileNotFoundError(f"Path {str(filename)!r} does not exist or is not a file.") + file_reader = torch.PyTorchFileReader(str(filename)) + with BytesIO(file_reader.get_record("data.pkl")) as pkl: + mup = _LazyLoadingUnpickler(pkl, file_reader) + return mup.load() + + +def _materialize_tensors(collection: Any) -> Any: + def _load_tensor(t: _NotYetLoadedTensor) -> Tensor: + return t._load_tensor() + + return apply_to_collection(collection, dtype=_NotYetLoadedTensor, function=_load_tensor) + + +def _move_state_into( + source: dict[str, Any], destination: dict[str, Union[Any, _Stateful]], keys: Optional[set[str]] = None +) -> None: + """Takes the state from the source destination and moves it into the destination dictionary. + + If an object in the destination follows the stateful protocol, it loads the source state via ``load_state_dict``. + + """ + keys = set(source) if keys is None else keys & set(source) + for key in keys: + state = source.pop(key) + if key in destination and isinstance(destination[key], _Stateful): + destination[key].load_state_dict(state) + else: + destination[key] = state + + +def _load_distributed_checkpoint(checkpoint_folder: Path) -> dict[str, Any]: + """Loads a sharded checkpoint saved with the `torch.distributed.checkpoint` into a full state dict. + + The current implementation assumes that the entire checkpoint fits in CPU memory. + + """ + if not _TORCH_GREATER_EQUAL_2_3: + raise ImportError("Processing distributed checkpoints requires PyTorch >= 2.3.") + + from torch.distributed.checkpoint import FileSystemReader + from torch.distributed.checkpoint.format_utils import _EmptyStateDictLoadPlanner + from torch.distributed.checkpoint.state_dict_loader import _load_state_dict + + checkpoint: dict[str, Any] = {} + _load_state_dict( + checkpoint, + storage_reader=FileSystemReader(checkpoint_folder), + planner=_EmptyStateDictLoadPlanner(), + no_dist=True, + ) + + # This is the extra file saved by Fabric, with user data separate from weights and optimizer states + extra_file = checkpoint_folder / _METADATA_FILENAME + extra = torch.load(extra_file, map_location="cpu") if extra_file.is_file() else {} + checkpoint.update(extra) + + return checkpoint diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/logger.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..3a128c016b3599432fc738161c0e9d2790a41f22 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/logger.py @@ -0,0 +1,183 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +import json +from argparse import Namespace +from collections.abc import Mapping, MutableMapping +from dataclasses import asdict, is_dataclass +from typing import Any, Optional, Union + +from torch import Tensor + +from lightning_fabric.utilities.imports import _NUMPY_AVAILABLE + + +def _convert_params(params: Optional[Union[dict[str, Any], Namespace]]) -> dict[str, Any]: + """Ensure parameters are a dict or convert to dict if necessary. + + Args: + params: Target to be converted to a dictionary + + Returns: + params as a dictionary + + """ + # in case converting from namespace + if isinstance(params, Namespace): + params = vars(params) + + if params is None: + params = {} + + return params + + +def _sanitize_callable_params(params: dict[str, Any]) -> dict[str, Any]: + """Sanitize callable params dict, e.g. ``{'a': } -> {'a': 'function_****'}``. + + Args: + params: Dictionary containing the hyperparameters + + Returns: + dictionary with all callables sanitized + + """ + + def _sanitize_callable(val: Any) -> Any: + if inspect.isclass(val): + # If it's a class, don't try to instantiate it, just return the name + return val.__name__ + if callable(val): + # Callables get a chance to return a name + try: + _val = val() + if callable(_val): + return val.__name__ + return _val + # todo: specify the possible exception + except Exception: + return getattr(val, "__name__", None) + return val + + return {key: _sanitize_callable(val) for key, val in params.items()} + + +def _flatten_dict(params: MutableMapping[Any, Any], delimiter: str = "/", parent_key: str = "") -> dict[str, Any]: + """Flatten hierarchical dict, e.g. ``{'a': {'b': 'c'}} -> {'a/b': 'c'}``. + + Args: + params: Dictionary containing the hyperparameters + delimiter: Delimiter to express the hierarchy. Defaults to ``'/'``. + + Returns: + Flattened dict. + + Examples: + >>> _flatten_dict({'a': {'b': 'c'}}) + {'a/b': 'c'} + >>> _flatten_dict({'a': {'b': 123}}) + {'a/b': 123} + >>> _flatten_dict({5: {'a': 123}}) + {'5/a': 123} + >>> _flatten_dict({"dl": [{"a": 1, "c": 3}, {"b": 2, "d": 5}], "l": [1, 2, 3, 4]}) + {'dl/0/a': 1, 'dl/0/c': 3, 'dl/1/b': 2, 'dl/1/d': 5, 'l': [1, 2, 3, 4]} + + """ + result: dict[str, Any] = {} + for k, v in params.items(): + new_key = parent_key + delimiter + str(k) if parent_key else str(k) + if is_dataclass(v) and not isinstance(v, type): + v = asdict(v) + elif isinstance(v, Namespace): + v = vars(v) + + if isinstance(v, MutableMapping): + result = {**result, **_flatten_dict(v, parent_key=new_key, delimiter=delimiter)} + # Also handle the case where v is a list of dictionaries + elif isinstance(v, list) and all(isinstance(item, MutableMapping) for item in v): + for i, item in enumerate(v): + result = {**result, **_flatten_dict(item, parent_key=f"{new_key}/{i}", delimiter=delimiter)} + else: + result[new_key] = v + return result + + +def _sanitize_params(params: dict[str, Any]) -> dict[str, Any]: + """Returns params with non-primitvies converted to strings for logging. + + >>> import torch + >>> params = {"float": 0.3, + ... "int": 1, + ... "string": "abc", + ... "bool": True, + ... "list": [1, 2, 3], + ... "namespace": Namespace(foo=3), + ... "layer": torch.nn.BatchNorm1d} + >>> import pprint + >>> pprint.pprint(_sanitize_params(params)) # doctest: +NORMALIZE_WHITESPACE + {'bool': True, + 'float': 0.3, + 'int': 1, + 'layer': "", + 'list': '[1, 2, 3]', + 'namespace': 'Namespace(foo=3)', + 'string': 'abc'} + + """ + for k in params: + if _NUMPY_AVAILABLE: + import numpy as np + + if isinstance(params[k], (np.bool_, np.integer, np.floating)): + params[k] = params[k].item() + if type(params[k]) not in [bool, int, float, str, Tensor]: + params[k] = str(params[k]) + return params + + +def _convert_json_serializable(params: dict[str, Any]) -> dict[str, Any]: + """Convert non-serializable objects in params to string.""" + return {k: str(v) if not _is_json_serializable(v) else v for k, v in params.items()} + + +def _is_json_serializable(value: Any) -> bool: + """Test whether a variable can be encoded as json.""" + if value is None or isinstance(value, (bool, int, float, str, list, dict)): # fast path + return True + try: + json.dumps(value) + return True + except (TypeError, OverflowError): + # OverflowError is raised if number is too large to encode + return False + + +def _add_prefix( + metrics: Mapping[str, Union[Tensor, float]], prefix: str, separator: str +) -> Mapping[str, Union[Tensor, float]]: + """Insert prefix before each key in a dict, separated by the separator. + + Args: + metrics: Dictionary with metric names as keys and measured quantities as values + prefix: Prefix to insert before each key + separator: Separates prefix and original key name + + Returns: + Dictionary with prefix and separator inserted before each key + + """ + if not prefix: + return metrics + return {f"{prefix}{separator}{k}": v for k, v in metrics.items()} diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/optimizer.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..6b47722d788248228336879ddc63196c52d99cd4 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/optimizer.py @@ -0,0 +1,41 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Iterable, MutableMapping + +from torch import Tensor +from torch.optim import Optimizer + +from lightning_fabric.utilities.apply_func import apply_to_collection, move_data_to_device +from lightning_fabric.utilities.types import _DEVICE + + +def _optimizers_to_device(optimizers: Iterable[Optimizer], device: _DEVICE) -> None: + """Moves optimizer states for a sequence of optimizers to the device.""" + for opt in optimizers: + _optimizer_to_device(opt, device) + + +def _optimizer_to_device(optimizer: Optimizer, device: _DEVICE) -> None: + """Moves the state of a single optimizer to the device.""" + for p, v in optimizer.state.items(): + if not isinstance(v, MutableMapping): + # Support for custom optimizers + optimizer.state[p] = apply_to_collection(v, Tensor, move_data_to_device, device, allow_frozen=True) + continue + for key, val in v.items(): + # The 'step' parameter needs to remain unmoved (possibly on the CPU) since that is where the optimizer + # needs it. See https://github.com/pytorch/pytorch/issues/74424 + if key != "step": + v[key] = move_data_to_device(val, device) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/rank_zero.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/rank_zero.py new file mode 100644 index 0000000000000000000000000000000000000000..d34e19430b107981b886fb1f8dc85ea274d64f61 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/rank_zero.py @@ -0,0 +1,57 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Utilities that can be used for calling functions on a particular rank.""" + +import logging +import os +from typing import Optional + +import lightning_utilities.core.rank_zero as rank_zero_module + +# note: we want to keep these indirections so the `rank_zero_only.rank` is set on import +from lightning_utilities.core.rank_zero import ( # noqa: F401 + WarningCache, + rank_prefixed_message, + rank_zero_debug, + rank_zero_deprecation, + rank_zero_info, + rank_zero_warn, +) + +rank_zero_module.log = logging.getLogger(__name__) + + +def _get_rank() -> Optional[int]: + # SLURM_PROCID can be set even if SLURM is not managing the multiprocessing, + # therefore LOCAL_RANK needs to be checked first + rank_keys = ("RANK", "LOCAL_RANK", "SLURM_PROCID", "JSM_NAMESPACE_RANK") + for key in rank_keys: + rank = os.environ.get(key) + if rank is not None: + return int(rank) + # None to differentiate whether an environment variable was set at all + return None + + +rank_zero_only = rank_zero_module.rank_zero_only + +# add the attribute to the function but don't overwrite in case Trainer has already set it +rank_zero_only.rank = getattr(rank_zero_only, "rank", _get_rank() or 0) + + +class LightningDeprecationWarning(DeprecationWarning): + """Deprecation warnings raised by Lightning.""" + + +rank_zero_module.rank_zero_deprecation_category = LightningDeprecationWarning diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/registry.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..1eabb5e1ffbfaff0bc15673bd021dfdff2f1841f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/registry.py @@ -0,0 +1,61 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import logging +from importlib.metadata import entry_points +from inspect import getmembers, isclass +from types import ModuleType +from typing import Any, Union + +from lightning_utilities import is_overridden + +from lightning_fabric.utilities.imports import _PYTHON_GREATER_EQUAL_3_10_0 + +_log = logging.getLogger(__name__) + + +def _load_external_callbacks(group: str) -> list[Any]: + """Collect external callbacks registered through entry points. + + The entry points are expected to be functions returning a list of callbacks. + + Args: + group: The entry point group name to load callbacks from. + + Return: + A list of all callbacks collected from external factories. + + """ + factories = ( + entry_points(group=group) if _PYTHON_GREATER_EQUAL_3_10_0 else entry_points().get(group, {}) # type: ignore[arg-type] + ) + + external_callbacks: list[Any] = [] + for factory in factories: + callback_factory = factory.load() + callbacks_list: Union[list[Any], Any] = callback_factory() + callbacks_list = [callbacks_list] if not isinstance(callbacks_list, list) else callbacks_list + if callbacks_list: + _log.info( + f"Adding {len(callbacks_list)} callbacks from entry point '{factory.name}':" + f" {', '.join(type(cb).__name__ for cb in callbacks_list)}" + ) + external_callbacks.extend(callbacks_list) + return external_callbacks + + +def _register_classes(registry: Any, method: str, module: ModuleType, parent: type[object]) -> None: + for _, member in getmembers(module, isclass): + if issubclass(member, parent) and is_overridden(method, member, parent): + register_fn = getattr(member, method) + register_fn(registry) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/seed.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/seed.py new file mode 100644 index 0000000000000000000000000000000000000000..67bb253e3f2a40e4f7bbe71af0b153d6c2e2aa13 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/seed.py @@ -0,0 +1,162 @@ +import logging +import os +import random +from random import getstate as python_get_rng_state +from random import setstate as python_set_rng_state +from typing import Any, Optional + +import torch + +from lightning_fabric.utilities.imports import _NUMPY_AVAILABLE +from lightning_fabric.utilities.rank_zero import _get_rank, rank_prefixed_message, rank_zero_only, rank_zero_warn + +log = logging.getLogger(__name__) + + +max_seed_value = 4294967295 # 2^32 - 1 (uint32) +min_seed_value = 0 + + +def seed_everything(seed: Optional[int] = None, workers: bool = False, verbose: bool = True) -> int: + r"""Function that sets the seed for pseudo-random number generators in: torch, numpy, and Python's random module. + In addition, sets the following environment variables: + + - ``PL_GLOBAL_SEED``: will be passed to spawned subprocesses (e.g. ddp_spawn backend). + - ``PL_SEED_WORKERS``: (optional) is set to 1 if ``workers=True``. + + Args: + seed: the integer value seed for global random state in Lightning. + If ``None``, it will read the seed from ``PL_GLOBAL_SEED`` env variable. If ``None`` and the + ``PL_GLOBAL_SEED`` env variable is not set, then the seed defaults to 0. If seed is + not in bounds or cannot be cast to int, a ValueError is raised. + workers: if set to ``True``, will properly configure all dataloaders passed to the + Trainer with a ``worker_init_fn``. If the user already provides such a function + for their dataloaders, setting this argument will have no influence. See also: + :func:`~lightning_fabric.utilities.seed.pl_worker_init_function`. + verbose: Whether to print a message on each rank with the seed being set. + + """ + if seed is None: + env_seed = os.environ.get("PL_GLOBAL_SEED") + if env_seed is None: + seed = 0 + if verbose: + rank_zero_warn(f"No seed found, seed set to {seed}") + else: + try: + seed = int(env_seed) + except ValueError: + raise ValueError(f"Invalid seed specified via PL_GLOBAL_SEED: {repr(env_seed)}") + elif not isinstance(seed, int): + seed = int(seed) + + if not (min_seed_value <= seed <= max_seed_value): + raise ValueError(f"{seed} is not in bounds, numpy accepts from {min_seed_value} to {max_seed_value}") + + if verbose: + log.info(rank_prefixed_message(f"Seed set to {seed}", _get_rank())) + + os.environ["PL_GLOBAL_SEED"] = str(seed) + random.seed(seed) + if _NUMPY_AVAILABLE: + import numpy as np + + np.random.seed(seed) + torch.manual_seed(seed) + + os.environ["PL_SEED_WORKERS"] = f"{int(workers)}" + + return seed + + +def reset_seed() -> None: + r"""Reset the seed to the value that :func:`~lightning_fabric.utilities.seed.seed_everything` previously set. + + If :func:`~lightning_fabric.utilities.seed.seed_everything` is unused, this function will do nothing. + + """ + seed = os.environ.get("PL_GLOBAL_SEED", None) + if seed is None: + return + workers = os.environ.get("PL_SEED_WORKERS", "0") + seed_everything(int(seed), workers=bool(int(workers)), verbose=False) + + +def pl_worker_init_function(worker_id: int, rank: Optional[int] = None) -> None: # pragma: no cover + r"""The worker_init_fn that Lightning automatically adds to your dataloader if you previously set the seed with + ``seed_everything(seed, workers=True)``. + + See also the PyTorch documentation on + `randomness in DataLoaders `_. + + """ + # implementation notes: https://github.com/pytorch/pytorch/issues/5059#issuecomment-817392562 + global_rank = rank if rank is not None else rank_zero_only.rank + process_seed = torch.initial_seed() + # back out the base seed so we can use all the bits + base_seed = process_seed - worker_id + log.debug( + f"Initializing random number generators of process {global_rank} worker {worker_id} with base seed {base_seed}" + ) + seed_sequence = _generate_seed_sequence(base_seed, worker_id, global_rank, count=4) + torch.manual_seed(seed_sequence[0]) # torch takes a 64-bit seed + random.seed((seed_sequence[1] << 32) | seed_sequence[2]) # combine two 64-bit seeds + if _NUMPY_AVAILABLE: + import numpy as np + + ss = np.random.SeedSequence([base_seed, worker_id, global_rank]) + np_rng_seed = ss.generate_state(4) + + np.random.seed(np_rng_seed) + + +def _generate_seed_sequence(base_seed: int, worker_id: int, global_rank: int, count: int) -> list[int]: + """Generates a sequence of seeds from a base seed, worker id and rank using hash-based mixing followed by the + linear congruential generator (LCG) algorithm.""" + # Combine base seed, worker id and rank into a unique 64-bit number + combined_seed = (base_seed << 32) | (worker_id << 16) | global_rank + + # Apply hash-based mixing (MurmurHash3 finalizer) to distribute bits uniformly + # This ensures that small base seeds don't result in zeros in lower bits + combined_seed ^= combined_seed >> 33 + combined_seed = (combined_seed * 0xFF51AFD7ED558CCD) & ((1 << 64) - 1) + combined_seed ^= combined_seed >> 33 + combined_seed = (combined_seed * 0xC4CEB9FE1A85EC53) & ((1 << 64) - 1) + combined_seed ^= combined_seed >> 33 + + seeds = [] + for _ in range(count): + # x_(n+1) = (a * x_n + c) mod m. With c=1, m=2^64 and a is D. Knuth's constant + combined_seed = (combined_seed * 6364136223846793005 + 1) & ((1 << 64) - 1) + seeds.append(combined_seed) + return seeds + + +def _collect_rng_states(include_cuda: bool = True) -> dict[str, Any]: + r"""Collect the global random state of :mod:`torch`, :mod:`torch.cuda`, :mod:`numpy` and Python.""" + states = { + "torch": torch.get_rng_state(), + "python": python_get_rng_state(), + } + if _NUMPY_AVAILABLE: + import numpy as np + + states["numpy"] = np.random.get_state() + if include_cuda: + states["torch.cuda"] = torch.cuda.get_rng_state_all() if torch.cuda.is_available() else [] + return states + + +def _set_rng_states(rng_state_dict: dict[str, Any]) -> None: + r"""Set the global random state of :mod:`torch`, :mod:`torch.cuda`, :mod:`numpy` and Python in the current + process.""" + torch.set_rng_state(rng_state_dict["torch"]) + # torch.cuda rng_state is only included since v1.8. + if "torch.cuda" in rng_state_dict: + torch.cuda.set_rng_state_all(rng_state_dict["torch.cuda"]) + if _NUMPY_AVAILABLE and "numpy" in rng_state_dict: + import numpy as np + + np.random.set_state(rng_state_dict["numpy"]) + version, state, gauss = rng_state_dict["python"] + python_set_rng_state((version, tuple(state), gauss)) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/spike.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/spike.py new file mode 100644 index 0000000000000000000000000000000000000000..ee118958e94ddab06ef30b39ea78a5f6be292613 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/spike.py @@ -0,0 +1,176 @@ +import json +import os +import warnings +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +import torch + +from lightning_fabric.utilities.imports import _TORCHMETRICS_GREATER_EQUAL_1_0_0 +from lightning_fabric.utilities.types import _PATH + +if TYPE_CHECKING: + from lightning_fabric.fabric import Fabric + + +class SpikeDetection: + """Spike Detection Callback. + + Terminates training with a ``TrainingSpikeException`` when a loss-spike was detected and + saves the batches to skip when resuming to a file. + + We skip the current and the previous batch since it is unclear whether the previous batch + altered the weights in a way that it causes the spike or just the current batch is corrupted somehow. + + Args: + mode: Whether to minimize or maximize the tracked metric + window: A running mean of metrics with ``window`` size. Serves as reference value for spikes. + warmup: After how many batches spike-tracking should start + atol: An absolute tolerance. Every diff between the running mean and the current value, + that's not an improvement and above ``atol`` will be considered a spike + rtol: A relative tolerance. Every diff between the running mean and the current value, + that's higher than ``rtol * running_mean`` is considered a spike + exclude_batches_path: Where to save the file that contains the batches to exclude. + Will default to current directory. + finite_only: If set to ``False``, consider non-finite values like NaN, inf and -inf a spike as well. + + """ + + def __init__( + self, + mode: Literal["min", "max"] = "min", + window: int = 10, + warmup: int = 1, + atol: Optional[float] = None, + rtol: Optional[float] = 2.0, + exclude_batches_path: Optional[_PATH] = None, + finite_only: bool = True, + ): + if _TORCHMETRICS_GREATER_EQUAL_1_0_0: + from torchmetrics.aggregation import MeanMetric + from torchmetrics.wrappers import Running + else: + raise RuntimeError("SpikeDetection requires `torchmetrics>=1.0.0` Please upgrade your version.") + super().__init__() + + self.last_val: Union[torch.Tensor, float] = 0.0 + # spike detection happens individually on each machine + self.running_mean = Running(MeanMetric(dist_sync_on_step=False, sync_on_compute=False), window=window) + # workaround for https://github.com/Lightning-AI/torchmetrics/issues/1899 + self.running_mean.dist_sync_on_step = False + self.running_mean.sync_on_compute = False + + self.mode = mode + self.warmup = warmup + self.atol = atol + self.rtol = rtol + self.bad_batches: list[int] = [] + self.exclude_batches_path = exclude_batches_path + self.finite_only = finite_only + + @torch.no_grad() + def on_train_batch_end(self, fabric: "Fabric", loss: torch.Tensor, batch: Any, batch_idx: int) -> None: + """Checks if we currently have a loss-spike.""" + if batch_idx == 0: + self.running_mean.to(fabric.strategy.root_device) + + if self.exclude_batches_path is None: + self.exclude_batches_path = os.getcwd() + + if not str(self.exclude_batches_path).endswith(".json"): + self.exclude_batches_path = os.path.join(self.exclude_batches_path, "skip_batches.json") + + is_spike = bool(batch_idx >= self.warmup and self._is_spike(loss)) + fabric.strategy.barrier() + + # While spike-detection happens on a per-rank level, we need to fail all ranks if any rank detected a spike + is_spike_global = fabric.strategy.reduce_boolean_decision(is_spike, all=False) + + if is_spike_global: + self._handle_spike(fabric, batch_idx) + else: + is_finite_all = self.finite_only or fabric.strategy.reduce_boolean_decision( + bool(torch.isfinite(loss).all()), all=True + ) + if is_finite_all: + self._update_stats(loss) + + def _is_spike(self, loss: torch.Tensor) -> bool: + # we might call compute more often than update which is fine as long as the + # metric has at least one internal value. + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + running_val = self.running_mean.compute() + curr_diff = loss - self.last_val + + if self.finite_only and not torch.isfinite(loss): + return True + + if self._is_better(curr_diff): + return False + + return self._check_atol(loss, running_val) and self._check_rtol(loss, running_val) + + def _handle_spike(self, fabric: "Fabric", batch_idx: int) -> None: + # Exclude current and last batch + # Current batch is excluded since it could be that the data of this batch produces a high loss + # Last batch is excluded since the previous batch could have "corrupted" the weights + self.bad_batches.extend([batch_idx - 1, batch_idx]) + + if fabric.global_rank == 0: + assert self.exclude_batches_path is not None + os.makedirs(os.path.dirname(self.exclude_batches_path), exist_ok=True) + + with open(self.exclude_batches_path, "w") as f: + json.dump(self.bad_batches, f, indent=4) + + raise TrainingSpikeException(batch_idx=batch_idx) + + def _check_atol(self, val_a: Union[float, torch.Tensor], val_b: Union[float, torch.Tensor]) -> bool: + return (self.atol is None) or bool(abs(val_a - val_b) >= abs(self.atol)) # type: ignore + + def _check_rtol(self, val_a: Union[float, torch.Tensor], val_b: Union[float, torch.Tensor]) -> bool: + return (self.rtol is None) or bool(abs(val_a - val_b) >= abs(self.rtol * val_b)) # type: ignore + + def _is_better(self, diff_val: torch.Tensor) -> bool: + if self.mode == "min": + return bool((diff_val <= 0.0).all()) + if self.mode == "max": + return bool((diff_val >= 0).all()) + + raise ValueError(f"Invalid mode. Has to be min or max, found {self.mode}") + + def _update_stats(self, val: torch.Tensor) -> None: + # only update if finite + self.running_mean.update(val) + self.last_val = val + + def state_dict(self) -> dict[str, Any]: + return { + "last_val": self.last_val.item() if isinstance(self.last_val, torch.Tensor) else self.last_val, + "mode": self.mode, + "warmup": self.warmup, + "atol": self.atol, + "rtol": self.rtol, + "bad_batches": self.bad_batches, + "bad_batches_path": self.exclude_batches_path, + "running": self.running_mean.state_dict(), + "mean": self.running_mean.base_metric.state_dict(), + } + + def load_state_dict(self, state_dict: dict[str, Any]) -> None: + self.last_val = state_dict.pop("last_val") + self.mode = state_dict.pop("mode") + self.warmup = state_dict.pop("warmup") + self.atol = state_dict.pop("atol") + self.rtol = state_dict.pop("rtol") + self.bad_batches = state_dict.pop("bad_batches") + self.exclude_batches_path = state_dict.pop("bad_batches_path") + self.running.load_state_dict(state_dict.pop("running")) + self.running_mean.base_metric.load_state_dict(state_dict.pop("mean")) + + +class TrainingSpikeException(RuntimeError): + """Exception to be raised with Training Spikes.""" + + def __init__(self, batch_idx: int, *args: Any, **kwargs: Any): + super().__init__(f"Training spike detected in batch {batch_idx}", *args, **kwargs) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0a8a11d83b2e5a03607a52002670e8412daea656 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/__init__.py @@ -0,0 +1,3 @@ +from lightning_fabric.utilities.testing._runif import _runif_reasons + +__all__ = ["_runif_reasons"] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00df54897fdff94829171e8ea6a11d339361d42d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/__pycache__/_runif.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/__pycache__/_runif.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1508f5320edc0da9ce2a815feaf8d0e7b3f657a2 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/__pycache__/_runif.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/_runif.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/_runif.py new file mode 100644 index 0000000000000000000000000000000000000000..46c21e9ac02c5e6d5cb39025ff482c3fdae9cafa --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/testing/_runif.py @@ -0,0 +1,128 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import operator +import os +import sys +from typing import Optional + +import torch +from lightning_utilities.core.imports import compare_version +from packaging.version import Version + +from lightning_fabric.accelerators import XLAAccelerator +from lightning_fabric.accelerators.cuda import num_cuda_devices +from lightning_fabric.accelerators.mps import MPSAccelerator +from lightning_fabric.strategies.deepspeed import _DEEPSPEED_AVAILABLE +from lightning_fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_4 + + +def _runif_reasons( + *, + min_cuda_gpus: int = 0, + min_torch: Optional[str] = None, + max_torch: Optional[str] = None, + min_python: Optional[str] = None, + bf16_cuda: bool = False, + tpu: bool = False, + mps: Optional[bool] = None, + skip_windows: bool = False, + standalone: bool = False, + deepspeed: bool = False, + dynamo: bool = False, + linux_only: bool = False, +) -> tuple[list[str], dict[str, bool]]: + """Construct reasons for pytest skipif. + + Args: + min_cuda_gpus: Require this number of gpus and that the ``RUN_ONLY_CUDA_TESTS=1`` environment variable is set. + min_torch: Require that PyTorch is greater or equal than this version. + max_torch: Require that PyTorch is less than this version. + min_python: Require that Python is greater or equal than this version. + bf16_cuda: Require that CUDA device supports bf16. + tpu: Require that TPU is available. + mps: If True: Require that MPS (Apple Silicon) is available, + if False: Explicitly Require that MPS is not available + skip_windows: Skip for Windows platform. + standalone: Mark the test as standalone, our CI will run it in a separate process. + This requires that the ``PL_RUN_STANDALONE_TESTS=1`` environment variable is set. + deepspeed: Require that microsoft/DeepSpeed is installed. + dynamo: Require that `torch.dynamo` is supported. + + """ + reasons = [] + kwargs = {} # used in conftest.py::pytest_collection_modifyitems + + if min_cuda_gpus: + if num_cuda_devices() < min_cuda_gpus: + reasons.append(f"GPUs>={min_cuda_gpus}") + kwargs["min_cuda_gpus"] = True + + # set use_base_version for nightly support + if min_torch and compare_version("torch", operator.lt, min_torch, use_base_version=True): + reasons.append(f"torch>={min_torch}, {torch.__version__} installed") + + # set use_base_version for nightly support + if max_torch and compare_version("torch", operator.ge, max_torch, use_base_version=True): + reasons.append(f"torch<{max_torch}, {torch.__version__} installed") + + if min_python: + py_version = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}" + if Version(py_version) < Version(min_python): + reasons.append(f"python>={min_python}") + + if bf16_cuda: + try: + cond = not (torch.cuda.is_available() and torch.cuda.is_bf16_supported()) + except (AssertionError, RuntimeError) as ex: + # AssertionError: Torch not compiled with CUDA enabled + # RuntimeError: Found no NVIDIA driver on your system. + is_unrelated = "Found no NVIDIA driver" not in str(ex) or "Torch not compiled with CUDA" not in str(ex) + if is_unrelated: + raise ex + cond = True + if cond: + reasons.append("CUDA device bf16") + + if skip_windows and sys.platform == "win32": + reasons.append("unimplemented on Windows") + + if tpu: + if not XLAAccelerator.is_available(): + reasons.append("TPU") + kwargs["tpu"] = True + + if mps is not None: + if mps and not MPSAccelerator.is_available(): + reasons.append("MPS") + elif not mps and MPSAccelerator.is_available(): + reasons.append("not MPS") + + if standalone: + if os.getenv("PL_RUN_STANDALONE_TESTS", "0") != "1": + reasons.append("Standalone execution") + kwargs["standalone"] = True + + if deepspeed and not (_DEEPSPEED_AVAILABLE and _TORCH_GREATER_EQUAL_2_4): + reasons.append("Deepspeed") + + if dynamo: + from torch._dynamo.eval_frame import is_dynamo_supported + + if not is_dynamo_supported(): + reasons.append("torch.dynamo") + + if linux_only and sys.platform != "linux": + reasons.append("only linux") + + return reasons, kwargs diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/throughput.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..64c7b01e4f29c6df751bf3f7def513fb854cec4f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/throughput.py @@ -0,0 +1,699 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Adapted from https://github.com/mosaicml/composer/blob/f2a2dc820/composer/callbacks/speed_monitor.py +from collections import deque +from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union + +import torch +from typing_extensions import override + +from lightning_fabric.utilities.rank_zero import rank_zero_only, rank_zero_warn + +if TYPE_CHECKING: + from lightning_fabric import Fabric + from lightning_fabric.plugins import Precision + +_THROUGHPUT_METRICS = dict[str, Union[int, float]] + + +# The API design of this class follows `torchmetrics.Metric` but it doesn't need to be an actual Metric because there's +# no need for synchronization or reduction as it doesn't use Tensors at all. +class Throughput: + """Computes throughput. + + +------------------------+-------------------------------------------------------------------------------------+ + | Key | Value | + +========================+=====================================================================================+ + | batches_per_sec | Rolling average (over ``window_size`` most recent updates) of the number of batches | + | | processed per second | + +--------------------------+-----------------------------------------------------------------------------------+ + | samples_per_sec | Rolling average (over ``window_size`` most recent updates) of the number of samples | + | | processed per second | + +--------------------------+-----------------------------------------------------------------------------------+ + | items_per_sec | Rolling average (over ``window_size`` most recent updates) of the number of items | + | | processed per second | + +--------------------------+-----------------------------------------------------------------------------------+ + | flpps_per_sec | Rolling average (over ``window_size`` most recent updates) of the number of flops | + | | processed per second | + +--------------------------+-----------------------------------------------------------------------------------+ + | device/batches_per_sec | batches_per_sec divided by world size | + +--------------------------+-----------------------------------------------------------------------------------+ + | device/samples_per_sec | samples_per_sec divided by world size | + +--------------------------+-----------------------------------------------------------------------------------+ + | device/items_per_sec | items_per_sec divided by world size. This may include padding depending on the data | + +--------------------------+-----------------------------------------------------------------------------------+ + | device/flops_per_sec | flops_per_sec divided by world size. | + +--------------------------+-----------------------------------------------------------------------------------+ + | device/mfu | device/flops_per_sec divided by world size. | + +--------------------------+-----------------------------------------------------------------------------------+ + | time | Total elapsed time | + +--------------------------+-----------------------------------------------------------------------------------+ + | batches | Total batches seen | + +--------------------------+-----------------------------------------------------------------------------------+ + | samples | Total samples seen | + +--------------------------+-----------------------------------------------------------------------------------+ + | lengths | Total items seen | + +--------------------------+-----------------------------------------------------------------------------------+ + + Example:: + + throughput = Throughput() + t0 = time() + for i in range(1000): + do_work() + if torch.cuda.is_available(): torch.cuda.synchronize() # required or else time() won't be correct + throughput.update(time=time() - t0, samples=i) + if i % 10 == 0: + print(throughput.compute()) + + Notes: + - The implementation assumes that devices FLOPs are all the same as it normalizes by the world size and only + takes a single ``available_flops`` value. + - items_per_sec, flops_per_sec and MFU do not account for padding if present. We suggest using + samples_per_sec or batches_per_sec to measure throughput under this circumstance. + + Args: + available_flops: Number of theoretical flops available for a single device. + world_size: Number of devices available across hosts. Global metrics are not included if the world size is 1. + window_size: Number of batches to use for a rolling average. + separator: Key separator to use when creating per-device and global metrics. + + """ + + def __init__( + self, available_flops: Optional[float] = None, world_size: int = 1, window_size: int = 100, separator: str = "/" + ) -> None: + self.available_flops = available_flops + self.separator = separator + assert world_size > 0 + self.world_size = world_size + + # throughput is computed over a window of values. at least 2 is enforced since it looks at the difference + # between the first and last elements + assert window_size > 1 + # custom class instead of `deque(maxlen=)` because it's easy for users to mess up their timer/counters and log + # values that do not increase monotonically. this class will raise an error if that happens. + self._time: _MonotonicWindow[float] = _MonotonicWindow(maxlen=window_size) + self._batches: _MonotonicWindow[int] = _MonotonicWindow(maxlen=window_size) + self._samples: _MonotonicWindow[int] = _MonotonicWindow(maxlen=window_size) + self._lengths: _MonotonicWindow[int] = _MonotonicWindow(maxlen=window_size) + self._flops: deque[int] = deque(maxlen=window_size) + + def update( + self, + *, + time: float, + batches: int, + samples: int, + lengths: Optional[int] = None, + flops: Optional[int] = None, + ) -> None: + """Update throughput metrics. + + Args: + time: Total elapsed time in seconds. It should monotonically increase by the iteration time with each + call. + batches: Total batches seen per device. It should monotonically increase with each call. + samples: Total samples seen per device. It should monotonically increase by the batch size with each call. + lengths: Total length of the samples seen. It should monotonically increase by the lengths of a batch with + each call. + flops: Flops elapased per device since last ``update()`` call. You can easily compute this by using + :func:`measure_flops` and multiplying it by the number of batches that have been processed. + The value might be different in each device if the batch size is not the same. + + """ + self._time.append(time) + if samples < batches: + raise ValueError(f"Expected samples ({samples}) to be greater or equal than batches ({batches})") + self._batches.append(batches) + self._samples.append(samples) + if lengths is not None: + if lengths < samples: + raise ValueError(f"Expected lengths ({lengths}) to be greater or equal than samples ({samples})") + self._lengths.append(lengths) + if len(self._samples) != len(self._lengths): + raise RuntimeError( + f"If lengths are passed ({len(self._lengths)}), there needs to be the same number of samples" + f" ({len(self._samples)})" + ) + if flops is not None: + # sum of flops across ranks + self._flops.append(flops * self.world_size) + + def compute(self) -> _THROUGHPUT_METRICS: + """Compute throughput metrics.""" + metrics = { + "time": self._time[-1], + "batches": self._batches[-1], + "samples": self._samples[-1], + } + if self._lengths: + metrics["lengths"] = self._lengths[-1] + + add_global_metrics = self.world_size > 1 + # a different but valid design choice would be to still compute all these metrics even if the window of values + # has not been filled + if len(self._time) == self._time.maxlen: + elapsed_time = self._time[-1] - self._time[0] + elapsed_batches = self._batches[-1] - self._batches[0] + elapsed_samples = self._samples[-1] - self._samples[0] + # we are safe from ZeroDivisionError thanks to `_MonotonicWindow` + dev_samples_per_sec = elapsed_samples / elapsed_time + dev_batches_per_sec = elapsed_batches / elapsed_time + metrics.update({ + f"device{self.separator}batches_per_sec": elapsed_batches / elapsed_time, + f"device{self.separator}samples_per_sec": dev_samples_per_sec, + }) + if add_global_metrics: + samples_per_sec = dev_batches_per_sec * self.world_size + metrics.update({ + "batches_per_sec": samples_per_sec, + "samples_per_sec": dev_samples_per_sec * self.world_size, + }) + + if len(self._lengths) == self._lengths.maxlen: + elapsed_lengths = self._lengths[-1] - self._lengths[0] + dev_items_per_sec = elapsed_lengths / elapsed_time + metrics[f"device{self.separator}items_per_sec"] = dev_items_per_sec + if add_global_metrics: + items_per_sec = dev_items_per_sec * self.world_size + metrics["items_per_sec"] = items_per_sec + + if len(self._flops) == self._flops.maxlen: + elapsed_flops = sum(self._flops) - self._flops[0] + elapsed_time = self._time[-1] - self._time[0] + flops_per_sec = elapsed_flops / elapsed_time + dev_flops_per_sec = flops_per_sec / self.world_size + if add_global_metrics: + metrics["flops_per_sec"] = flops_per_sec + metrics[f"device{self.separator}flops_per_sec"] = dev_flops_per_sec + if self.available_flops: + metrics[f"device{self.separator}mfu"] = dev_flops_per_sec / self.available_flops + + return metrics + + def reset(self) -> None: + self._time.clear() + self._batches.clear() + self._samples.clear() + self._lengths.clear() + self._flops.clear() + + +class ThroughputMonitor(Throughput): + r"""Computes throughput. + + This class will automatically keep a count of the number of log calls (``step``). But that can be modified as + desired. For manual logging, using :class:`Throughput` directly might be desired. + + Example:: + + logger = ... + fabric = Fabric(logger=logger) + throughput = ThroughputMonitor(fabric) + t0 = time() + for i in range(1, 100): + do_work() + if torch.cuda.is_available(): torch.cuda.synchronize() # required or else time() won't be correct + throughput.update(time=time() - t0, batches=i, samples=i) + if i % 10 == 0: + throughput.compute_and_log(step=i) + + Args: + fabric: The Fabric object. + \**kwargs: See available parameters in :class:`Throughput` + + """ + + def __init__(self, fabric: "Fabric", **kwargs: Any) -> None: + fabric._validate_launched() # otherwise world_size might be incorrect + dtype = _plugin_to_compute_dtype(fabric.strategy.precision) + available_flops = get_available_flops(fabric.device, dtype) + super().__init__(available_flops=available_flops, world_size=fabric.world_size, **kwargs) + self._fabric = fabric + self.step = -1 + + self.update = rank_zero_only(self.update) # type: ignore[method-assign] + self.compute = rank_zero_only(self.compute, default={}) # type: ignore[method-assign] + self.compute_and_log = rank_zero_only(self.compute_and_log, default={}) # type: ignore[method-assign] + self.reset = rank_zero_only(self.reset) # type: ignore[method-assign] + + def compute_and_log(self, step: Optional[int] = None, **kwargs: Any) -> _THROUGHPUT_METRICS: + r"""See :meth:`Throughput.compute` + + Args: + step: Can be used to override the logging step. + \**kwargs: See available parameters in :meth:`Throughput.compute` + + """ + self.step = (self.step + 1) if step is None else step + metrics = self.compute(**kwargs) + self._fabric.log_dict(metrics=metrics, step=self.step) + return metrics + + +def measure_flops( + model: torch.nn.Module, + forward_fn: Callable[[], torch.Tensor], + loss_fn: Optional[Callable[[torch.Tensor], torch.Tensor]] = None, +) -> int: + """Utility to compute the total number of FLOPs used by a module during training or during inference. + + It's recommended to create a meta-device model for this: + + Example:: + + with torch.device("meta"): + model = MyModel() + x = torch.randn(2, 32) + + model_fwd = lambda: model(x) + fwd_flops = measure_flops(model, model_fwd) + + model_loss = lambda y: y.sum() + fwd_and_bwd_flops = measure_flops(model, model_fwd, model_loss) + + Args: + model: The model whose FLOPs should be measured. + forward_fn: A function that runs ``forward`` on the model and returns the result. + loss_fn: A function that computes the loss given the ``forward_fn`` output. If provided, the loss and `backward` + FLOPs will be included in the result. + + """ + from torch.utils.flop_counter import FlopCounterMode + + flop_counter = FlopCounterMode(display=False) + with flop_counter: + if loss_fn is None: + forward_fn() + else: + loss_fn(forward_fn()).backward() + return flop_counter.get_total_flops() + + +_CUDA_FLOPS: dict[str, dict[Union[str, torch.dtype], float]] = { + # Hopper + # source: https://nvdam.widen.net/s/nb5zzzsjdf/hpc-datasheet-sc23-h200-datasheet-3002446 + "h200 sxm1": { + torch.float64: 3.4e13, + torch.float32: 6.7e13, + "tfloat32": 9.9e14, + torch.bfloat16: 2.0e15, + torch.float16: 2.0e15, + torch.int8: 4.0e15, + }, + "h200 nvl1": { + torch.float64: 3.0e13, + torch.float32: 6.0e13, + "tfloat32": 8.4e14, + torch.bfloat16: 1.7e15, + torch.float16: 1.7e15, + torch.int8: 3.3e15, + }, + # source: https://resources.nvidia.com/en-us-tensor-core + "h100 nvl": { + torch.float64: 67e12, + torch.float32: 133.8e12, + "tfloat32": 989.4e12, + torch.bfloat16: 1978.8e12, + torch.float16: 1978.8e12, + torch.int8: 3957.8e12, + }, + "h100 sxm": { + torch.float64: 33.5e12, + torch.float32: 66.9e12, + "tfloat32": 494.7e12, + torch.bfloat16: 989.4e12, + torch.float16: 989.4e12, + torch.int8: 1978.9e12, + }, + "h100 pcie": { + torch.float64: 25.6e12, + torch.float32: 51.2e12, + "tfloat32": 378e12, + torch.bfloat16: 756e12, + torch.float16: 756e12, + torch.int8: 1513e12, + }, + # Ada + # source: https://images.nvidia.com/aem-dam/Solutions/Data-Center/l4/nvidia-ada-gpu-architecture-whitepaper-v2.1.pdf + "rtx 4090": { + torch.float32: 82.6e12, + "tfloat32": 82.6e12, + torch.bfloat16: 82.6e12, + torch.float16: 82.6e12, + torch.int8: 660.6e12, + "int4": 1321.2e12, + }, + "rtx 4080": { + torch.float32: 48.7e12, + "tfloat32": 48.7e12, + torch.bfloat16: 48.7e12, + torch.float16: 48.7e12, + torch.int8: 389.9e12, + "int4": 779.8e12, + }, + "rtx 4080 super": { + torch.float32: 52.2e12, + "tfloat32": 52.2e12, + torch.bfloat16: 52.2e12, + torch.float16: 52.2e12, + torch.int8: 417.6e12, + "int4": 835.2e12, + }, + "l4": { + torch.float32: 30.3e12, + "tfloat32": 60e12, + torch.bfloat16: 121e12, + torch.float16: 121e12, + torch.int8: 242e12, + "int4": 484e12, + }, + "l40": { + torch.float32: 90.5e12, + "tfloat32": 90.5e12, + torch.bfloat16: 181e12, + torch.float16: 181e12, + torch.int8: 362e12, + "int4": 724e12, + }, + # Ampere + # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf + # sxm and pcie have same flop counts + "a100": { + torch.float64: 9.7e12, + torch.float32: 19.5e12, + "tfloat32": 156e12, + torch.bfloat16: 312e12, + torch.float16: 312e12, + torch.int8: 624e12, + }, + "a6000": { + torch.float32: 38.7e12, + "tfloat32": 77.4e12, + torch.bfloat16: 38.7e12, + torch.float16: 38.7e12, + torch.int8: 309.7e12, + "int4": 619.3e12, + }, + "a40": { + torch.float32: 37.4e12, + "tfloat32": 74.8e12, + torch.bfloat16: 37.4e12, + torch.float16: 37.4e12, + torch.int8: 299.3e12, + "int4": 598.7e12, + }, + # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a10/pdf/a10-datasheet.pdf + "a10g": { + torch.float32: 31.2e12, + "tfloat32": 62.5e12, + torch.bfloat16: 125e12, + torch.float16: 125e12, + torch.int8: 250e12, + "int4": 500e12, + }, + "rtx 3090 ti": { + torch.float32: 40e12, + "tfloat32": 40e12, + torch.bfloat16: 40e12, + torch.float16: 40e12, + torch.int8: 320e12, + "int4": 640e12, + }, + "rtx 3090": { + torch.float32: 35.6e12, + "tfloat32": 35.6e12, + torch.bfloat16: 35.6e12, + torch.float16: 35.6e12, + torch.int8: 284e12, + "int4": 568e12, + }, + "rtx 3080 ti": { + torch.float32: 34.1e12, + "tfloat32": 34.1e12, + torch.bfloat16: 34.1e12, + torch.float16: 34.1e12, + torch.int8: 272.8e12, + "int4": 546.6e12, + }, + "rtx 3080": { + torch.float32: 29.8e12, + "tfloat32": 29.8e12, + torch.bfloat16: 29.8e12, + torch.float16: 29.8e12, + torch.int8: 238e12, + "int4": 476e12, + }, + "rtx 3070": { + torch.float32: 20.3e12, + "tfloat32": 20.3e12, + torch.bfloat16: 20.3e12, + torch.float16: 20.3e12, + torch.int8: 162.6e12, + "int4": 325.2e12, + }, + # Turing + # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/tesla-t4/t4-tensor-core-datasheet-951643.pdf + # sxm and pcie have same flop counts + "t4": { + torch.float32: 8.1e12, + torch.float16: 65e12, + torch.int8: 130e12, + "int4": 260e12, + }, + # https://www.nvidia.com/content/dam/en-zz/Solutions/design-visualization/quadro-product-literature/quadro-rtx-5000-data-sheet-us-nvidia-704120-r4-web.pdf + "quadro rtx 5000": { + torch.float32: 11.2e12, + torch.float16: 89.2e12, + }, + "rtx 2080 super": { + torch.float32: 11.2e12, + torch.float16: 22.3e12, + torch.int8: 178.4e12, + "int4": 356.8e12, + }, + "rtx 2080 ti": { + torch.float32: 14.2e12, + torch.float16: 28.5e12, + torch.int8: 227.7e12, + "int4": 455.4e12, + }, + "rtx 2080": { + torch.float32: 10.6e12, + torch.float16: 21.2e12, + torch.int8: 169.6e12, + "int4": 339.1e12, + }, + # https://www.nvidia.com/content/PDF/nvidia-ampere-ga-102-gpu-architecture-whitepaper-v2.pdf + "rtx 2070 super": { + torch.float32: 9.1e12, + torch.float16: 18.1e12, + torch.int8: 145e12, + "int4": 290e12, + }, + "titan rtx": { + torch.float32: 16.3e12, + torch.float16: 32.6e12, + torch.int8: 261e12, + "int4": 522e12, + }, + # Volta + # source: https://images.nvidia.com/content/technologies/volta/pdf/volta-v100-datasheet-update-us-1165301-r5.pdf + "v100 sxm": { + torch.float64: 7.8e12, + torch.float32: 15.7e12, + torch.float16: 125e12, + }, + "v100 pcie": { + torch.float64: 7e12, + torch.float32: 14e12, + torch.float16: 112e12, + }, + "v100s pcie": { + torch.float64: 8.2e12, + torch.float32: 16.4e12, + torch.float16: 130e12, + }, +} + +_TPU_FLOPS = { + # flop count for each TPU generation is the same for all precisions + # since bfloat16 precision is always used for performing matrix operations + # for more info: https://cloud.google.com/tpu/docs/bfloat16#choosing_bfloat16 + # source: https://arxiv.org/pdf/1907.10701.pdf + "v2": 45e12, + # source: https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#tpu_v3 + "v3": 123e12, + # source: https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#tpu_v4 + "v4": 275e12, + # source: https://cloud.google.com/tpu/docs/v5e-training + "v5litepod": 197e12, +} + + +def get_available_flops(device: torch.device, dtype: Union[torch.dtype, str]) -> Optional[int]: + """Returns the available theoretical FLOPs. + + This is an optimistic upper limit that could only be achievable if only thick matmuls were run in a benchmark + environment. + + """ + if device.type == "cuda": + device_name = torch.cuda.get_device_name(device) + chip = device_name.lower() + if "h200" in chip: + if "sxm1" in chip: + chip = "h200 sxm1" + elif "nvl1" in chip: + chip = "h200 nvl1" + elif "h100" in chip: + if "hbm3" in chip: + chip = "h100 sxm" + elif "nvl" in chip: + chip = "h100 nvl" + elif "pcie" in chip or "hbm2e" in chip: + chip = "h100 pcie" + elif "l4" in chip: + chip = "l40" if "tesla" in chip else "l4" + elif "geforce rtx" in chip: + number = chip.split(" ")[3] + extra = "" + if "super" in chip: + extra = " super" + elif "ti" in chip: + extra = " ti" + chip = f"rtx {number}{extra}" + elif "a6000" in chip: + chip = "a6000" + elif "a100" in chip: + chip = "a100" + elif "a40" in chip: + chip = "a40" + elif "a10g" in chip: + chip = "a10g" + elif "t4" in chip: + chip = "t4" + elif "quadro rtx 5000" in chip: + chip = "quadro rtx 5000" + elif "titan rtx" in chip: + chip = "titan rtx" + elif "v100-sxm" in chip: + chip = "v100 sxm" + elif "v100-pcie" in chip: + chip = "v100 pcie" + elif "v100s-pcie" in chip: + chip = "v100s pcie" + else: + # the flops list is not exhaustive, return with a warning + rank_zero_warn(f"FLOPs not found for {device_name!r}") + return None + if chip not in _CUDA_FLOPS: + # parsing is implemented but we don't have the stats + rank_zero_warn(f"FLOPs not found for {device_name!r}, chip is {chip!r}") + return None + dtype_to_flops = _CUDA_FLOPS[chip] + if dtype is torch.float32: + from lightning_fabric.accelerators.cuda import _is_ampere_or_later + + if _is_ampere_or_later() and torch.get_float32_matmul_precision() != "highest": + dtype = "tfloat32" + if dtype not in dtype_to_flops: + # for example, T4 doesn't support bfloat16. it might also be that we are missing this dtype from the list + rank_zero_warn(f"{device_name!r} does not support {dtype}") + return None + return int(dtype_to_flops[dtype]) + + if device.type == "xla": + from lightning_fabric.accelerators.xla import _XLA_GREATER_EQUAL_2_1 + + if _XLA_GREATER_EQUAL_2_1: + from torch_xla._internal import tpu + else: + from torch_xla.experimental import tpu + + tpu_env = tpu.get_tpu_env() + # not all TPU generations define the "TYPE" envar. example: TYPE="V4", ACCELERATOR_TYPE="v4-8" + device_name = tpu_env.get("TYPE") or tpu_env["ACCELERATOR_TYPE"].split("-")[0] + chip = device_name.lower() + assert isinstance(device_name, str) + if chip not in _TPU_FLOPS: + rank_zero_warn(f"FLOPs not found for TPU {device_name!r} with {dtype}") + return None + return int(_TPU_FLOPS[chip]) + + +def _plugin_to_compute_dtype(plugin: "Precision") -> torch.dtype: + # TODO: integrate this into the precision plugins + from lightning_fabric.plugins import ( + BitsandbytesPrecision, + DeepSpeedPrecision, + DoublePrecision, + FSDPPrecision, + HalfPrecision, + MixedPrecision, + Precision, + TransformerEnginePrecision, + XLAPrecision, + ) + + if not isinstance(plugin, Precision): + raise RuntimeError(f"Expected a precision plugin, got {plugin}") + if isinstance(plugin, BitsandbytesPrecision): + return plugin.dtype + if isinstance(plugin, (HalfPrecision, MixedPrecision)): + return plugin._desired_input_dtype + if isinstance(plugin, DoublePrecision): + return torch.double + if isinstance(plugin, (XLAPrecision, DeepSpeedPrecision)): + return plugin._desired_dtype + if isinstance(plugin, TransformerEnginePrecision): + return torch.int8 + if isinstance(plugin, FSDPPrecision): + return plugin.mixed_precision_config.reduce_dtype or torch.float32 + if isinstance(plugin, Precision): + return torch.float32 + raise NotImplementedError(plugin) + + +T = TypeVar("T", bound=float) + + +class _MonotonicWindow(list[T]): + """Custom fixed size list that only supports right-append and ensures that all values increase monotonically.""" + + def __init__(self, maxlen: int) -> None: + super().__init__() + self.maxlen = maxlen + + @property + def last(self) -> Optional[T]: + if len(self) > 0: + return self[-1] + return None + + @override + def append(self, x: T) -> None: + last = self.last + if last is not None and last >= x: + raise ValueError(f"Expected the value to increase, last: {last}, current: {x}") + list.append(self, x) + # truncate excess + if len(self) > self.maxlen: + del self[0] + + @override + def __setitem__(self, key: Any, value: Any) -> None: + # assigning is not implemented since we don't use it. it could be by checking all previous values + raise NotImplementedError("__setitem__ is not supported") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/types.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/types.py new file mode 100644 index 0000000000000000000000000000000000000000..365ecbcefcb425cc0b5019c70ea2a973cadbf8f1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/types.py @@ -0,0 +1,90 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from collections import defaultdict +from collections.abc import Iterator +from pathlib import Path +from typing import ( + Any, + Callable, + Optional, + Protocol, + TypeVar, + Union, + runtime_checkable, +) + +import torch +from torch import Tensor +from typing_extensions import TypeAlias, overload + +UntypedStorage: TypeAlias = torch.UntypedStorage + +_PATH = Union[str, Path] +_DEVICE = Union[torch.device, str, int] +_MAP_LOCATION_TYPE = Optional[ + Union[_DEVICE, Callable[[UntypedStorage, str], Optional[UntypedStorage]], dict[_DEVICE, _DEVICE]] +] +_PARAMETERS = Iterator[torch.nn.Parameter] + +if torch.distributed.is_available(): + from torch.distributed import ProcessGroup, ReduceOp + + RedOpType: TypeAlias = ReduceOp.RedOpType +else: + ProcessGroup = Any # type: ignore[assignment,misc] + ReduceOp = RedOpType = object # type: ignore[assignment,misc] # we are using isinstance check once + +_DictKey = TypeVar("_DictKey") + + +@runtime_checkable +class _Stateful(Protocol[_DictKey]): + """This class is used to detect if an object is stateful using `isinstance(obj, _Stateful)`.""" + + def state_dict(self) -> dict[_DictKey, Any]: ... + + def load_state_dict(self, state_dict: dict[_DictKey, Any]) -> None: ... + + +@runtime_checkable +class CollectibleGroup(Protocol): + def size(self) -> int: ... + + def rank(self) -> int: ... + + +@runtime_checkable +class Steppable(Protocol): + """To structurally type ``optimizer.step()``""" + + @overload + def step(self, closure: None = ...) -> None: ... + + @overload + def step(self, closure: Callable[[], float]) -> float: ... + + def step(self, closure: Optional[Callable[[], float]] = ...) -> Optional[float]: ... + + +@runtime_checkable +class Optimizable(Steppable, Protocol): + """To structurally type ``optimizer``""" + + param_groups: list[dict[Any, Any]] + defaults: dict[Any, Any] + state: defaultdict[Tensor, Any] + + def state_dict(self) -> dict[str, dict[Any, Any]]: ... + + def load_state_dict(self, state_dict: dict[str, dict[Any, Any]]) -> None: ... diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/warnings.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..ec505bd66233f718c65b68e81eeac33657c2ecd3 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/utilities/warnings.py @@ -0,0 +1,59 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Warning-related utilities.""" + +import warnings +from pathlib import Path +from typing import Optional, Union + +from lightning_fabric.utilities.rank_zero import LightningDeprecationWarning + +# enable our warnings +warnings.simplefilter("default", category=LightningDeprecationWarning) +_default_format_warning = warnings.formatwarning + + +def disable_possible_user_warnings(module: str = "") -> None: + """Ignore warnings of the category ``PossibleUserWarning`` from Lightning. + + For more granular control over which warnings to ignore, use :func:`warnings.filterwarnings` directly. + + Args: + module: Name of the module for which the warnings should be ignored (e.g., ``'pytorch_lightning.strategies'``). + Default: Disables warnings from all modules. + + """ + warnings.filterwarnings("ignore", module=module, category=PossibleUserWarning) + + +def _custom_format_warning( + message: Union[Warning, str], category: type[Warning], filename: str, lineno: int, line: Optional[str] = None +) -> str: + """Custom formatting that avoids an extra line in case warnings are emitted from the `rank_zero`-functions.""" + if _is_path_in_lightning(Path(filename)): + # The warning originates from the Lightning package + return f"{filename}:{lineno}: {message}\n" + return _default_format_warning(message, category, filename, lineno, line) + + +warnings.formatwarning = _custom_format_warning + + +class PossibleUserWarning(UserWarning): + """Warnings that could be false positives.""" + + +def _is_path_in_lightning(path: Path) -> bool: + """Naive check whether the path looks like a path from the lightning package.""" + return "lightning" in str(path.absolute()) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/version.info b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/version.info new file mode 100644 index 0000000000000000000000000000000000000000..57cf282ebbc41ec4cd51601733bc26d60c2341d4 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/version.info @@ -0,0 +1 @@ +2.6.5 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/wrappers.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..ded7bd8d101dd584eac7bdd358d9c53308012c5f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_fabric/wrappers.py @@ -0,0 +1,416 @@ +# Copyright The Lightning AI team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import inspect +from collections.abc import Generator, Iterator, Mapping +from copy import deepcopy +from functools import partial, wraps +from types import MethodType +from typing import ( + Any, + Callable, + Optional, + TypeVar, + Union, + overload, +) + +import torch +from lightning_utilities import is_overridden +from lightning_utilities.core.apply_func import apply_to_collection +from torch import Tensor +from torch import nn as nn +from torch._dynamo import OptimizedModule +from torch.nn.modules.module import _IncompatibleKeys +from torch.optim import Optimizer +from torch.utils.data import DataLoader +from typing_extensions import override + +from lightning_fabric.plugins import Precision +from lightning_fabric.strategies import Strategy +from lightning_fabric.utilities import move_data_to_device +from lightning_fabric.utilities.data import _set_sampler_epoch +from lightning_fabric.utilities.device_dtype_mixin import _DeviceDtypeModuleMixin +from lightning_fabric.utilities.types import Optimizable + +T_destination = TypeVar("T_destination", bound=dict[str, Any]) +_LIGHTNING_MODULE_STEP_METHODS = ("training_step", "validation_step", "test_step", "predict_step") + +_in_fabric_backward: bool = False + + +class _FabricOptimizer: + def __init__(self, optimizer: Optimizer, strategy: Strategy, callbacks: Optional[list[Callable]] = None) -> None: + """FabricOptimizer is a thin wrapper around the :class:`~torch.optim.Optimizer` that delegates the optimizer + step calls to the strategy. + + The underlying wrapped optimizer object can be accessed via the property :attr:`optimizer`. + + Args: + optimizer: The optimizer to wrap + strategy: Reference to the strategy for handling the optimizer step + + """ + self._optimizer = optimizer + self._strategy = strategy + self._callbacks = callbacks or [] + # imitate the class of the wrapped object to make isinstance checks work + self.__class__ = type("Fabric" + optimizer.__class__.__name__, (self.__class__, optimizer.__class__), {}) + + @property + def optimizer(self) -> Optimizer: + return self._optimizer + + def state_dict(self) -> dict[str, Tensor]: + return self._strategy.get_optimizer_state(self.optimizer) + + def load_state_dict(self, state_dict: dict[str, Tensor]) -> None: + self.optimizer.load_state_dict(state_dict) + + def step(self, closure: Optional[Callable] = None) -> Any: + kwargs = {"closure": closure} if closure is not None else {} + if hasattr(self._strategy, "model") and isinstance(self._strategy.model, Optimizable): + # only DeepSpeed defines this + optimizer = self._strategy.model + else: + optimizer = self.optimizer + output = self._strategy.optimizer_step( + optimizer, + **kwargs, + ) + for callback in self._callbacks: + hook = getattr(callback, "on_after_optimizer_step", None) + if callable(hook): + hook(strategy=self._strategy, optimizer=optimizer) + return output + + def __getattr__(self, item: Any) -> Any: + return getattr(self._optimizer, item) + + +class _FabricModule(_DeviceDtypeModuleMixin): + def __init__( + self, forward_module: nn.Module, strategy: Strategy, original_module: Optional[nn.Module] = None + ) -> None: + """The FabricModule is a thin wrapper around the :class:`torch.nn.Module` and handles precision / autocast + automatically for the forward pass. + + The underlying wrapped module can be accessed via the property :attr:`module`. + + Args: + forward_module: The module to wrap the ``forward`` method on. + strategy: Reference to the strategy for handling precision etc. + original_module: The original, unmodified module as passed into the + :meth:`lightning_fabric.fabric.Fabric.setup` method. This is needed when attribute lookup + on this wrapper should pass through to the original module. + + """ + super().__init__() + self._forward_module = forward_module + self._original_module = forward_module if original_module is None else original_module + self._strategy = strategy + self._forward_methods = set(_LIGHTNING_MODULE_STEP_METHODS) + self._fabric_module_initialized = True + + @property + def module(self) -> nn.Module: + return self._original_module or self._forward_module + + @override + def forward(self, *args: Any, **kwargs: Any) -> Any: + """Casts all inputs to the right precision and handles autocast for operations in the module forward method.""" + precision = self._strategy.precision + args, kwargs = precision.convert_input((args, kwargs)) + + with precision.forward_context(): + output = self._forward_module(*args, **kwargs) + + output = precision.convert_output(output) + + apply_to_collection(output, dtype=Tensor, function=self._register_backward_hook) + return output + + @overload + def state_dict(self, *, destination: T_destination, prefix: str = ..., keep_vars: bool = ...) -> T_destination: ... + + @overload + def state_dict(self, *, prefix: str = ..., keep_vars: bool = ...) -> dict[str, Any]: ... + + @override + def state_dict( + self, destination: Optional[T_destination] = None, prefix: str = "", keep_vars: bool = False + ) -> Optional[dict[str, Any]]: + return self._original_module.state_dict( + destination=destination, # type: ignore[type-var] + prefix=prefix, + keep_vars=keep_vars, + ) + + @override + def load_state_dict( # type: ignore[override] + self, state_dict: Mapping[str, Any], strict: bool = True, **kwargs: Any + ) -> _IncompatibleKeys: + return self._original_module.load_state_dict(state_dict=state_dict, strict=strict, **kwargs) + + def mark_forward_method(self, method: Union[MethodType, str]) -> None: + """Mark a method as a 'forward' method to prevent it bypassing the strategy wrapper (e.g., DDP).""" + if not isinstance(method, (MethodType, str)): + raise TypeError(f"Expected a method or a string, but got: {type(method).__name__}") + name = method if isinstance(method, str) else method.__name__ + if name == "forward": + raise ValueError("You cannot mark the forward method itself as a forward method.") + if not isinstance(getattr(self._original_module, name, None), MethodType): + raise AttributeError( + f"You marked '{name}' as a forward method, but `{type(self._original_module).__name__}.{name}` does not" + f" exist or is not a method." + ) + self._forward_methods.add(name) + + def _redirection_through_forward(self, method_name: str) -> Callable: + assert method_name != "forward" + original_forward = self._original_module.forward + + def wrapped_forward(*args: Any, **kwargs: Any) -> Any: + # Unpatch ourselves immediately before calling the method `method_name` + # because itself may want to call the real `forward` + self._original_module.forward = original_forward + # Call the actual method e.g. `.training_step(...)` + method = getattr(self._original_module, method_name) + return method(*args, **kwargs) + + # We make the caller "unknowingly" send their arguments through the forward_module's `__call__`. + # We expect that the `forward_module` will eventually call `original_module.forward`, which we + # have patched to redirect back to `original_module.method_name()`. + def call_forward_module(*args: Any, **kwargs: Any) -> Any: + # Patch the original_module's forward, so we can redirect the arguments back to the real method + self._original_module.forward = wrapped_forward + return self.forward(*args, **kwargs) + + return call_forward_module + + def _wrap_method_with_module_call_tracker(self, method: Callable, name: str) -> Callable: + """Tracks whether any submodule in ``self._original_module`` was called during the execution of ``method`` by + registering forward hooks on all submodules.""" + module_called = False + + def hook(*_: Any, **__: Any) -> None: + nonlocal module_called + module_called = True + + @wraps(method) + def _wrapped_method(*args: Any, **kwargs: Any) -> Any: + handles = [] + for module in self._original_module.modules(): + handles.append(module.register_forward_hook(hook)) + + output = method(*args, **kwargs) + + if module_called: + raise RuntimeError( + f"You are calling the method `{type(self._original_module).__name__}.{name}()` from outside the" + " model. To avoid issues with the currently selected strategy, explicitly mark it as a" + f" forward method with `fabric_model.mark_forward_method({name!r})` after `fabric.setup()`." + ) + for handle in handles: + handle.remove() + return output + + return _wrapped_method + + def _register_backward_hook(self, tensor: Tensor) -> Tensor: + if not tensor.requires_grad: + return tensor + + strategy_requires = is_overridden("backward", self._strategy, parent=Strategy) + precision_requires = any( + is_overridden(method, self._strategy.precision, parent=Precision) + for method in ("pre_backward", "backward", "post_backward") + ) + hook = partial(_backward_hook, (strategy_requires or precision_requires)) + tensor.register_hook(hook) + return tensor + + @override + def __getattr__(self, item: Any) -> Any: + if ( + item != "_forward_methods" + and item in self._forward_methods + and self._forward_module != self._original_module + ): + # Special support for methods marked by `mark_forward_method` to prevent bypassing DDP's forward + return self._redirection_through_forward(item) + + try: + # __getattr__ gets called as a last resort if the attribute does not exist + # call nn.Module's implementation first + return super().__getattr__(item) + except AttributeError: + # If the attribute is not available on the _FabricModule wrapper, redirect to the wrapped nn.Module + original_module = super().__getattr__("_original_module") + attr = getattr(original_module, item) + + if inspect.ismethod(attr) and self._forward_module != self._original_module: + attr = self._wrap_method_with_module_call_tracker(attr, item) + return attr + + @override + def __setattr__(self, name: str, value: Any) -> None: + if not getattr(self, "_fabric_module_initialized", False): + super().__setattr__(name, value) + return + + # Get the _original_module attribute + original_module = self._original_module + original_has_attr = hasattr(original_module, name) + # Can't use super().__getattr__ because nn.Module only checks _parameters, _buffers, and _modules + # Can't use self.__getattr__ because it would pass through to the original module + fabric_has_attr = name in dir(self) + + if not (original_has_attr or fabric_has_attr): + setattr(original_module, name, value) + return + + # The original module can also inherit from _DeviceDtypeModuleMixin, + # in this case, both the Fabric module and original module have attributes like _dtype + # set attribute on both + if original_has_attr: + setattr(original_module, name, value) + + if fabric_has_attr: + super().__setattr__(name, value) + + +class _FabricDataLoader: + def __init__(self, dataloader: DataLoader, device: Optional[torch.device] = None) -> None: + """The FabricDataLoader is a wrapper for the :class:`~torch.utils.data.DataLoader`. It moves the data to the + device automatically if the device is specified. + + Args: + dataloader: The dataloader to wrap + device: The device to which the data should be moved. By default the device is `None` and no data + transfers will be made (identical behavior as :class:`~torch.utils.data.DataLoader`). + + """ + self.__dict__.update(dataloader.__dict__) + self._dataloader = dataloader + self._device = device + self._num_iter_calls = 0 + + @property + def device(self) -> Optional[torch.device]: + return self._device + + def __len__(self) -> int: + return len(self._dataloader) + + def __iter__(self) -> Union[Iterator[Any], Generator[Any, None, None]]: + # Without setting the epoch, the distributed sampler would return the same indices every time, even when + # shuffling is enabled. In PyTorch, the user would normally have to call `.set_epoch()` on the sampler. + # In Fabric, we take care of this boilerplate code. + _set_sampler_epoch(self._dataloader, self._num_iter_calls) + self._num_iter_calls += 1 + + if self._device is None: + yield from iter(self._dataloader) + else: + for item in self._dataloader: + yield move_data_to_device(item, self._device) + + +def _unwrap_objects(collection: Any) -> Any: + def _unwrap( + obj: Union[_FabricModule, _FabricOptimizer, _FabricDataLoader], + ) -> Union[nn.Module, Optimizer, DataLoader]: + if isinstance(unwrapped := _unwrap_compiled(obj)[0], _FabricModule): + return _unwrap_compiled(unwrapped._forward_module)[0] + if isinstance(obj, _FabricOptimizer): + return obj.optimizer + if isinstance(obj, _FabricDataLoader): + return obj._dataloader + return obj + + types = [_FabricModule, _FabricOptimizer, _FabricDataLoader] + types.append(OptimizedModule) + + return apply_to_collection(collection, dtype=tuple(types), function=_unwrap) + + +def _unwrap_compiled(obj: Union[Any, OptimizedModule]) -> tuple[Union[Any, nn.Module], Optional[dict[str, Any]]]: + """Removes the :class:`torch._dynamo.OptimizedModule` around the object if it is wrapped. + + Use this function before instance checks against e.g. :class:`_FabricModule`. + + """ + if isinstance(obj, OptimizedModule): + if (compile_kwargs := getattr(obj, "_compile_kwargs", None)) is None: + raise RuntimeError( + "Failed to determine the arguments that were used to compile the module. Make sure to import" + " lightning before `torch.compile` is used." + ) + return obj._orig_mod, compile_kwargs + return obj, None + + +def _to_compiled(module: nn.Module, compile_kwargs: dict[str, Any]) -> OptimizedModule: + return torch.compile(module, **compile_kwargs) # type: ignore[return-value] + + +def _backward_hook(requires_backward: bool, *_: Any) -> None: + if requires_backward and not _in_fabric_backward: + raise RuntimeError( + "The current strategy and precision selection requires you to call `fabric.backward(loss)`" + " instead of `loss.backward()`." + ) + + +def is_wrapped(obj: object) -> bool: + """Checks if an object was set up by Fabric. + + A :class:`~torch.nn.Module` may be wrapped by a :class:`_FabricModule`, a :class:`~torch.optim.Optimizer` + may be wrapped by a :class:`_FabricOptimizer`, or a :class:`~torch.utils.data.DataLoader` may be wrapped by + :class:`_FabricDataLoader`. + + Args: + obj: The object to test. + + """ + obj, _ = _unwrap_compiled(obj) + return isinstance(obj, (_FabricModule, _FabricOptimizer, _FabricDataLoader)) + + +def _capture_compile_kwargs(compile_fn: Callable) -> Callable: + """Wraps the ``torch.compile`` function and captures the compile arguments. + + We extract the compile arguments so that we can reapply ``torch.compile`` in ``Fabric.setup()`` with the + same arguments as the user passed to the original call. The arguments get stored in a dictionary + ``_compile_kwargs`` on the returned compiled module. + + """ + # Limitation: Currently, the global compile config does not get captured on a per-model basis. + # PyTorch will resolve this in the future: https://github.com/pytorch/pytorch/issues/116575 + + @wraps(compile_fn) + def _capture(*args: Any, **kwargs: Any) -> Any: + if not args or not isinstance(args[0], nn.Module): + # either torch.compile is being applied as a decorator or we're compiling something else + return compile_fn(*args, **kwargs) + + model = args[0] + compiled_model = compile_fn(model, **kwargs) + compiled_model._compile_kwargs = deepcopy(kwargs) + return compiled_model + + return _capture + + +torch.compile = _capture_compile_kwargs(torch.compile) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/INSTALLER b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/METADATA b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..d9b8caa4bfa2acbfd2560144b74815bf40b167ee --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/METADATA @@ -0,0 +1,191 @@ +Metadata-Version: 2.4 +Name: lightning-utilities +Version: 0.15.3 +Summary: Lightning toolbox for across the our ecosystem. +Home-page: https://github.com/Lightning-AI/utilities +Download-URL: https://github.com/Lightning-AI/utilities +Author: Lightning AI et al. +Author-email: developer@lightning.ai +License: Apache-2.0 +Project-URL: Bug Tracker, https://github.com/Lightning-AI/utilities/issues +Project-URL: Documentation, https://dev-toolbox.rtfd.io/en/latest/ +Project-URL: Source Code, https://github.com/Lightning-AI/utilities +Keywords: Utilities,DevOps,CI/CD +Classifier: Environment :: Console +Classifier: Natural Language :: English +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: packaging>=22 +Requires-Dist: typing_extensions +Provides-Extra: typing +Requires-Dist: mypy>=1.0.0; extra == "typing" +Requires-Dist: types-setuptools; extra == "typing" +Provides-Extra: docs +Requires-Dist: requests>=2.0.0; extra == "docs" +Provides-Extra: cli +Requires-Dist: jsonargparse[signatures]>=4.38.0; extra == "cli" +Requires-Dist: tomlkit; extra == "cli" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: download-url +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: project-url +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +# Lightning Utilities + +[![PyPI Status](https://badge.fury.io/py/lightning-utilities.svg)](https://badge.fury.io/py/lightning-utilities) +[![license](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/Lightning-AI/utilities/blob/main/LICENSE) +[![PyPI - Downloads](https://img.shields.io/pypi/dm/lightning-utilities)](https://pepy.tech/project/lightning-utilities) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/lightning-utilities)](https://pypi.org/project/lightning-utilities/) + +[![UnitTests](https://github.com/Lightning-AI/utilities/actions/workflows/ci-testing.yml/badge.svg?event=push)](https://github.com/Lightning-AI/utilities/actions/workflows/ci-testing.yml) +[![Apply checks](https://github.com/Lightning-AI/utilities/actions/workflows/ci-use-checks.yaml/badge.svg?event=push)](https://github.com/Lightning-AI/utilities/actions/workflows/ci-use-checks.yaml) +[![Docs Status](https://readthedocs.org/projects/lit-utilities/badge/?version=latest)](https://lit-utilities.readthedocs.io/en/latest/?badge=latest) +[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/Lightning-AI/utilities/main.svg)](https://results.pre-commit.ci/latest/github/Lightning-AI/utilities/main) + +__This repository covers the following use-cases:__ + +1. _Reusable GitHub workflows_ +2. _Shared GitHub actions_ +3. _General Python utilities in `lightning_utilities.core`_ +4. _CLI `python -m lightning_utilities.cli --help`_ + +## 1. Reusable workflows + +__Usage:__ + +```yaml +name: Check schema + +on: [push] + +jobs: + + check-schema: + uses: Lightning-AI/utilities/.github/workflows/check-schema.yml@v0.5.0 + with: + azure-dir: "" # skip Azure check + + check-code: + uses: Lightning-AI/utilities/.github/workflows/check-code.yml@main + with: + actions-ref: main # normally you shall use the same version as the workflow +``` + +See usage of other workflows in [.github/workflows/ci-use-checks.yaml](https://github.com/Lightning-AI/utilities/tree/main/.github/workflows/ci-use-checks.yaml). + +## 2. Reusable composite actions + +See available composite actions [.github/actions/](https://github.com/Lightning-AI/utilities/tree/main/.github/actions). + +__Usage:__ + +```yaml +name: Do something with cache + +on: [push] + +jobs: + pytest: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: 3.10 + - uses: Lightning-AI/utilities/.github/actions/cache + with: + python-version: 3.10 + requires: oldest # or latest +``` + +## 3. General Python utilities `lightning_utilities.core` + +
+ Installation +From source: + +```bash +pip install https://github.com/Lightning-AI/utilities/archive/refs/heads/main.zip +``` + +From pypi: + +```bash +pip install lightning_utilities +``` + +
+ +__Usage:__ + +Example for optional imports: + +```python +from lightning_utilities.core.imports import module_available + +if module_available("some_package.something"): + from some_package import something +``` + +## 4. CLI `lightning_utilities.cli` + +The package provides common CLI commands. + +
+ Installation + +From pypi: + +```bash +pip install lightning_utilities[cli] +``` + +
+ +__Usage:__ + +```bash +python -m lightning_utilities.cli [group] [command] +``` + +
+ Example for setting min versions + +```console +$ cat requirements/test.txt +coverage>=5.0 +codecov>=2.1 +pytest>=6.0 +pytest-cov +pytest-timeout +$ python -m lightning_utilities.cli requirements set-oldest +$ cat requirements/test.txt +coverage==5.0 +codecov==2.1 +pytest==6.0 +pytest-cov +pytest-timeout +``` + +
diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/RECORD b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..fca80fbfc4d4d84ee5a03e1688ed3f44d87f8cf4 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/RECORD @@ -0,0 +1,46 @@ +lightning_utilities-0.15.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +lightning_utilities-0.15.3.dist-info/METADATA,sha256=rHAu7ZPR3pvGZwKnGTDYM7_kS1nWoxgCXnUuKLuvHiY,5511 +lightning_utilities-0.15.3.dist-info/RECORD,, +lightning_utilities-0.15.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +lightning_utilities-0.15.3.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91 +lightning_utilities-0.15.3.dist-info/licenses/LICENSE,sha256=pB4vrpkVrlYCj429C_J5lfGQdhPLzS2BphsBCtNOn-k,11349 +lightning_utilities-0.15.3.dist-info/top_level.txt,sha256=bv1jgJg-r8O6G6ljv5WbFK74IvX-S44ynneEzRkWmyQ,20 +lightning_utilities/__about__.py,sha256=gOMeshg_rVDn-W-ycP6j2NjvQvyrRgBQjTSp37tNvgc,652 +lightning_utilities/__init__.py,sha256=vWUDdYAdKlx5QE67ZpQLxBSCcXJfoEDO7llXndv94Vk,650 +lightning_utilities/__pycache__/__about__.cpython-312.pyc,, +lightning_utilities/__pycache__/__init__.cpython-312.pyc,, +lightning_utilities/cli/__init__.py,sha256=A8Ys2MpS7DjQkKyKuuoNW2ltDfsZz4htAmUFG00Abr8,16 +lightning_utilities/cli/__main__.py,sha256=27vhe5hr0sTvvTfI2kjwCMRqkGyf3-DH4R6wk_uiC9Y,1071 +lightning_utilities/cli/__pycache__/__init__.cpython-312.pyc,, +lightning_utilities/cli/__pycache__/__main__.cpython-312.pyc,, +lightning_utilities/cli/__pycache__/dependencies.cpython-312.pyc,, +lightning_utilities/cli/dependencies.py,sha256=6ihm3Yb3cUD4vcMOz5NcbjWTVn8-pe0MUnVUqOMdWAE,7199 +lightning_utilities/core/__init__.py,sha256=tj8S9tr0eDnhdeA6jX53TBIbwQS6LdXusXWihqyzuzk,487 +lightning_utilities/core/__pycache__/__init__.cpython-312.pyc,, +lightning_utilities/core/__pycache__/apply_func.cpython-312.pyc,, +lightning_utilities/core/__pycache__/enums.cpython-312.pyc,, +lightning_utilities/core/__pycache__/imports.cpython-312.pyc,, +lightning_utilities/core/__pycache__/inheritance.cpython-312.pyc,, +lightning_utilities/core/__pycache__/overrides.cpython-312.pyc,, +lightning_utilities/core/__pycache__/rank_zero.cpython-312.pyc,, +lightning_utilities/core/apply_func.py,sha256=3_ZDcSJDE4A-aa9ACBSW6jWejvW1DFb1rNPjcvIQGfE,12270 +lightning_utilities/core/enums.py,sha256=GSwqpZ-nSmV7TLfkmsp_uo1Uf0UJgl34MXCVHIp_Eww,3238 +lightning_utilities/core/imports.py,sha256=w4AaDBfNnSDZ8nonTLX4g-7nOfXToqAu_yU5cuaOKNw,12562 +lightning_utilities/core/inheritance.py,sha256=MHzgmsLH9D7JdKShD1EmSs-9DpquljnmwJdKkNI4Ykw,701 +lightning_utilities/core/overrides.py,sha256=a9C6coTEA-StYXNbEF90VUC9oNFHWZ3ig88WVHfsmVg,1826 +lightning_utilities/core/rank_zero.py,sha256=sNlCT_7Uquxf18GJClMzpdUxSQmU03cZtqhAGbNAs_s,4179 +lightning_utilities/docs/__init__.py,sha256=jSBSm8AS3bZRLoSwQAPYMhKLatJOKUQsh0e3Dak5YHk,244 +lightning_utilities/docs/__pycache__/__init__.cpython-312.pyc,, +lightning_utilities/docs/__pycache__/formatting.cpython-312.pyc,, +lightning_utilities/docs/__pycache__/retriever.cpython-312.pyc,, +lightning_utilities/docs/formatting.py,sha256=2B46JnGTXK4HldGqg9bafwFfYtdN5ktwFtPIKoZOHGw,7269 +lightning_utilities/docs/retriever.py,sha256=H0YSiDc_a-GOhIRCdER7YO4QQw1HM8EktWJl-iF_GjM,4219 +lightning_utilities/install/__init__.py,sha256=kJypQkcv_QOK9mlI3cqhN6W9zGQWCimcV1m_rMdNMFU,167 +lightning_utilities/install/__pycache__/__init__.cpython-312.pyc,, +lightning_utilities/install/__pycache__/requirements.cpython-312.pyc,, +lightning_utilities/install/requirements.py,sha256=1EDeKshxBnvfkyWLrXwEq6Oyd3EYnNIJAujsp_Qez0M,8260 +lightning_utilities/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +lightning_utilities/test/__init__.py,sha256=aO-ZHCHwBH06mKNp72dc95ncwjgC_LQSf8gXm3JqF7g,37 +lightning_utilities/test/__pycache__/__init__.cpython-312.pyc,, +lightning_utilities/test/__pycache__/warning.cpython-312.pyc,, +lightning_utilities/test/warning.py,sha256=bIz65eu1gTzxwHAzlE24lfVPJadc3APJAUlPxD27oYM,1036 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/REQUESTED b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/WHEEL b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1ef5583317a5e59140e3f1c85c2db91aec0961e8 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/licenses/LICENSE b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2e66bec2e791c2dfa1f8d9bd205180fc06ffc053 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018-2021 William Falcon + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/top_level.txt b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5771e5125f762575b817ec688861c9a0dbde8c7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities-0.15.3.dist-info/top_level.txt @@ -0,0 +1 @@ +lightning_utilities diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__about__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__about__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7a78abc89ade9b6595d3c6aca53bdf886026e43 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__about__.py @@ -0,0 +1,23 @@ +import time + +__version__ = "0.15.3" +__author__ = "Lightning AI et al." +__author_email__ = "developer@lightning.ai" +__license__ = "Apache-2.0" +__copyright__ = f"Copyright (c) 2022-{time.strftime('%Y')}, {__author__}." +__homepage__ = "https://github.com/Lightning-AI/utilities" +__docs__ = "Lightning toolbox for across the our ecosystem." +__long_doc__ = """ +This package allows for sharing GitHub workflows, CI/CD assistance actions, and Python utilities across the Lightning +ecosystem - projects. +""" + +__all__ = [ + "__author__", + "__author_email__", + "__copyright__", + "__docs__", + "__homepage__", + "__license__", + "__version__", +] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..48e39c6df1de65ade7fc3aa72f00823e3fecd0a3 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__init__.py @@ -0,0 +1,23 @@ +"""Root package info.""" + +import os + +from lightning_utilities.__about__ import * # noqa: F403 +from lightning_utilities.core.apply_func import apply_to_collection +from lightning_utilities.core.enums import StrEnum +from lightning_utilities.core.imports import compare_version, module_available +from lightning_utilities.core.overrides import is_overridden +from lightning_utilities.core.rank_zero import WarningCache + +_PACKAGE_ROOT = os.path.dirname(__file__) +_PROJECT_ROOT = os.path.dirname(_PACKAGE_ROOT) + + +__all__ = [ + "StrEnum", + "WarningCache", + "apply_to_collection", + "compare_version", + "is_overridden", + "module_available", +] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__pycache__/__about__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__pycache__/__about__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3c3a4bc6cb74b39f34290d57c398164294c07b9 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__pycache__/__about__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15a4f9ea7c60f684e95a60317e862f22cfe5e943 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5be9d8843cb5d54f397cff9e07d777f4729dfc6 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__init__.py @@ -0,0 +1 @@ +"""CLI root.""" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__main__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..47ceb6f553336f46bf320b03b035ad30926f8811 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__main__.py @@ -0,0 +1,39 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# + +import lightning_utilities +from lightning_utilities.cli.dependencies import ( + prune_packages_in_requirements, + replace_oldest_version, + replace_package_in_requirements, +) + + +def _get_version() -> None: + """Prints the version of the lightning_utilities package.""" + print(lightning_utilities.__version__) + + +def main() -> None: + """CLI entry point.""" + from jsonargparse import auto_cli, set_parsing_settings + + set_parsing_settings(parse_optionals_as_positionals=True) + auto_cli( + { + "requirements": { + "_help": "Manage requirements files.", + "prune-pkgs": prune_packages_in_requirements, + "set-oldest": replace_oldest_version, + "replace-pkg": replace_package_in_requirements, + }, + "version": _get_version, + }, + as_positional=False, + ) + + +if __name__ == "__main__": + main() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52dc6a42c608cf2c4ba4a16920d4a88bc95585b9 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__pycache__/__main__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f67aa5444859e47a953c7f2f8fda47fbc265702 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__pycache__/__main__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__pycache__/dependencies.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__pycache__/dependencies.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..399fcb39aa27d9c3514d45e3dfdf4fff2a9d27d5 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/__pycache__/dependencies.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/dependencies.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..d0467ed1dfd8ad1ba8c29f0cefb3f4e757c1c4d2 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/cli/dependencies.py @@ -0,0 +1,206 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import glob +import os.path +import re +import warnings +from collections.abc import Sequence +from pprint import pprint +from typing import Union + +REQUIREMENT_ROOT = "requirements.txt" +REQUIREMENT_FILES_ALL: list = glob.glob(os.path.join("requirements", "*.txt")) +REQUIREMENT_FILES_ALL += glob.glob(os.path.join("requirements", "**", "*.txt"), recursive=True) +REQUIREMENT_FILES_ALL += glob.glob(os.path.join("**", "pyproject.toml")) +if os.path.isfile(REQUIREMENT_ROOT): + REQUIREMENT_FILES_ALL += [REQUIREMENT_ROOT] + + +def prune_packages_in_requirements( + packages: Union[str, Sequence[str]], req_files: Union[str, Sequence[str]] = REQUIREMENT_FILES_ALL +) -> None: + """Remove one or more packages from the specified requirement files. + + Args: + packages: A package name or list of package names to remove. + req_files: A path or list of paths to requirement files to process. + + """ + if isinstance(packages, str): + packages = [packages] + if isinstance(req_files, str): + req_files = [req_files] + for req in req_files: + _prune_packages(req, packages) + + +def _prune_packages(req_file: str, packages: Sequence[str]) -> None: + """Remove all occurrences of the given packages (by line prefix) from a requirements file. + + Args: + req_file: Path to a requirements file. + packages: Package names to remove. Lines starting with any of these names will be dropped. + + """ + with open(req_file) as fp: + lines = fp.readlines() + + if isinstance(packages, str): + packages = [packages] + for pkg in packages: + lines = [ln for ln in lines if not ln.startswith(pkg)] + pprint(lines) + + with open(req_file, "w") as fp: + fp.writelines(lines) + + +def _replace_min_req_in_txt(req_file: str) -> None: + """Replace all occurrences of '>=' with '==' in a plain text requirements file. + + Args: + req_file: Path to the requirements.txt-like file to update. + + """ + with open(req_file) as fopen: + req = fopen.read().replace(">=", "==") + with open(req_file, "w") as fw: + fw.write(req) + + +def _replace_min_req_in_pyproject_toml(proj_file: str = "pyproject.toml") -> None: + """Replace all '>=' with '==' in the [project.dependencies] section of a standard pyproject.toml. + + Preserves formatting and comments using tomlkit. + + Args: + proj_file: Path to the pyproject.toml file. + + """ + import tomlkit + + # Load and parse the existing pyproject.toml + with open(proj_file, encoding="utf-8") as f: + content = f.read() + doc = tomlkit.parse(content) + + # todo: consider also replace extras in [dependency-groups] -> extras = [...] + deps = doc.get("project", {}).get("dependencies") + if not deps: + return + + # Replace '>=version' with '==version' in each dependency + for i, req in enumerate(deps): + # Simple string value + deps[i] = req.replace(">=", "==") + + # Dump back out, preserving layout + with open(proj_file, "w", encoding="utf-8") as f: + f.write(tomlkit.dumps(doc)) + + +def replace_oldest_version(req_files: Union[str, Sequence[str]] = REQUIREMENT_FILES_ALL) -> None: + """Convert minimal version specifiers (>=) to pinned ones (==) in the given requirement files. + + Supports plain *.txt requirements and pyproject.toml files. Unsupported file types trigger a warning. + + Args: + req_files: A path or list of paths to requirement files to process. + + """ + if isinstance(req_files, str): + req_files = [req_files] + for fname in req_files: + if fname.endswith(".txt"): + _replace_min_req_in_txt(fname) + elif os.path.basename(fname) == "pyproject.toml": + _replace_min_req_in_pyproject_toml(fname) + else: + warnings.warn( + "Only *.txt with plain list of requirements or standard pyproject.toml are supported." + f"Provided '{fname}' is not supported.", + UserWarning, + stacklevel=2, + ) + + +def _replace_package_name_in_txt(req_file: str, old_package: str, new_package: str) -> None: + """Rename a package in a plain text requirements file, preserving version specifiers and markers. + + Args: + req_file: Path to the requirements.txt-like file to update. + old_package: The original package name to replace. + new_package: The new package name to use. + + """ + # load file + with open(req_file) as fopen: + requirements = fopen.readlines() + # replace all occurrences + for i, req in enumerate(requirements): + requirements[i] = re.sub(r"^" + re.escape(old_package) + r"(?=[ <=>#]|$)", new_package, req) + # save file + with open(req_file, "w") as fw: + fw.writelines(requirements) + + +def _replace_package_name_in_pyproject_toml(proj_file: str, old_package: str, new_package: str) -> None: + """Rename a package in the [project.dependencies] section of a standard pyproject.toml, preserving constraints. + + Args: + proj_file: Path to the pyproject.toml file. + old_package: The original package name to replace. + new_package: The new package name to use. + + """ + import tomlkit + + # Load and parse the existing pyproject.toml + with open(proj_file, encoding="utf-8") as f: + content = f.read() + doc = tomlkit.parse(content) + + # todo: consider also replace extras in [dependency-groups] -> extras = [...] + deps = doc.get("project", {}).get("dependencies") + if not deps: + return + + # Replace '>=version' with '==version' in each dependency + for i, req in enumerate(deps): + # Simple string value + deps[i] = re.sub(r"^" + re.escape(old_package) + r"(?=[ <=>]|$)", new_package, req) + + # Dump back out, preserving layout + with open(proj_file, "w", encoding="utf-8") as f: + f.write(tomlkit.dumps(doc)) + + +def replace_package_in_requirements( + old_package: str, new_package: str, req_files: Union[str, Sequence[str]] = REQUIREMENT_FILES_ALL +) -> None: + """Rename a package across multiple requirement files while keeping version constraints intact. + + Supports plain *.txt requirements and pyproject.toml files. Unsupported file types trigger a warning. + + Args: + old_package: The original package name to replace. + new_package: The new package name to use. + req_files: A path or list of paths to requirement files to process. + + """ + if isinstance(req_files, str): + req_files = [req_files] + for fname in req_files: + if fname.endswith(".txt"): + _replace_package_name_in_txt(fname, old_package, new_package) + elif os.path.basename(fname) == "pyproject.toml": + _replace_package_name_in_pyproject_toml(fname, old_package, new_package) + else: + warnings.warn( + "Only *.txt with plain list of requirements or standard pyproject.toml are supported." + f"Provided '{fname}' is not supported.", + UserWarning, + stacklevel=2, + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dd046496fa9df05e4ebf5ea8802287f0fe609482 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__init__.py @@ -0,0 +1,16 @@ +"""Core utilities.""" + +from lightning_utilities.core.apply_func import apply_to_collection +from lightning_utilities.core.enums import StrEnum +from lightning_utilities.core.imports import compare_version, module_available +from lightning_utilities.core.overrides import is_overridden +from lightning_utilities.core.rank_zero import WarningCache + +__all__ = [ + "StrEnum", + "WarningCache", + "apply_to_collection", + "compare_version", + "is_overridden", + "module_available", +] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c072470ac426724cbfe918677c8fb1516f31756 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/apply_func.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/apply_func.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..819dacd89eeb573be1f739d12b43849ba2b20193 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/apply_func.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/enums.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/enums.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb211f3b860edb420e388b87ed05c3260e294bc8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/enums.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/imports.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/imports.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d63cd402c2ae71af0befa824d11d22b68c35147 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/imports.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/inheritance.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/inheritance.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b22367289c598e86a69410512f76bf22d4cb8c07 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/inheritance.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/overrides.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90bfe469adb754986e1b664259a880c224f9ba71 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/overrides.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/rank_zero.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/rank_zero.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb92343cf6e4bc49b6696b4135d7f342899b1503 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/__pycache__/rank_zero.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/apply_func.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/apply_func.py new file mode 100644 index 0000000000000000000000000000000000000000..2c9765e59cc73c55d3e781af722556dc6a6c711f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/apply_func.py @@ -0,0 +1,303 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import dataclasses +from collections import OrderedDict, defaultdict +from collections.abc import Mapping, Sequence +from copy import deepcopy +from functools import cached_property +from typing import Any, Callable, Optional, Union + + +def is_namedtuple(obj: object) -> bool: + """Return True if the given object is a namedtuple instance. + + This checks for a tuple with the namedtuple-specific attributes `_asdict` and `_fields`. + + """ + # https://github.com/pytorch/pytorch/blob/v1.8.1/torch/nn/parallel/scatter_gather.py#L4-L8 + return isinstance(obj, tuple) and hasattr(obj, "_asdict") and hasattr(obj, "_fields") + + +def is_dataclass_instance(obj: object) -> bool: + """Return True if the given object is a dataclass instance (not a dataclass type).""" + # https://docs.python.org/3/library/dataclasses.html#module-level-decorators-classes-and-functions + return dataclasses.is_dataclass(obj) and not isinstance(obj, type) + + +def apply_to_collection( + data: Any, + dtype: Union[type, Any, tuple[Union[type, Any]]], + function: Callable, + *args: Any, + wrong_dtype: Optional[Union[type, tuple[type, ...]]] = None, + include_none: bool = True, + allow_frozen: bool = False, + **kwargs: Any, +) -> Any: + """Recursively applies a function to all elements of a certain dtype. + + Args: + data: the collection to apply the function to + dtype: the given function will be applied to all elements of this dtype + function: the function to apply + *args: positional arguments (will be forwarded to calls of ``function``) + wrong_dtype: the given function won't be applied if this type is specified and the given collections + is of the ``wrong_dtype`` even if it is of type ``dtype`` + include_none: Whether to include an element if the output of ``function`` is ``None``. + allow_frozen: Whether not to error upon encountering a frozen dataclass instance. + **kwargs: keyword arguments (will be forwarded to calls of ``function``) + + Returns: + The resulting collection + + """ + if include_none is False or wrong_dtype is not None or allow_frozen is True: + # not worth implementing these on the fast path: go with the slower option + return _apply_to_collection_slow( + data, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + include_none=include_none, + allow_frozen=allow_frozen, + **kwargs, + ) + # fast path for the most common cases: + if isinstance(data, dtype): # single element + return function(data, *args, **kwargs) + if data.__class__ is list and all(isinstance(x, dtype) for x in data): # 1d homogeneous list + return [function(x, *args, **kwargs) for x in data] + if data.__class__ is tuple and all(isinstance(x, dtype) for x in data): # 1d homogeneous tuple + return tuple(function(x, *args, **kwargs) for x in data) + if data.__class__ is dict and all(isinstance(x, dtype) for x in data.values()): # 1d homogeneous dict + return {k: function(v, *args, **kwargs) for k, v in data.items()} + # slow path for everything else + return _apply_to_collection_slow( + data, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + include_none=include_none, + allow_frozen=allow_frozen, + **kwargs, + ) + + +def _apply_to_collection_slow( + data: Any, + dtype: Union[type, Any, tuple[Union[type, Any]]], + function: Callable, + *args: Any, + wrong_dtype: Optional[Union[type, tuple[type, ...]]] = None, + include_none: bool = True, + allow_frozen: bool = False, + **kwargs: Any, +) -> Any: + # Breaking condition + if isinstance(data, dtype) and (wrong_dtype is None or not isinstance(data, wrong_dtype)): + return function(data, *args, **kwargs) + + elem_type = type(data) + + # Recursively apply to collection items + if is_dataclass_instance(data): + # make a deepcopy of the data, + # but do not deepcopy mapped fields since the computation would + # be wasted on values that likely get immediately overwritten + fields = {} + memo = {} + for field in dataclasses.fields(data): + field_value = getattr(data, field.name) + fields[field.name] = (field_value, field.init) + memo[id(field_value)] = field_value + result = deepcopy(data, memo=memo) + # apply function to each field + for field_name, (field_value, field_init) in fields.items(): + v = None + if field_init: + v = _apply_to_collection_slow( + field_value, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + include_none=include_none, + allow_frozen=allow_frozen, + **kwargs, + ) + if not field_init or (not include_none and v is None): # retain old value + v = getattr(data, field_name) + try: + setattr(result, field_name, v) + except dataclasses.FrozenInstanceError as e: + if allow_frozen: + # Quit early if we encounter a frozen data class; return `result` as is. + break + raise ValueError( + "A frozen dataclass was passed to `apply_to_collection` but this is not allowed." + ) from e + + # Explicitly resetting cached property. + for cached_name in filter( + lambda k: isinstance(getattr(type(data), k), cached_property), vars(type(data)).keys() + ): + vars(result).pop(cached_name, None) + return result + + if isinstance(data, Mapping): + out = [] + for k, v in data.items(): + v = _apply_to_collection_slow( + v, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + include_none=include_none, + allow_frozen=allow_frozen, + **kwargs, + ) + if include_none or v is not None: + out.append((k, v)) + if isinstance(data, defaultdict): + return elem_type(data.default_factory, OrderedDict(out)) + return elem_type(OrderedDict(out)) + + is_namedtuple_ = is_namedtuple(data) + is_sequence = isinstance(data, Sequence) and not isinstance(data, str) + if is_namedtuple_ or is_sequence: + out = [] + for d in data: + v = _apply_to_collection_slow( + d, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + include_none=include_none, + allow_frozen=allow_frozen, + **kwargs, + ) + if include_none or v is not None: + out.append(v) + return elem_type(*out) if is_namedtuple_ else elem_type(out) + + # data is neither of dtype, nor a collection + return data + + +def apply_to_collections( + data1: Optional[Any], + data2: Optional[Any], + dtype: Union[type, Any, tuple[Union[type, Any]]], + function: Callable, + *args: Any, + wrong_dtype: Optional[Union[type, tuple[type]]] = None, + **kwargs: Any, +) -> Any: + """Zip two collections and apply a function to items of a certain dtype. + + Args: + data1: The first collection. If ``None`` and ``data2`` is not ``None``, the arguments are swapped. + data2: The second collection. May be ``None`` to apply ``function`` only to ``data1``. + dtype: The type(s) for which the given ``function`` will be applied to matching elements. + function: The function to apply to matching elements. + *args: Positional arguments forwarded to calls of ``function``. + wrong_dtype: If specified, ``function`` won't be applied to elements of this type even if they match ``dtype``. + **kwargs: Keyword arguments forwarded to calls of ``function``. + + Returns: + A collection with the same structure as the input where matching elements are transformed. + + Raises: + ValueError: If sequence collections have different sizes. + TypeError: If dataclass inputs are mismatched (different types or fields), or if ``data1`` is a + dataclass instance but ``data2`` is not. + + """ + if data1 is None: + if data2 is None: + return None + # in case they were passed reversed + data1, data2 = data2, None + + elem_type = type(data1) + + if isinstance(data1, dtype) and data2 is not None and (wrong_dtype is None or not isinstance(data1, wrong_dtype)): + return function(data1, data2, *args, **kwargs) + + if isinstance(data1, Mapping) and data2 is not None: + # use union because we want to fail if a key does not exist in both + zipped = {k: (data1[k], data2[k]) for k in data1.keys() | data2.keys()} + return elem_type({ + k: apply_to_collections(*v, dtype, function, *args, wrong_dtype=wrong_dtype, **kwargs) + for k, v in zipped.items() + }) + + is_namedtuple_ = is_namedtuple(data1) + is_sequence = isinstance(data1, Sequence) and not isinstance(data1, str) + if (is_namedtuple_ or is_sequence) and data2 is not None: + if len(data1) != len(data2): + raise ValueError("Sequence collections have different sizes.") + out = [ + apply_to_collections(v1, v2, dtype, function, *args, wrong_dtype=wrong_dtype, **kwargs) + for v1, v2 in zip(data1, data2) + ] + return elem_type(*out) if is_namedtuple_ else elem_type(out) + + if is_dataclass_instance(data1) and data2 is not None: + if not is_dataclass_instance(data2): + raise TypeError( + "Expected inputs to be dataclasses of the same type or to have identical fields" + f" but got input 1 of type {type(data1)} and input 2 of type {type(data2)}." + ) + if not ( + len(dataclasses.fields(data1)) == len(dataclasses.fields(data2)) + and all(map(lambda f1, f2: isinstance(f1, type(f2)), dataclasses.fields(data1), dataclasses.fields(data2))) + ): + raise TypeError("Dataclasses fields do not match.") + # make a deepcopy of the data, + # but do not deepcopy mapped fields since the computation would + # be wasted on values that likely get immediately overwritten + data = [data1, data2] + fields: list[dict] = [{}, {}] + memo: dict = {} + for i in range(len(data)): + for field in dataclasses.fields(data[i]): + field_value = getattr(data[i], field.name) + fields[i][field.name] = (field_value, field.init) + if i == 0: + memo[id(field_value)] = field_value + + result = deepcopy(data1, memo=memo) + + # apply function to each field + for (field_name, (field_value1, field_init1)), (_, (field_value2, field_init2)) in zip( + fields[0].items(), fields[1].items() + ): + v = None + if field_init1 and field_init2: + v = apply_to_collections( + field_value1, + field_value2, + dtype, + function, + *args, + wrong_dtype=wrong_dtype, + **kwargs, + ) + if not field_init1 or not field_init2 or v is None: # retain old value + return apply_to_collection(data1, dtype, function, *args, wrong_dtype=wrong_dtype, **kwargs) + try: + setattr(result, field_name, v) + except dataclasses.FrozenInstanceError as e: + raise ValueError( + "A frozen dataclass was passed to `apply_to_collections` but this is not allowed." + ) from e + return result + + return apply_to_collection(data1, dtype, function, *args, wrong_dtype=wrong_dtype, **kwargs) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/enums.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..7d4ce60b7011d57ee978591a9e15266e9a8048b7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/enums.py @@ -0,0 +1,91 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import warnings +from enum import Enum +from typing import Optional + +from typing_extensions import Literal + + +class StrEnum(str, Enum): + """Type of any enumerator with allowed comparison to string invariant to cases. + + >>> class MySE(StrEnum): + ... t1 = "T-1" + ... t2 = "T-2" + >>> MySE("T-1") == MySE.t1 + True + >>> MySE.from_str("t-2", source="value") == MySE.t2 + True + >>> MySE.from_str("t-2", source="value") + + >>> MySE.from_str("t-3", source="any") + Traceback (most recent call last): + ... + ValueError: Invalid match: expected one of ['t1', 't2', 'T-1', 'T-2'], but got t-3. + + """ + + @classmethod + def from_str(cls, value: str, source: Literal["key", "value", "any"] = "key") -> "StrEnum": + """Create ``StrEnum`` from a string matching the key or value. + + Args: + value: matching string + source: compare with: + + - ``"key"``: validates only from the enum keys, typical alphanumeric with "_" + - ``"value"``: validates only from the values, could be any string + - ``"any"``: validates with any key or value, but key has priority + + Raises: + ValueError: + if requested string does not match any option based on selected source. + + """ + if source in ("key", "any"): + for enum_key in cls.__members__: + if enum_key.lower() == value.lower(): + return cls[enum_key] + if source in ("value", "any"): + for enum_key, enum_val in cls.__members__.items(): + if enum_val == value: + return cls[enum_key] + raise ValueError(f"Invalid match: expected one of {cls._allowed_matches(source)}, but got {value}.") + + @classmethod + def try_from_str(cls, value: str, source: Literal["key", "value", "any"] = "key") -> Optional["StrEnum"]: + """Try to create the enum; if no match is found, emit a warning and return ``None``.""" + try: + return cls.from_str(value, source) + except ValueError: + warnings.warn( # noqa: B028 + UserWarning(f"Invalid string: expected one of {cls._allowed_matches(source)}, but got {value}.") + ) + return None + + @classmethod + def _allowed_matches(cls, source: str) -> list[str]: + keys, vals = [], [] + for enum_key, enum_val in cls.__members__.items(): + keys.append(enum_key) + vals.append(enum_val.value) + if source == "key": + return keys + if source == "value": + return vals + return keys + vals + + def __eq__(self, other: object) -> bool: + """Compare two instances.""" + if isinstance(other, Enum): + other = other.value + return self.value.lower() == str(other).lower() + + def __hash__(self) -> int: + """Return unique hash.""" + # re-enable hashtable, so it can be used as a dict key or in a set + # example: set(LightningEnum) + return hash(self.value.lower()) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/imports.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/imports.py new file mode 100644 index 0000000000000000000000000000000000000000..e9af9e4d361698dcb8a7813823879df3ba1f735c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/imports.py @@ -0,0 +1,362 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 + +import functools +import importlib +import os +import warnings +from functools import lru_cache +from importlib.metadata import PackageNotFoundError, distribution +from importlib.metadata import version as _version +from importlib.util import find_spec +from types import ModuleType +from typing import Any, Callable, Optional, TypeVar + +from packaging.requirements import Requirement +from packaging.version import InvalidVersion, Version +from typing_extensions import ParamSpec + +T = TypeVar("T") +P = ParamSpec("P") + +try: + from importlib import metadata +except ImportError: + # Python < 3.8 + import importlib_metadata as metadata # type: ignore + + +@lru_cache +def package_available(package_name: str) -> bool: + """Check if a package is available in your environment. + + >>> package_available('os') + True + >>> package_available('bla') + False + + """ + try: + return find_spec(package_name) is not None + except ModuleNotFoundError: + return False + + +@lru_cache +def module_available(module_path: str) -> bool: + """Check if a module path is available in your environment. + + >>> module_available('os') + True + >>> module_available('os.bla') + False + >>> module_available('bla.bla') + False + + """ + module_names = module_path.split(".") + if not package_available(module_names[0]): + return False + try: + importlib.import_module(module_path) + except ImportError: + return False + return True + + +def compare_version(package: str, op: Callable, version: str, use_base_version: bool = False) -> bool: + """Compare package version with some requirements. + + >>> compare_version("torch", operator.ge, "0.1") + True + >>> compare_version("does_not_exist", operator.ge, "0.0") + False + + """ + try: + pkg = importlib.import_module(package) + except (ImportError, RuntimeError): + return False + try: + # Use importlib.metadata to infer version + pkg_version = Version(pkg.__version__) if hasattr(pkg, "__version__") else Version(_version(package)) + except (TypeError, PackageNotFoundError): + # this is mocked by Sphinx, so it should return True to generate all summaries + return True + if use_base_version: + pkg_version = Version(pkg_version.base_version) + return op(pkg_version, Version(version)) + + +class RequirementCache: + """Boolean-like class to check for requirement and module availability. + + Args: + requirement: The requirement to check, version specifiers are allowed. + module: The optional module to try to import if the requirement check fails. + + >>> RequirementCache("torch>=0.1") + Requirement 'torch>=0.1' met + >>> bool(RequirementCache("torch>=0.1")) + True + >>> bool(RequirementCache("torch>100.0")) + False + >>> RequirementCache("torch") + Requirement 'torch' met + >>> bool(RequirementCache("torch")) + True + >>> bool(RequirementCache("unknown_package")) + False + >>> bool(RequirementCache(module="torch.utils")) + True + >>> bool(RequirementCache(module="unknown_package")) + False + >>> bool(RequirementCache(module="unknown.module.path")) + False + + """ + + def __init__(self, requirement: Optional[str] = None, module: Optional[str] = None) -> None: + if not (requirement or module): + raise ValueError("At least one arguments need to be set.") + self.requirement = requirement + self.module = module + + def _check_requirement(self) -> None: + if not self.requirement: + raise ValueError("Requirement name is required.") + try: + req = Requirement(self.requirement) + pkg_version = Version(_version(req.name)) + self.available = req.specifier.contains(pkg_version, prereleases=True) and ( + not req.extras or self._check_extras_available(req) + ) + except (PackageNotFoundError, InvalidVersion) as ex: + self.available = False + self.message = f"{ex.__class__.__name__}: {ex}. HINT: Try running `pip install -U {self.requirement!r}`" + + if self.available: + self.message = f"Requirement {self.requirement!r} met" + else: + req_include_version = any(c in self.requirement for c in "=<>") + if not req_include_version or self.module is not None: + module = self.requirement if self.module is None else self.module + # Sometimes `importlib.metadata.version` fails but the module is importable + self.available = module_available(module) + if self.available: + self.message = f"Module {module!r} available" + self.message = ( + f"Requirement {self.requirement!r} not met. HINT: Try running `pip install -U {self.requirement!r}`" + ) + + def _check_module(self) -> None: + if not self.module: + raise ValueError("Module name is required.") + self.available = module_available(self.module) + if self.available: + self.message = f"Module {self.module!r} available" + else: + self.message = f"Module not found: {self.module!r}. HINT: Try running `pip install -U {self.module}`" + + def _check_available(self) -> None: + if hasattr(self, "available"): + return + if self.requirement: + self._check_requirement() + if getattr(self, "available", True) and self.module: + self._check_module() + + def _check_extras_available(self, requirement: Requirement) -> bool: + if not requirement.extras: + return True + + extra_requirements = self._get_extra_requirements(requirement) + + if not extra_requirements: + # The specified extra is not found in the package metadata + return False + + # Verify each extra requirement is installed + for extra_req in extra_requirements: + try: + extra_dist = distribution(extra_req.name) + extra_installed_version = Version(extra_dist.version) + if extra_req.specifier and not extra_req.specifier.contains(extra_installed_version, prereleases=True): + return False + except importlib.metadata.PackageNotFoundError: + return False + + return True + + def _get_extra_requirements(self, requirement: Requirement) -> list[Requirement]: + dist = distribution(requirement.name) + # Get the required dependencies for the specified extras + extra_requirements = dist.metadata.get_all("Requires-Dist") or [] + return [Requirement(r) for r in extra_requirements if any(extra in r for extra in requirement.extras)] + + def __bool__(self) -> bool: + """Format as bool.""" + self._check_available() + return self.available + + def __str__(self) -> str: + """Format as string.""" + self._check_available() + return self.message + + def __repr__(self) -> str: + """Format as string.""" + return self.__str__() + + +class ModuleAvailableCache(RequirementCache): + """Boolean-like class for check of module availability. + + >>> ModuleAvailableCache("torch") + Module 'torch' available + >>> bool(ModuleAvailableCache("torch.utils")) + True + >>> bool(ModuleAvailableCache("unknown_package")) + False + >>> bool(ModuleAvailableCache("unknown.module.path")) + False + + """ + + def __init__(self, module: str) -> None: + warnings.warn( + "`ModuleAvailableCache` is a special case of `RequirementCache`." + " Please use `RequirementCache(module=...)` instead.", + DeprecationWarning, + stacklevel=4, + ) + super().__init__(module=module) + + +def get_dependency_min_version_spec(package_name: str, dependency_name: str) -> str: + """Return the minimum version specifier of a dependency of a package. + + >>> get_dependency_min_version_spec("pytorch-lightning==1.8.0", "jsonargparse") + '>=4.12.0' + + """ + dependencies = metadata.requires(package_name) or [] + for dep in dependencies: + dependency = Requirement(dep) + if dependency.name == dependency_name: + spec = [str(s) for s in dependency.specifier if str(s)[0] == ">"] + return spec[0] if spec else "" + raise ValueError( + "This is an internal error. Please file a GitHub issue with the error message. Dependency " + f"{dependency_name!r} not found in package {package_name!r}." + ) + + +class LazyModule(ModuleType): + """Proxy module that lazily imports the underlying module the first time it is actually used. + + Args: + module_name: the fully-qualified module name to import + callback: a callback function to call before importing the module + + """ + + def __init__(self, module_name: str, callback: Optional[Callable] = None) -> None: + super().__init__(module_name) + self._module: Any = None + self._callback = callback + + def __getattr__(self, item: str) -> Any: + """Lazily import the underlying module and delegate attribute access to it.""" + if self._module is None: + self._import_module() + + return getattr(self._module, item) + + def __dir__(self) -> list[str]: + """Lazily import the underlying module and return its attributes for introspection (dir()).""" + if self._module is None: + self._import_module() + + return dir(self._module) + + def _import_module(self) -> None: + # Execute callback, if any + if self._callback is not None: + self._callback() + + # Actually import the module + self._module = importlib.import_module(self.__name__) + + # Update this object's dict so that attribute references are efficient + # (__getattr__ is only called on lookups that fail) + self.__dict__.update(self._module.__dict__) + + +def lazy_import(module_name: str, callback: Optional[Callable] = None) -> LazyModule: + """Return a proxy module object that will lazily import the given module the first time it is used. + + Example usage: + + # Lazy version of `import tensorflow as tf` + tf = lazy_import("tensorflow") + # Other commands + # Now the module is loaded + tf.__version__ + + Args: + module_name: the fully-qualified module name to import + callback: a callback function to call before importing the module + + Returns: + a proxy module object that will be lazily imported when first used + + """ + return LazyModule(module_name, callback=callback) + + +def requires(*module_path_version: str, raise_exception: bool = True) -> Callable[[Callable[P, T]], Callable[P, T]]: + """Decorator to check optional dependencies at call time with a clear error/warning message. + + Args: + module_path_version: Python module paths (e.g., ``"torch.cuda"``) and/or pip-style requirements + (e.g., ``"torch>=2.0.0"``) to verify. + raise_exception: If ``True``, raise ``ModuleNotFoundError`` when requirements are not satisfied; + otherwise emit a warning and proceed to call the function. + + Example: + >>> @requires("libpath", raise_exception=bool(int(os.getenv("LIGHTING_TESTING", "0")))) + ... def my_cwd(): + ... from pathlib import Path + ... return Path(__file__).parent + + >>> class MyRndPower: + ... @requires("math", "random") + ... def __init__(self): + ... from math import pow + ... from random import randint + ... self._rnd = pow(randint(1, 9), 2) + + """ + + def decorator(func: Callable[P, T]) -> Callable[P, T]: + reqs = [ + ModuleAvailableCache(mod_ver) if "." in mod_ver else RequirementCache(mod_ver) + for mod_ver in module_path_version + ] + available = all(map(bool, reqs)) + + @functools.wraps(func) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: + if not available: + missing = os.linesep.join([repr(r) for r in reqs if not bool(r)]) + msg = f"Required dependencies not available: \n{missing}" + if raise_exception: + raise ModuleNotFoundError(msg) + warnings.warn(msg, stacklevel=2) + return func(*args, **kwargs) + + return wrapper + + return decorator diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/inheritance.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/inheritance.py new file mode 100644 index 0000000000000000000000000000000000000000..d7fb4d913aef0087a30febd167e020f693cc1127 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/inheritance.py @@ -0,0 +1,21 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +from collections.abc import Iterator + + +def get_all_subclasses_iterator(cls: type) -> Iterator[type]: + """Depth-first iterator over all subclasses of ``cls`` (recursively).""" + + def recurse(cl: type) -> Iterator[type]: + for subclass in cl.__subclasses__(): + yield subclass + yield from recurse(subclass) + + yield from recurse(cls) + + +def get_all_subclasses(cls: type) -> set[type]: + """Return a set containing all subclasses of ``cls`` discovered recursively.""" + return set(get_all_subclasses_iterator(cls)) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/overrides.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..31899a4fecdf9cd0712db0ba6e4f824666f45c0e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/overrides.py @@ -0,0 +1,48 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +from functools import partial +from unittest.mock import Mock + + +def is_overridden(method_name: str, instance: object, parent: type[object]) -> bool: + """Return True if ``instance`` overrides ``parent.method_name``. + + Supports functions wrapped with ``functools.wraps``, context managers (``__wrapped__``), + ``unittest.mock.Mock(wraps=...)``, and ``functools.partial``. If the parent does not define + ``method_name``, a ``ValueError`` is raised. + + Args: + method_name: The name of the method to check. + instance: The object instance to inspect. + parent: The parent class that declares the original method. + + Returns: + True if the method implementation on the instance differs from the parent's; otherwise False. + + """ + instance_attr = getattr(instance, method_name, None) + if instance_attr is None: + return False + # `functools.wraps()` and `@contextmanager` support + if hasattr(instance_attr, "__wrapped__"): + instance_attr = instance_attr.__wrapped__ + # `Mock(wraps=...)` support + if isinstance(instance_attr, Mock): + # access the wrapped function + instance_attr = instance_attr._mock_wraps + # `partial` support + elif isinstance(instance_attr, partial): + instance_attr = instance_attr.func + if instance_attr is None: + return False + + parent_attr = getattr(parent, method_name, None) + if parent_attr is None: + raise ValueError("The parent should define the method") + # `@contextmanager` support + if hasattr(parent_attr, "__wrapped__"): + parent_attr = parent_attr.__wrapped__ + + return instance_attr.__code__ != parent_attr.__code__ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/rank_zero.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/rank_zero.py new file mode 100644 index 0000000000000000000000000000000000000000..13d15deb070f7603f1c4c831992122a927c4e34f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/core/rank_zero.py @@ -0,0 +1,116 @@ +# Copyright The Lightning AI team. +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +"""Utilities that can be used for calling functions on a particular rank.""" + +import logging +import warnings +from functools import wraps +from typing import Any, Callable, Optional, TypeVar, Union + +from typing_extensions import ParamSpec, overload + +log = logging.getLogger(__name__) + +T = TypeVar("T") +P = ParamSpec("P") + + +@overload +def rank_zero_only(fn: Callable[P, T]) -> Callable[P, Optional[T]]: ... + + +@overload +def rank_zero_only(fn: Callable[P, T], default: T) -> Callable[P, T]: ... + + +def rank_zero_only(fn: Callable[P, T], default: Optional[T] = None) -> Callable[P, Optional[T]]: + """Decorator to run the wrapped function only on global rank 0. + + Set ``rank_zero_only.rank`` before use. On non-zero ranks, the function is skipped and the provided + ``default`` is returned (or ``None`` if not given). + + """ + + @wraps(fn) + def wrapped_fn(*args: P.args, **kwargs: P.kwargs) -> Optional[T]: + rank = getattr(rank_zero_only, "rank", None) + if rank is None: + raise RuntimeError("The `rank_zero_only.rank` needs to be set before use") + if rank == 0: + return fn(*args, **kwargs) + return default + + return wrapped_fn + + +def _debug(*args: Any, stacklevel: int = 2, **kwargs: Any) -> None: + kwargs["stacklevel"] = stacklevel + log.debug(*args, **kwargs) + + +@rank_zero_only +def rank_zero_debug(*args: Any, stacklevel: int = 4, **kwargs: Any) -> None: + """Emit debug-level messages only on global rank 0.""" + _debug(*args, stacklevel=stacklevel, **kwargs) + + +def _info(*args: Any, stacklevel: int = 2, **kwargs: Any) -> None: + kwargs["stacklevel"] = stacklevel + log.info(*args, **kwargs) + + +@rank_zero_only +def rank_zero_info(*args: Any, stacklevel: int = 4, **kwargs: Any) -> None: + """Emit info-level messages only on global rank 0.""" + _info(*args, stacklevel=stacklevel, **kwargs) + + +def _warn(message: Union[str, Warning], stacklevel: int = 2, **kwargs: Any) -> None: + warnings.warn(message, stacklevel=stacklevel, **kwargs) + + +@rank_zero_only +def rank_zero_warn(message: Union[str, Warning], stacklevel: int = 4, **kwargs: Any) -> None: + """Emit warn-level messages only on global rank 0.""" + _warn(message, stacklevel=stacklevel, **kwargs) + + +rank_zero_deprecation_category = DeprecationWarning + + +def rank_zero_deprecation(message: Union[str, Warning], stacklevel: int = 5, **kwargs: Any) -> None: + """Emit a deprecation warning only on global rank 0.""" + category = kwargs.pop("category", rank_zero_deprecation_category) + rank_zero_warn(message, stacklevel=stacklevel, category=category, **kwargs) + + +def rank_prefixed_message(message: str, rank: Optional[int]) -> str: + """Add a ``[rank: X]`` prefix to the message if ``rank`` is provided; otherwise return the message unchanged.""" + if rank is not None: + # specify the rank of the process being logged + return f"[rank: {rank}] {message}" + return message + + +class WarningCache(set): + """A simple de-duplication cache for messages to avoid emitting the same warning/info multiple times.""" + + def warn(self, message: str, stacklevel: int = 5, **kwargs: Any) -> None: + """Emit a warning once on global rank 0; subsequent identical messages are suppressed.""" + if message not in self: + self.add(message) + rank_zero_warn(message, stacklevel=stacklevel, **kwargs) + + def deprecation(self, message: str, stacklevel: int = 6, **kwargs: Any) -> None: + """Emit a deprecation warning once on global rank 0; subsequent identical messages are suppressed.""" + if message not in self: + self.add(message) + rank_zero_deprecation(message, stacklevel=stacklevel, **kwargs) + + def info(self, message: str, stacklevel: int = 5, **kwargs: Any) -> None: + """Emit an info-level log once on global rank 0; subsequent identical messages are suppressed.""" + if message not in self: + self.add(message) + rank_zero_info(message, stacklevel=stacklevel, **kwargs) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..093cce5c583ebcbf63bbce34a67c55f0a8d5458c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__init__.py @@ -0,0 +1,6 @@ +"""General tools for Docs.""" + +from lightning_utilities.docs.formatting import adjust_linked_external_docs +from lightning_utilities.docs.retriever import fetch_external_assets + +__all__ = ["adjust_linked_external_docs", "fetch_external_assets"] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2454a02cba945495f519a3953638e698bd4e36e0 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__pycache__/formatting.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__pycache__/formatting.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e65f9f6b58a23b67234eba12a05b2dbe02730bf0 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__pycache__/formatting.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__pycache__/retriever.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__pycache__/retriever.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b4ffe246870f03ad2c0642afe1c5c4b2695e1d1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/__pycache__/retriever.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/formatting.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..126efc0efc2929781bc62ccaf5a2efaf46d4b3c5 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/formatting.py @@ -0,0 +1,187 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import glob +import importlib +import inspect +import logging +import os +import re +import sys +from collections.abc import Iterable +from typing import Optional, Union + + +def _transform_changelog(path_in: str, path_out: str) -> None: + """Adjust changelog headers to avoid duplication of short subtitles. + + Args: + path_in: Input Markdown file path. + path_out: Output Markdown file path. + + """ + with open(path_in) as fp: + chlog_lines = fp.readlines() + # enrich short subsub-titles to be unique + chlog_ver = "" + for i, ln in enumerate(chlog_lines): + if ln.startswith("## "): + chlog_ver = ln[2:].split("-")[0].strip() + elif ln.startswith("### "): + ln = ln.replace("###", f"### {chlog_ver} -") + chlog_lines[i] = ln + with open(path_out, "w") as fp: + fp.writelines(chlog_lines) + + +def _linkcode_resolve( + domain: str, + info: dict, + github_user: str, + github_repo: str, + main_branch: str = "master", + stable_branch: str = "release/stable", +) -> str: + def find_source() -> tuple[str, int, int]: + # try to find the file and line number, based on code from numpy: + # https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L286 + obj = sys.modules[info["module"]] + for part in info["fullname"].split("."): + obj = getattr(obj, part) + fname = str(inspect.getsourcefile(obj)) + # https://github.com/rtfd/readthedocs.org/issues/5735 + if any(s in fname for s in ("readthedocs", "rtfd", "checkouts")): + # /home/docs/checkouts/readthedocs.org/user_builds/pytorch_lightning/checkouts/ + # devel/pytorch_lightning/utilities/cls_experiment.py#L26-L176 + path_top = os.path.abspath(os.path.join("..", "..", "..")) + fname = str(os.path.relpath(fname, start=path_top)) + else: + # Local build, imitate master + fname = f"{main_branch}/{os.path.relpath(fname, start=os.path.abspath('..'))}" + source, line_start = inspect.getsourcelines(obj) + return fname, line_start, line_start + len(source) - 1 + + if domain != "py" or not info["module"]: + return "" + try: + filename = "%s#L%d-L%d" % find_source() # noqa: UP031 + except Exception: + filename = info["module"].replace(".", "/") + ".py" + # import subprocess + # tag = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, + # universal_newlines=True).communicate()[0][:-1] + branch = filename.split("/")[0] + # do mapping from latest tags to master + branch = {"latest": main_branch, "stable": stable_branch}.get(branch, branch) + filename = "/".join([branch, *filename.split("/")[1:]]) + return f"https://github.com/{github_user}/{github_repo}/blob/{filename}" + + +def _load_pypi_versions(package_name: str) -> list[str]: + """Load the versions of the package from PyPI. + + >>> _load_pypi_versions("numpy") # doctest: +ELLIPSIS + ['0.9.6', '0.9.8', '1.0', ...] + >>> _load_pypi_versions("scikit-learn") # doctest: +ELLIPSIS + ['0.9', '0.10', '0.11', '0.12', ...] + + """ + import requests + from packaging.version import Version + + url = f"https://pypi.org/pypi/{package_name}/json" + data = requests.get(url, timeout=10).json() + versions = data["releases"].keys() + # filter all version which include only numbers and dots + versions = {k for k in versions if re.match(r"^\d+(\.\d+)*$", k)} + return sorted(versions, key=Version) + + +def _update_link_based_imported_package(link: str, pkg_ver: str, version_digits: Optional[int]) -> str: + """Resolve a ``{package.version}`` placeholder in a link using the latest available version. + + Args: + link: The link template containing a ``{...}`` placeholder to replace. + pkg_ver: A dotted path to resolve the version (e.g., ``"numpy.__version__"``). + version_digits: Number of version components to keep (e.g., ``2`` -> ``"1.26"``). If ``None``, keep all. + + Returns: + The link with the ``{...}`` placeholder replaced by a version string. + + """ + pkg_att = pkg_ver.split(".") + try: + ver = _load_pypi_versions(pkg_att[0])[-1] + except Exception: + # load the package with all additional sub-modules + module = importlib.import_module(".".join(pkg_att[:-1])) + # load the attribute + ver = getattr(module, pkg_att[0]) + # drop any additional context after `+` + ver = ver.split("+")[0] + # crop the version to the number of digits + ver = ".".join(ver.split(".")[:version_digits]) + # replace the version + return link.replace(f"{{{pkg_ver}}}", ver) + + +def adjust_linked_external_docs( + source_link: str, + target_link: str, + browse_folder: Union[str, Iterable[str]], + file_extensions: Iterable[str] = (".rst", ".py"), + version_digits: int = 2, +) -> None: + r"""Adjust the linked external docs to be local. + + Args: + source_link: the link to be replaced + target_link: the link to be replaced, if ``{package.version}`` is included it will be replaced accordingly + browse_folder: the location of the browsable folder + file_extensions: what kind of files shall be scanned + version_digits: for semantic versioning, how many digits to be considered + + Examples: + >>> adjust_linked_external_docs( + ... "https://numpy.org/doc/stable/", + ... "https://numpy.org/doc/{numpy.__version__}/", + ... "docs/source", + ... ) + + """ + list_files = [] + if isinstance(browse_folder, str): + browse_folder = [browse_folder] + for folder in browse_folder: + for ext in file_extensions: + list_files += glob.glob(os.path.join(folder, "**", f"*{ext}"), recursive=True) + if not list_files: + logging.warning(f'No files were listed in folder "{browse_folder}" and pattern "{file_extensions}"') + return + + # find the expression for package version in {} brackets if any, use re to find it + pkg_ver_all = re.findall(r"{(.+)}", target_link) + for pkg_ver in pkg_ver_all: + target_link = _update_link_based_imported_package(target_link, pkg_ver, version_digits) + + # replace the source link with target link + for fpath in set(list_files): + with open(fpath, encoding="UTF-8") as fopen: + lines = fopen.readlines() + found, skip = False, False + for i, ln in enumerate(lines): + # prevent the replacement its own function calls + if f"{adjust_linked_external_docs.__name__}(" in ln: + skip = True + if not skip and source_link in ln: + # replace the link if any found + lines[i] = ln.replace(source_link, target_link) + # record the found link for later write file + found = True + if skip and ")" in ln: + skip = False + if not found: + continue + logging.debug(f'links adjusting in {fpath}: "{source_link}" -> "{target_link}"') + with open(fpath, "w", encoding="UTF-8") as fw: + fw.writelines(lines) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/retriever.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..7798b1b0afc62da7445f881b58163228ddc3b847 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/docs/retriever.py @@ -0,0 +1,108 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import glob +import logging +import os +import re + +import requests + + +def _download_file(file_url: str, folder: str) -> str: + """Download a file from a URL into the given folder. + + If a file with the same name already exists, it will be overwritten. + Returns the basename of the downloaded file. Network-related exceptions from + ``requests.get`` (e.g., timeouts or connection errors) may propagate to the caller. + + """ + fname = os.path.basename(file_url) + file_path = os.path.join(folder, fname) + if os.path.isfile(file_path): + logging.warning(f'given file "{file_path}" already exists and will be overwritten with {file_url}') + # see: https://stackoverflow.com/a/34957875 + rq = requests.get(file_url, timeout=10) + with open(file_path, "wb") as outfile: + outfile.write(rq.content) + return fname + + +def _search_all_occurrences(list_files: list[str], pattern: str) -> list[str]: + """Search for all occurrences of a regular-expression pattern across files. + + Args: + list_files: The list of file paths to scan. + pattern: A regular-expression pattern to search for in each file. + + Returns: + A list with all matches found across the provided files (order preserved per file). + + """ + collected = [] + for file_path in list_files: + with open(file_path, encoding="UTF-8") as fopem: + body = fopem.read() + found = re.findall(pattern, body) + collected += found + return collected + + +def _replace_remote_with_local(file_path: str, docs_folder: str, pairs_url_path: list[tuple[str, str]]) -> None: + """Replace all matching remote URLs with local file paths in a given file. + + Args: + file_path: The file in which replacements should be performed. + docs_folder: The documentation root folder (used to compute relative paths). + pairs_url_path: Pairs of (remote_url, local_relative_path) to replace. + + """ + # drop the default/global path to the docs + relt_path = os.path.dirname(file_path).replace(docs_folder, "") + # filter the path starting with / as not empty folder names + depth = len([p for p in relt_path.split(os.path.sep) if p]) + with open(file_path, encoding="UTF-8") as fopen: + body = fopen.read() + for url, fpath in pairs_url_path: + if depth: + path_up = [".."] * depth + fpath = os.path.join(*path_up, fpath) + body = body.replace(url, fpath) + with open(file_path, "w", encoding="UTF-8") as fw: + fw.write(body) + + +def fetch_external_assets( + docs_folder: str = "docs/source", + assets_folder: str = "fetched-s3-assets", + file_pattern: str = "*.rst", + retrieve_pattern: str = r"https?://[-a-zA-Z0-9_]+\.s3\.[-a-zA-Z0-9()_\\+.\\/=]+", +) -> None: + """Find S3 (or HTTP) asset URLs in docs, download them locally, and rewrite references to local paths. + + Args: + docs_folder: The documentation root relative to the project. + assets_folder: Subfolder inside ``docs_folder`` used to store downloaded assets (created if missing). + file_pattern: Glob pattern of files to scan. + retrieve_pattern: Regular-expression pattern used to find remote asset URLs. + + """ + list_files = glob.glob(os.path.join(docs_folder, "**", file_pattern), recursive=True) + if not list_files: + logging.warning(f'no files were listed in folder "{docs_folder}" and pattern "{file_pattern}"') + return + + urls = _search_all_occurrences(list_files, pattern=retrieve_pattern) + if not urls: + logging.info(f"no resources/assets were match in {docs_folder} for {retrieve_pattern}") + return + target_folder = os.path.join(docs_folder, assets_folder) + os.makedirs(target_folder, exist_ok=True) + pairs_url_file = [] + for i, url in enumerate(set(urls)): + logging.info(f" >> downloading ({i}/{len(urls)}): {url}") + fname = _download_file(url, target_folder) + pairs_url_file.append((url, os.path.join(assets_folder, fname))) + + for fpath in list_files: + _replace_remote_with_local(fpath, docs_folder, pairs_url_file) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..723406a802fc66555ba8c46661e64fd438f982d2 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/__init__.py @@ -0,0 +1,5 @@ +"""Generic Installation tools.""" + +from lightning_utilities.install.requirements import Requirement, load_requirements + +__all__ = ["Requirement", "load_requirements"] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1117f9d4acac6c6dd8ad80a2e2a781fe02ec8b7a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/__pycache__/requirements.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/__pycache__/requirements.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ed1e28bda027044a9ddbee910dc38d5efc14fe0 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/__pycache__/requirements.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/requirements.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..4a06ccbad04b4769268359badd827f52613282f7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/install/requirements.py @@ -0,0 +1,192 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +"""Utilities to parse and adjust Python requirements files. + +This module parses requirement lines while preserving inline comments and pip arguments and +supports relaxing version pins based on a chosen unfreeze strategy: "none", "major", or "all". + +""" + +import re +from collections.abc import Iterable, Iterator +from pathlib import Path +from typing import Any, Optional, Union + +from packaging.requirements import Requirement +from packaging.version import Version + + +def _yield_lines(strs: Union[str, Iterable[str]]) -> Iterator[str]: + """Yield non-empty, non-comment lines from a string or iterable of strings. + + Adapted from pkg_resources.yield_lines. + + """ + if isinstance(strs, str): + strs = strs.splitlines() + for line in strs: + line = line.strip() + if line and not line.startswith("#"): + yield line + + +class _RequirementWithComment(Requirement): + """Requirement subclass that preserves an inline comment and optional pip argument. + + Attributes: + comment: The trailing comment captured from the requirement line (including the leading '# ...'). + pip_argument: A preceding pip argument line (e.g., ``"--extra-index-url ..."``) associated + with this requirement, or ``None`` if not provided. + strict: Whether the special marker ``"# strict"`` appears in ``comment`` (case-insensitive), in which case + upper bound adjustments are disabled. + + """ + + strict_string = "# strict" + + def __init__(self, *args: Any, comment: str = "", pip_argument: Optional[str] = None, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.comment = comment + if not (pip_argument is None or pip_argument): # sanity check that it's not an empty str + raise RuntimeError(f"wrong pip argument: {pip_argument}") + self.pip_argument = pip_argument + self.strict = self.strict_string in comment.lower() + + def adjust(self, unfreeze: str) -> str: + """Adjust version specifiers according to the selected unfreeze strategy. + + The special marker ``"# strict"`` in the captured comment disables any relaxation of upper bounds. + + >>> _RequirementWithComment("arrow<=1.2.2,>=1.2.0", comment="# anything").adjust("none") + 'arrow<=1.2.2,>=1.2.0' + >>> _RequirementWithComment("arrow<=1.2.2,>=1.2.0", comment="# strict").adjust("none") + 'arrow<=1.2.2,>=1.2.0 # strict' + >>> _RequirementWithComment("arrow<=1.2.2,>=1.2.0", comment="# my name").adjust("all") + 'arrow>=1.2.0' + >>> _RequirementWithComment("arrow>=1.2.0, <=1.2.2", comment="# strict").adjust("all") + 'arrow<=1.2.2,>=1.2.0 # strict' + >>> _RequirementWithComment("arrow").adjust("all") + 'arrow' + >>> _RequirementWithComment("arrow>=1.2.0, <=1.2.2", comment="# cool").adjust("major") + 'arrow<2.0,>=1.2.0' + >>> _RequirementWithComment("arrow>=1.2.0, <=1.2.2", comment="# strict").adjust("major") + 'arrow<=1.2.2,>=1.2.0 # strict' + >>> _RequirementWithComment("arrow>=1.2.0").adjust("major") + 'arrow>=1.2.0' + >>> _RequirementWithComment("arrow").adjust("major") + 'arrow' + + Args: + unfreeze: One of: + - ``"none"``: Keep all version specifiers unchanged. + - ``"major"``: Relax the upper bound to the next major version (e.g., ``<2.0``). + - ``"all"``: Drop any upper bound constraint entirely. + + Returns: + The adjusted requirement string. If strict, the original string is returned with the strict marker appended. + + """ + out = str(self) + if self.strict: + return f"{out} {self.strict_string}" + if unfreeze == "major": + for spec in self.specifier: + if spec.operator in ("<", "<="): + major = Version(spec.version).major + # replace upper bound with major version increased by one + return out.replace(f"{spec.operator}{spec.version}", f"<{int(major) + 1}.0") + elif unfreeze == "all": + for spec in self.specifier: + if spec.operator in ("<", "<="): + # drop upper bound (with or without trailing/leading comma) + upper = f"{spec.operator}{spec.version}" + result = out.replace(f"{upper},", "").replace(f",{upper}", "") + if upper in result: + result = result.replace(upper, "") + return result.strip() + elif unfreeze != "none": + raise ValueError(f"Unexpected unfreeze: {unfreeze!r} value.") + return out + + +def _parse_requirements(strs: Union[str, Iterable[str]]) -> Iterator[_RequirementWithComment]: + r"""Adapted from ``pkg_resources.parse_requirements`` to include comments and pip arguments. + + Parses a sequence or string of requirement lines, preserving trailing comments and associating any + preceding pip arguments (``--...``) with the subsequent requirement. Lines starting with ``-r`` or + containing direct URLs are ignored. + + >>> txt = ['# ignored', '', 'this # is an', '--piparg', 'example', 'foo # strict', 'thing', '-r different/file.txt'] + >>> [r.adjust('none') for r in _parse_requirements(txt)] + ['this', 'example', 'foo # strict', 'thing'] + >>> txt = '\\n'.join(txt) + >>> [r.adjust('none') for r in _parse_requirements(txt)] + ['this', 'example', 'foo # strict', 'thing'] + + Args: + strs: Either an iterable of requirement lines or a single multi-line string. + + Yields: + _RequirementWithComment: Parsed requirement objects with preserved comment and pip argument. + + """ + lines = _yield_lines(strs) + pip_argument = None + for line in lines: + # Drop comments -- a hash without a space may be in a URL. + if " #" in line: + comment_pos = line.find(" #") + line, comment = line[:comment_pos], line[comment_pos:] + else: + comment = "" + # If there is a line continuation, drop it, and append the next line. + if line.endswith("\\"): + line = line[:-1].strip() + try: + line += next(lines) + except StopIteration: + return + # If there's a pip argument, save it + if line.startswith("--"): + pip_argument = line + continue + if line.startswith("-r "): + # linked requirement files are unsupported + continue + if "@" in line or re.search("https?://", line): + # skip lines with links like `pesq @ git+https://github.com/ludlows/python-pesq` + continue + yield _RequirementWithComment(line, comment=comment, pip_argument=pip_argument) + pip_argument = None + + +def load_requirements(path_dir: str, file_name: str = "base.txt", unfreeze: str = "all") -> list[str]: + """Load, parse, and optionally relax requirement specifiers from a file. + + >>> import os + >>> from lightning_utilities import _PROJECT_ROOT + >>> path_req = os.path.join(_PROJECT_ROOT, "requirements") + >>> load_requirements(path_req, "docs.txt", unfreeze="major") # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE + ['sphinx<6.0,>=4.0', ...] + + Args: + path_dir: Directory containing the requirements file. + file_name: The requirements filename inside ``path_dir``. + unfreeze: Unfreeze strategy: ``"none"``, ``"major"``, or ``"all"`` (see ``_RequirementWithComment.adjust``). + + Returns: + A list of requirement strings adjusted according to ``unfreeze``. + + Raises: + ValueError: If ``unfreeze`` is not one of the supported options. + FileNotFoundError: If the composed path does not exist. + + """ + if unfreeze not in {"none", "major", "all"}: + raise ValueError(f'unsupported option of "{unfreeze}"') + path = Path(path_dir) / file_name + if not path.exists(): + raise FileNotFoundError(f"missing file for {(path_dir, file_name, path)}") + text = path.read_text() + return [req.adjust(unfreeze) for req in _parse_requirements(text)] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/py.typed b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2741f80aa49d03148535eb4f2af3c94364f47d81 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/__init__.py @@ -0,0 +1 @@ +"""General testing functionality.""" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..168c23e498cbc66d4f0f5410291892ecd44a2e9a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/__pycache__/warning.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/__pycache__/warning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e53ac42dc388339f474e7a7c23454437fbd4036 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/__pycache__/warning.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/warning.py b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/warning.py new file mode 100644 index 0000000000000000000000000000000000000000..bcd31486cd175e9c37e3c45ae93e9cc8b6e1784a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/lightning_utilities/test/warning.py @@ -0,0 +1,28 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# http://www.apache.org/licenses/LICENSE-2.0 +# +import re +import warnings +from collections.abc import Generator +from contextlib import contextmanager +from typing import Optional + + +@contextmanager +def no_warning_call(expected_warning: type[Warning] = Warning, match: Optional[str] = None) -> Generator: + """Assert that no matching warning is emitted within the context. + + Args: + expected_warning: The warning class (or subclass) to check for. + match: Optional regular expression to match against the warning message. + + Raises: + AssertionError: If a warning of the given type (and matching the regex, if provided) is captured. + + """ + with warnings.catch_warnings(record=True) as record: + yield + + for w in record: + if issubclass(w.category, expected_warning) and (match is None or re.compile(match).search(str(w.message))): + raise AssertionError(f"`{expected_warning.__name__}` was raised: {w.message!r}") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d628f93ee21352f1ad36ccb62f6708b1484e9a40 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__init__.py @@ -0,0 +1,13 @@ +from typing import List, Optional + +__version__ = "25.0.1" + + +def main(args: Optional[List[str]] = None) -> int: + """This is an internal API only meant for use by pip's own console scripts. + + For additional details, see https://github.com/pypa/pip/issues/7498. + """ + from pip._internal.utils.entrypoints import _wrapper + + return _wrapper(args) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/__main__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..5991326115fe5026470165b387ba2bc78bceb006 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__main__.py @@ -0,0 +1,24 @@ +import os +import sys + +# Remove '' and current working directory from the first entry +# of sys.path, if present to avoid using current directory +# in pip commands check, freeze, install, list and show, +# when invoked as python -m pip +if sys.path[0] in ("", os.getcwd()): + sys.path.pop(0) + +# If we are running from a wheel, add the wheel to sys.path +# This allows the usage python pip-*.whl/pip install pip-*.whl +if __package__ == "": + # __file__ is pip-*.whl/pip/__main__.py + # first dirname call strips of '/__main__.py', second strips off '/pip' + # Resulting path is the name of the wheel itself + # Add that to sys.path so we can import pip + path = os.path.dirname(os.path.dirname(__file__)) + sys.path.insert(0, path) + +if __name__ == "__main__": + from pip._internal.cli.main import main as _main + + sys.exit(_main()) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pip-runner__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pip-runner__.py new file mode 100644 index 0000000000000000000000000000000000000000..c633787fcedff4f145f1edfcc4e4ffc6988fe5ac --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pip-runner__.py @@ -0,0 +1,50 @@ +"""Execute exactly this copy of pip, within a different environment. + +This file is named as it is, to ensure that this module can't be imported via +an import statement. +""" + +# /!\ This version compatibility check section must be Python 2 compatible. /!\ + +import sys + +# Copied from pyproject.toml +PYTHON_REQUIRES = (3, 8) + + +def version_str(version): # type: ignore + return ".".join(str(v) for v in version) + + +if sys.version_info[:2] < PYTHON_REQUIRES: + raise SystemExit( + "This version of pip does not support python {} (requires >={}).".format( + version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES) + ) + ) + +# From here on, we can use Python 3 features, but the syntax must remain +# Python 2 compatible. + +import runpy # noqa: E402 +from importlib.machinery import PathFinder # noqa: E402 +from os.path import dirname # noqa: E402 + +PIP_SOURCES_ROOT = dirname(dirname(__file__)) + + +class PipImportRedirectingFinder: + @classmethod + def find_spec(self, fullname, path=None, target=None): # type: ignore + if fullname != "pip": + return None + + spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target) + assert spec, (PIP_SOURCES_ROOT, fullname) + return spec + + +sys.meta_path.insert(0, PipImportRedirectingFinder()) + +assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module" +runpy.run_module("pip", run_name="__main__", alter_sys=True) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34c614732514cde71cb662c8f5cdeb2346181185 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pycache__/__main__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f04f544af300448de2b5f87c2640650ab7c57ee Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pycache__/__main__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pycache__/__pip-runner__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pycache__/__pip-runner__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8665086c64411cd378e583ed411fb8d053e99af4 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/__pycache__/__pip-runner__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1a5b7f87f973b36af0ee6fbfb76ce38420f5f9d7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__init__.py @@ -0,0 +1,18 @@ +from typing import List, Optional + +from pip._internal.utils import _log + +# init_logging() must be called before any call to logging.getLogger() +# which happens at import of most modules. +_log.init_logging() + + +def main(args: Optional[List[str]] = None) -> int: + """This is preserved for old console scripts that may still be referencing + it. + + For additional details, see https://github.com/pypa/pip/issues/7498. + """ + from pip._internal.utils.entrypoints import _wrapper + + return _wrapper(args) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac48df55ba2f483de78890ddaa88f43c477843fd Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/build_env.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/build_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bd9a632569c94ba5ec15a167137eb0f329fd97d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/build_env.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/cache.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9d978e096787894dcac9f0b6d3f95cfc4f87db0 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/cache.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/configuration.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/configuration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06ac44ecc1f2a0ca1bd7e16351f7c221ae6871cd Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/configuration.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/exceptions.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c16bd41a9aee98747b98d5feff87600fa321df7 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/exceptions.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/main.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b31763b2130b6c957ee36852832967652a1d833 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/main.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/pyproject.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/pyproject.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d786d3cd9a9512426843a60adaddf4228ea21260 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/pyproject.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..850f61ea00d192bce145067002a9abd4fe633c02 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed34e3885dca74fd02d7a3489c68a18f291a9ccb Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/build_env.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/build_env.py new file mode 100644 index 0000000000000000000000000000000000000000..e8d1aca0d6ae65972bd6642b27550f339e9d711f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/build_env.py @@ -0,0 +1,322 @@ +"""Build Environment used for isolation during sdist building +""" + +import logging +import os +import pathlib +import site +import sys +import textwrap +from collections import OrderedDict +from types import TracebackType +from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Type, Union + +from pip._vendor.packaging.version import Version + +from pip import __file__ as pip_location +from pip._internal.cli.spinners import open_spinner +from pip._internal.locations import get_platlib, get_purelib, get_scheme +from pip._internal.metadata import get_default_environment, get_environment +from pip._internal.utils.logging import VERBOSE +from pip._internal.utils.packaging import get_requirement +from pip._internal.utils.subprocess import call_subprocess +from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds + +if TYPE_CHECKING: + from pip._internal.index.package_finder import PackageFinder + +logger = logging.getLogger(__name__) + + +def _dedup(a: str, b: str) -> Union[Tuple[str], Tuple[str, str]]: + return (a, b) if a != b else (a,) + + +class _Prefix: + def __init__(self, path: str) -> None: + self.path = path + self.setup = False + scheme = get_scheme("", prefix=path) + self.bin_dir = scheme.scripts + self.lib_dirs = _dedup(scheme.purelib, scheme.platlib) + + +def get_runnable_pip() -> str: + """Get a file to pass to a Python executable, to run the currently-running pip. + + This is used to run a pip subprocess, for installing requirements into the build + environment. + """ + source = pathlib.Path(pip_location).resolve().parent + + if not source.is_dir(): + # This would happen if someone is using pip from inside a zip file. In that + # case, we can use that directly. + return str(source) + + return os.fsdecode(source / "__pip-runner__.py") + + +def _get_system_sitepackages() -> Set[str]: + """Get system site packages + + Usually from site.getsitepackages, + but fallback on `get_purelib()/get_platlib()` if unavailable + (e.g. in a virtualenv created by virtualenv<20) + + Returns normalized set of strings. + """ + if hasattr(site, "getsitepackages"): + system_sites = site.getsitepackages() + else: + # virtualenv < 20 overwrites site.py without getsitepackages + # fallback on get_purelib/get_platlib. + # this is known to miss things, but shouldn't in the cases + # where getsitepackages() has been removed (inside a virtualenv) + system_sites = [get_purelib(), get_platlib()] + return {os.path.normcase(path) for path in system_sites} + + +class BuildEnvironment: + """Creates and manages an isolated environment to install build deps""" + + def __init__(self) -> None: + temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True) + + self._prefixes = OrderedDict( + (name, _Prefix(os.path.join(temp_dir.path, name))) + for name in ("normal", "overlay") + ) + + self._bin_dirs: List[str] = [] + self._lib_dirs: List[str] = [] + for prefix in reversed(list(self._prefixes.values())): + self._bin_dirs.append(prefix.bin_dir) + self._lib_dirs.extend(prefix.lib_dirs) + + # Customize site to: + # - ensure .pth files are honored + # - prevent access to system site packages + system_sites = _get_system_sitepackages() + + self._site_dir = os.path.join(temp_dir.path, "site") + if not os.path.exists(self._site_dir): + os.mkdir(self._site_dir) + with open( + os.path.join(self._site_dir, "sitecustomize.py"), "w", encoding="utf-8" + ) as fp: + fp.write( + textwrap.dedent( + """ + import os, site, sys + + # First, drop system-sites related paths. + original_sys_path = sys.path[:] + known_paths = set() + for path in {system_sites!r}: + site.addsitedir(path, known_paths=known_paths) + system_paths = set( + os.path.normcase(path) + for path in sys.path[len(original_sys_path):] + ) + original_sys_path = [ + path for path in original_sys_path + if os.path.normcase(path) not in system_paths + ] + sys.path = original_sys_path + + # Second, add lib directories. + # ensuring .pth file are processed. + for path in {lib_dirs!r}: + assert not path in sys.path + site.addsitedir(path) + """ + ).format(system_sites=system_sites, lib_dirs=self._lib_dirs) + ) + + def __enter__(self) -> None: + self._save_env = { + name: os.environ.get(name, None) + for name in ("PATH", "PYTHONNOUSERSITE", "PYTHONPATH") + } + + path = self._bin_dirs[:] + old_path = self._save_env["PATH"] + if old_path: + path.extend(old_path.split(os.pathsep)) + + pythonpath = [self._site_dir] + + os.environ.update( + { + "PATH": os.pathsep.join(path), + "PYTHONNOUSERSITE": "1", + "PYTHONPATH": os.pathsep.join(pythonpath), + } + ) + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + for varname, old_value in self._save_env.items(): + if old_value is None: + os.environ.pop(varname, None) + else: + os.environ[varname] = old_value + + def check_requirements( + self, reqs: Iterable[str] + ) -> Tuple[Set[Tuple[str, str]], Set[str]]: + """Return 2 sets: + - conflicting requirements: set of (installed, wanted) reqs tuples + - missing requirements: set of reqs + """ + missing = set() + conflicting = set() + if reqs: + env = ( + get_environment(self._lib_dirs) + if hasattr(self, "_lib_dirs") + else get_default_environment() + ) + for req_str in reqs: + req = get_requirement(req_str) + # We're explicitly evaluating with an empty extra value, since build + # environments are not provided any mechanism to select specific extras. + if req.marker is not None and not req.marker.evaluate({"extra": ""}): + continue + dist = env.get_distribution(req.name) + if not dist: + missing.add(req_str) + continue + if isinstance(dist.version, Version): + installed_req_str = f"{req.name}=={dist.version}" + else: + installed_req_str = f"{req.name}==={dist.version}" + if not req.specifier.contains(dist.version, prereleases=True): + conflicting.add((installed_req_str, req_str)) + # FIXME: Consider direct URL? + return conflicting, missing + + def install_requirements( + self, + finder: "PackageFinder", + requirements: Iterable[str], + prefix_as_string: str, + *, + kind: str, + ) -> None: + prefix = self._prefixes[prefix_as_string] + assert not prefix.setup + prefix.setup = True + if not requirements: + return + self._install_requirements( + get_runnable_pip(), + finder, + requirements, + prefix, + kind=kind, + ) + + @staticmethod + def _install_requirements( + pip_runnable: str, + finder: "PackageFinder", + requirements: Iterable[str], + prefix: _Prefix, + *, + kind: str, + ) -> None: + args: List[str] = [ + sys.executable, + pip_runnable, + "install", + "--ignore-installed", + "--no-user", + "--prefix", + prefix.path, + "--no-warn-script-location", + "--disable-pip-version-check", + # The prefix specified two lines above, thus + # target from config file or env var should be ignored + "--target", + "", + ] + if logger.getEffectiveLevel() <= logging.DEBUG: + args.append("-vv") + elif logger.getEffectiveLevel() <= VERBOSE: + args.append("-v") + for format_control in ("no_binary", "only_binary"): + formats = getattr(finder.format_control, format_control) + args.extend( + ( + "--" + format_control.replace("_", "-"), + ",".join(sorted(formats or {":none:"})), + ) + ) + + index_urls = finder.index_urls + if index_urls: + args.extend(["-i", index_urls[0]]) + for extra_index in index_urls[1:]: + args.extend(["--extra-index-url", extra_index]) + else: + args.append("--no-index") + for link in finder.find_links: + args.extend(["--find-links", link]) + + if finder.proxy: + args.extend(["--proxy", finder.proxy]) + for host in finder.trusted_hosts: + args.extend(["--trusted-host", host]) + if finder.custom_cert: + args.extend(["--cert", finder.custom_cert]) + if finder.client_cert: + args.extend(["--client-cert", finder.client_cert]) + if finder.allow_all_prereleases: + args.append("--pre") + if finder.prefer_binary: + args.append("--prefer-binary") + args.append("--") + args.extend(requirements) + with open_spinner(f"Installing {kind}") as spinner: + call_subprocess( + args, + command_desc=f"pip subprocess to install {kind}", + spinner=spinner, + ) + + +class NoOpBuildEnvironment(BuildEnvironment): + """A no-op drop-in replacement for BuildEnvironment""" + + def __init__(self) -> None: + pass + + def __enter__(self) -> None: + pass + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + pass + + def cleanup(self) -> None: + pass + + def install_requirements( + self, + finder: "PackageFinder", + requirements: Iterable[str], + prefix_as_string: str, + *, + kind: str, + ) -> None: + raise NotImplementedError() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cache.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..6b4512672dbad2766464405adb0193f12500e767 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cache.py @@ -0,0 +1,290 @@ +"""Cache Management +""" + +import hashlib +import json +import logging +import os +from pathlib import Path +from typing import Any, Dict, List, Optional + +from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.exceptions import InvalidWheelFilename +from pip._internal.models.direct_url import DirectUrl +from pip._internal.models.link import Link +from pip._internal.models.wheel import Wheel +from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds +from pip._internal.utils.urls import path_to_url + +logger = logging.getLogger(__name__) + +ORIGIN_JSON_NAME = "origin.json" + + +def _hash_dict(d: Dict[str, str]) -> str: + """Return a stable sha224 of a dictionary.""" + s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + return hashlib.sha224(s.encode("ascii")).hexdigest() + + +class Cache: + """An abstract class - provides cache directories for data from links + + :param cache_dir: The root of the cache. + """ + + def __init__(self, cache_dir: str) -> None: + super().__init__() + assert not cache_dir or os.path.isabs(cache_dir) + self.cache_dir = cache_dir or None + + def _get_cache_path_parts(self, link: Link) -> List[str]: + """Get parts of part that must be os.path.joined with cache_dir""" + + # We want to generate an url to use as our cache key, we don't want to + # just reuse the URL because it might have other items in the fragment + # and we don't care about those. + key_parts = {"url": link.url_without_fragment} + if link.hash_name is not None and link.hash is not None: + key_parts[link.hash_name] = link.hash + if link.subdirectory_fragment: + key_parts["subdirectory"] = link.subdirectory_fragment + + # Include interpreter name, major and minor version in cache key + # to cope with ill-behaved sdists that build a different wheel + # depending on the python version their setup.py is being run on, + # and don't encode the difference in compatibility tags. + # https://github.com/pypa/pip/issues/7296 + key_parts["interpreter_name"] = interpreter_name() + key_parts["interpreter_version"] = interpreter_version() + + # Encode our key url with sha224, we'll use this because it has similar + # security properties to sha256, but with a shorter total output (and + # thus less secure). However the differences don't make a lot of + # difference for our use case here. + hashed = _hash_dict(key_parts) + + # We want to nest the directories some to prevent having a ton of top + # level directories where we might run out of sub directories on some + # FS. + parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] + + return parts + + def _get_candidates(self, link: Link, canonical_package_name: str) -> List[Any]: + can_not_cache = not self.cache_dir or not canonical_package_name or not link + if can_not_cache: + return [] + + path = self.get_path_for_link(link) + if os.path.isdir(path): + return [(candidate, path) for candidate in os.listdir(path)] + return [] + + def get_path_for_link(self, link: Link) -> str: + """Return a directory to store cached items in for link.""" + raise NotImplementedError() + + def get( + self, + link: Link, + package_name: Optional[str], + supported_tags: List[Tag], + ) -> Link: + """Returns a link to a cached item if it exists, otherwise returns the + passed link. + """ + raise NotImplementedError() + + +class SimpleWheelCache(Cache): + """A cache of wheels for future installs.""" + + def __init__(self, cache_dir: str) -> None: + super().__init__(cache_dir) + + def get_path_for_link(self, link: Link) -> str: + """Return a directory to store cached wheels for link + + Because there are M wheels for any one sdist, we provide a directory + to cache them in, and then consult that directory when looking up + cache hits. + + We only insert things into the cache if they have plausible version + numbers, so that we don't contaminate the cache with things that were + not unique. E.g. ./package might have dozens of installs done for it + and build a version of 0.0...and if we built and cached a wheel, we'd + end up using the same wheel even if the source has been edited. + + :param link: The link of the sdist for which this will cache wheels. + """ + parts = self._get_cache_path_parts(link) + assert self.cache_dir + # Store wheels within the root cache_dir + return os.path.join(self.cache_dir, "wheels", *parts) + + def get( + self, + link: Link, + package_name: Optional[str], + supported_tags: List[Tag], + ) -> Link: + candidates = [] + + if not package_name: + return link + + canonical_package_name = canonicalize_name(package_name) + for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name): + try: + wheel = Wheel(wheel_name) + except InvalidWheelFilename: + continue + if canonicalize_name(wheel.name) != canonical_package_name: + logger.debug( + "Ignoring cached wheel %s for %s as it " + "does not match the expected distribution name %s.", + wheel_name, + link, + package_name, + ) + continue + if not wheel.supported(supported_tags): + # Built for a different python/arch/etc + continue + candidates.append( + ( + wheel.support_index_min(supported_tags), + wheel_name, + wheel_dir, + ) + ) + + if not candidates: + return link + + _, wheel_name, wheel_dir = min(candidates) + return Link(path_to_url(os.path.join(wheel_dir, wheel_name))) + + +class EphemWheelCache(SimpleWheelCache): + """A SimpleWheelCache that creates it's own temporary cache directory""" + + def __init__(self) -> None: + self._temp_dir = TempDirectory( + kind=tempdir_kinds.EPHEM_WHEEL_CACHE, + globally_managed=True, + ) + + super().__init__(self._temp_dir.path) + + +class CacheEntry: + def __init__( + self, + link: Link, + persistent: bool, + ): + self.link = link + self.persistent = persistent + self.origin: Optional[DirectUrl] = None + origin_direct_url_path = Path(self.link.file_path).parent / ORIGIN_JSON_NAME + if origin_direct_url_path.exists(): + try: + self.origin = DirectUrl.from_json( + origin_direct_url_path.read_text(encoding="utf-8") + ) + except Exception as e: + logger.warning( + "Ignoring invalid cache entry origin file %s for %s (%s)", + origin_direct_url_path, + link.filename, + e, + ) + + +class WheelCache(Cache): + """Wraps EphemWheelCache and SimpleWheelCache into a single Cache + + This Cache allows for gracefully degradation, using the ephem wheel cache + when a certain link is not found in the simple wheel cache first. + """ + + def __init__(self, cache_dir: str) -> None: + super().__init__(cache_dir) + self._wheel_cache = SimpleWheelCache(cache_dir) + self._ephem_cache = EphemWheelCache() + + def get_path_for_link(self, link: Link) -> str: + return self._wheel_cache.get_path_for_link(link) + + def get_ephem_path_for_link(self, link: Link) -> str: + return self._ephem_cache.get_path_for_link(link) + + def get( + self, + link: Link, + package_name: Optional[str], + supported_tags: List[Tag], + ) -> Link: + cache_entry = self.get_cache_entry(link, package_name, supported_tags) + if cache_entry is None: + return link + return cache_entry.link + + def get_cache_entry( + self, + link: Link, + package_name: Optional[str], + supported_tags: List[Tag], + ) -> Optional[CacheEntry]: + """Returns a CacheEntry with a link to a cached item if it exists or + None. The cache entry indicates if the item was found in the persistent + or ephemeral cache. + """ + retval = self._wheel_cache.get( + link=link, + package_name=package_name, + supported_tags=supported_tags, + ) + if retval is not link: + return CacheEntry(retval, persistent=True) + + retval = self._ephem_cache.get( + link=link, + package_name=package_name, + supported_tags=supported_tags, + ) + if retval is not link: + return CacheEntry(retval, persistent=False) + + return None + + @staticmethod + def record_download_origin(cache_dir: str, download_info: DirectUrl) -> None: + origin_path = Path(cache_dir) / ORIGIN_JSON_NAME + if origin_path.exists(): + try: + origin = DirectUrl.from_json(origin_path.read_text(encoding="utf-8")) + except Exception as e: + logger.warning( + "Could not read origin file %s in cache entry (%s). " + "Will attempt to overwrite it.", + origin_path, + e, + ) + else: + # TODO: use DirectUrl.equivalent when + # https://github.com/pypa/pip/pull/10564 is merged. + if origin.url != download_info.url: + logger.warning( + "Origin URL %s in cache entry %s does not match download URL " + "%s. This is likely a pip bug or a cache corruption issue. " + "Will overwrite it with the new value.", + origin.url, + cache_dir, + download_info.url, + ) + origin_path.write_text(download_info.to_json(), encoding="utf-8") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e589bb917e23823e25f9fff7e0849c4d6d4a62bc --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__init__.py @@ -0,0 +1,4 @@ +"""Subpackage containing all of pip's command line interface related code +""" + +# This file intentionally does not import submodules diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3223c2812f9daa2dc9a82b2bd46697b90f3853c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b95a0a91048b77b498f0677de60fab1c6de2eceb Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d57e0bffe43e5a7bb34ee78a0aff5a91ae0eaedc Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af4086dab3064206d0e61e0907d3801f7e3c3d78 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aef77239ca17f4da5b74aa7cc69f47af29021857 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/command_context.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/index_command.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/index_command.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c8c96916d3ad9e038f172171ef2f93c96ac3ea8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/index_command.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/main.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec81c7a73747906b998d232af5e1578c5c734a0d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/main.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d29f280b3c128832595e39ea6e2210a7a7b2c32 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/parser.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84b055958ba44cfefbefbc5f6551e9748ff08492 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/parser.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5f677b10fcb4bbf97a80605dcc47cf99a56ed6f Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f20c1a4faff4c267b326a56b4356f663554f441 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..277c353ad00c991034bdd6f90d6ff2048682ee45 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/spinners.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..684c3d7cb061754b66dfafb299c5d95e079366ab Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/autocompletion.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/autocompletion.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f70ac8553b069d2d7f87926e6ba12f8998b5e5 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/autocompletion.py @@ -0,0 +1,176 @@ +"""Logic that powers autocompletion installed by ``pip completion``. +""" + +import optparse +import os +import sys +from itertools import chain +from typing import Any, Iterable, List, Optional + +from pip._internal.cli.main_parser import create_main_parser +from pip._internal.commands import commands_dict, create_command +from pip._internal.metadata import get_default_environment + + +def autocomplete() -> None: + """Entry Point for completion of main and subcommand options.""" + # Don't complete if user hasn't sourced bash_completion file. + if "PIP_AUTO_COMPLETE" not in os.environ: + return + # Don't complete if autocompletion environment variables + # are not present + if not os.environ.get("COMP_WORDS") or not os.environ.get("COMP_CWORD"): + return + cwords = os.environ["COMP_WORDS"].split()[1:] + cword = int(os.environ["COMP_CWORD"]) + try: + current = cwords[cword - 1] + except IndexError: + current = "" + + parser = create_main_parser() + subcommands = list(commands_dict) + options = [] + + # subcommand + subcommand_name: Optional[str] = None + for word in cwords: + if word in subcommands: + subcommand_name = word + break + # subcommand options + if subcommand_name is not None: + # special case: 'help' subcommand has no options + if subcommand_name == "help": + sys.exit(1) + # special case: list locally installed dists for show and uninstall + should_list_installed = not current.startswith("-") and subcommand_name in [ + "show", + "uninstall", + ] + if should_list_installed: + env = get_default_environment() + lc = current.lower() + installed = [ + dist.canonical_name + for dist in env.iter_installed_distributions(local_only=True) + if dist.canonical_name.startswith(lc) + and dist.canonical_name not in cwords[1:] + ] + # if there are no dists installed, fall back to option completion + if installed: + for dist in installed: + print(dist) + sys.exit(1) + + should_list_installables = ( + not current.startswith("-") and subcommand_name == "install" + ) + if should_list_installables: + for path in auto_complete_paths(current, "path"): + print(path) + sys.exit(1) + + subcommand = create_command(subcommand_name) + + for opt in subcommand.parser.option_list_all: + if opt.help != optparse.SUPPRESS_HELP: + options += [ + (opt_str, opt.nargs) for opt_str in opt._long_opts + opt._short_opts + ] + + # filter out previously specified options from available options + prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]] + options = [(x, v) for (x, v) in options if x not in prev_opts] + # filter options by current input + options = [(k, v) for k, v in options if k.startswith(current)] + # get completion type given cwords and available subcommand options + completion_type = get_path_completion_type( + cwords, + cword, + subcommand.parser.option_list_all, + ) + # get completion files and directories if ``completion_type`` is + # ````, ```` or ```` + if completion_type: + paths = auto_complete_paths(current, completion_type) + options = [(path, 0) for path in paths] + for option in options: + opt_label = option[0] + # append '=' to options which require args + if option[1] and option[0][:2] == "--": + opt_label += "=" + print(opt_label) + else: + # show main parser options only when necessary + + opts = [i.option_list for i in parser.option_groups] + opts.append(parser.option_list) + flattened_opts = chain.from_iterable(opts) + if current.startswith("-"): + for opt in flattened_opts: + if opt.help != optparse.SUPPRESS_HELP: + subcommands += opt._long_opts + opt._short_opts + else: + # get completion type given cwords and all available options + completion_type = get_path_completion_type(cwords, cword, flattened_opts) + if completion_type: + subcommands = list(auto_complete_paths(current, completion_type)) + + print(" ".join([x for x in subcommands if x.startswith(current)])) + sys.exit(1) + + +def get_path_completion_type( + cwords: List[str], cword: int, opts: Iterable[Any] +) -> Optional[str]: + """Get the type of path completion (``file``, ``dir``, ``path`` or None) + + :param cwords: same as the environmental variable ``COMP_WORDS`` + :param cword: same as the environmental variable ``COMP_CWORD`` + :param opts: The available options to check + :return: path completion type (``file``, ``dir``, ``path`` or None) + """ + if cword < 2 or not cwords[cword - 2].startswith("-"): + return None + for opt in opts: + if opt.help == optparse.SUPPRESS_HELP: + continue + for o in str(opt).split("/"): + if cwords[cword - 2].split("=")[0] == o: + if not opt.metavar or any( + x in ("path", "file", "dir") for x in opt.metavar.split("/") + ): + return opt.metavar + return None + + +def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]: + """If ``completion_type`` is ``file`` or ``path``, list all regular files + and directories starting with ``current``; otherwise only list directories + starting with ``current``. + + :param current: The word to be completed + :param completion_type: path completion type(``file``, ``path`` or ``dir``) + :return: A generator of regular files and/or directories + """ + directory, filename = os.path.split(current) + current_path = os.path.abspath(directory) + # Don't complete paths if they can't be accessed + if not os.access(current_path, os.R_OK): + return + filename = os.path.normcase(filename) + # list all files that start with ``filename`` + file_list = ( + x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename) + ) + for f in file_list: + opt = os.path.join(current_path, f) + comp_file = os.path.normcase(os.path.join(directory, f)) + # complete regular files when there is not ```` after option + # complete directories when there is ````, ```` or + # ````after option + if completion_type != "dir" and os.path.isfile(opt): + yield comp_file + elif os.path.isdir(opt): + yield os.path.join(comp_file, "") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/base_command.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/base_command.py new file mode 100644 index 0000000000000000000000000000000000000000..362f84b6b0b84612e40bd6e96b94fd0e05bb48d6 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/base_command.py @@ -0,0 +1,240 @@ +"""Base Command class, and related routines""" + +import logging +import logging.config +import optparse +import os +import sys +import traceback +from optparse import Values +from typing import List, Optional, Tuple + +from pip._vendor.rich import reconfigure +from pip._vendor.rich import traceback as rich_traceback + +from pip._internal.cli import cmdoptions +from pip._internal.cli.command_context import CommandContextMixIn +from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter +from pip._internal.cli.status_codes import ( + ERROR, + PREVIOUS_BUILD_DIR_ERROR, + UNKNOWN_ERROR, + VIRTUALENV_NOT_FOUND, +) +from pip._internal.exceptions import ( + BadCommand, + CommandError, + DiagnosticPipError, + InstallationError, + NetworkConnectionError, + PreviousBuildDirError, +) +from pip._internal.utils.deprecation import deprecated +from pip._internal.utils.filesystem import check_path_owner +from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging +from pip._internal.utils.misc import get_prog, normalize_path +from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry +from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry +from pip._internal.utils.virtualenv import running_under_virtualenv + +__all__ = ["Command"] + +logger = logging.getLogger(__name__) + + +class Command(CommandContextMixIn): + usage: str = "" + ignore_require_venv: bool = False + + def __init__(self, name: str, summary: str, isolated: bool = False) -> None: + super().__init__() + + self.name = name + self.summary = summary + self.parser = ConfigOptionParser( + usage=self.usage, + prog=f"{get_prog()} {name}", + formatter=UpdatingDefaultsHelpFormatter(), + add_help_option=False, + name=name, + description=self.__doc__, + isolated=isolated, + ) + + self.tempdir_registry: Optional[TempDirRegistry] = None + + # Commands should add options to this option group + optgroup_name = f"{self.name.capitalize()} Options" + self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name) + + # Add the general options + gen_opts = cmdoptions.make_option_group( + cmdoptions.general_group, + self.parser, + ) + self.parser.add_option_group(gen_opts) + + self.add_options() + + def add_options(self) -> None: + pass + + def handle_pip_version_check(self, options: Values) -> None: + """ + This is a no-op so that commands by default do not do the pip version + check. + """ + # Make sure we do the pip version check if the index_group options + # are present. + assert not hasattr(options, "no_index") + + def run(self, options: Values, args: List[str]) -> int: + raise NotImplementedError + + def _run_wrapper(self, level_number: int, options: Values, args: List[str]) -> int: + def _inner_run() -> int: + try: + return self.run(options, args) + finally: + self.handle_pip_version_check(options) + + if options.debug_mode: + rich_traceback.install(show_locals=True) + return _inner_run() + + try: + status = _inner_run() + assert isinstance(status, int) + return status + except DiagnosticPipError as exc: + logger.error("%s", exc, extra={"rich": True}) + logger.debug("Exception information:", exc_info=True) + + return ERROR + except PreviousBuildDirError as exc: + logger.critical(str(exc)) + logger.debug("Exception information:", exc_info=True) + + return PREVIOUS_BUILD_DIR_ERROR + except ( + InstallationError, + BadCommand, + NetworkConnectionError, + ) as exc: + logger.critical(str(exc)) + logger.debug("Exception information:", exc_info=True) + + return ERROR + except CommandError as exc: + logger.critical("%s", exc) + logger.debug("Exception information:", exc_info=True) + + return ERROR + except BrokenStdoutLoggingError: + # Bypass our logger and write any remaining messages to + # stderr because stdout no longer works. + print("ERROR: Pipe to stdout was broken", file=sys.stderr) + if level_number <= logging.DEBUG: + traceback.print_exc(file=sys.stderr) + + return ERROR + except KeyboardInterrupt: + logger.critical("Operation cancelled by user") + logger.debug("Exception information:", exc_info=True) + + return ERROR + except BaseException: + logger.critical("Exception:", exc_info=True) + + return UNKNOWN_ERROR + + def parse_args(self, args: List[str]) -> Tuple[Values, List[str]]: + # factored out for testability + return self.parser.parse_args(args) + + def main(self, args: List[str]) -> int: + try: + with self.main_context(): + return self._main(args) + finally: + logging.shutdown() + + def _main(self, args: List[str]) -> int: + # We must initialize this before the tempdir manager, otherwise the + # configuration would not be accessible by the time we clean up the + # tempdir manager. + self.tempdir_registry = self.enter_context(tempdir_registry()) + # Intentionally set as early as possible so globally-managed temporary + # directories are available to the rest of the code. + self.enter_context(global_tempdir_manager()) + + options, args = self.parse_args(args) + + # Set verbosity so that it can be used elsewhere. + self.verbosity = options.verbose - options.quiet + + reconfigure(no_color=options.no_color) + level_number = setup_logging( + verbosity=self.verbosity, + no_color=options.no_color, + user_log_file=options.log, + ) + + always_enabled_features = set(options.features_enabled) & set( + cmdoptions.ALWAYS_ENABLED_FEATURES + ) + if always_enabled_features: + logger.warning( + "The following features are always enabled: %s. ", + ", ".join(sorted(always_enabled_features)), + ) + + # Make sure that the --python argument isn't specified after the + # subcommand. We can tell, because if --python was specified, + # we should only reach this point if we're running in the created + # subprocess, which has the _PIP_RUNNING_IN_SUBPROCESS environment + # variable set. + if options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ: + logger.critical( + "The --python option must be placed before the pip subcommand name" + ) + sys.exit(ERROR) + + # TODO: Try to get these passing down from the command? + # without resorting to os.environ to hold these. + # This also affects isolated builds and it should. + + if options.no_input: + os.environ["PIP_NO_INPUT"] = "1" + + if options.exists_action: + os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action) + + if options.require_venv and not self.ignore_require_venv: + # If a venv is required check if it can really be found + if not running_under_virtualenv(): + logger.critical("Could not find an activated virtualenv (required).") + sys.exit(VIRTUALENV_NOT_FOUND) + + if options.cache_dir: + options.cache_dir = normalize_path(options.cache_dir) + if not check_path_owner(options.cache_dir): + logger.warning( + "The directory '%s' or its parent directory is not owned " + "or is not writable by the current user. The cache " + "has been disabled. Check the permissions and owner of " + "that directory. If executing pip with sudo, you should " + "use sudo's -H flag.", + options.cache_dir, + ) + options.cache_dir = None + + if options.no_python_version_warning: + deprecated( + reason="--no-python-version-warning is deprecated.", + replacement="to remove the flag as it's a no-op", + gone_in="25.1", + issue=13154, + ) + + return self._run_wrapper(level_number, options, args) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/cmdoptions.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/cmdoptions.py new file mode 100644 index 0000000000000000000000000000000000000000..eeb7e651b792b0c6c2d40ad6934216b05dd8354b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/cmdoptions.py @@ -0,0 +1,1075 @@ +""" +shared options and groups + +The principle here is to define options once, but *not* instantiate them +globally. One reason being that options with action='append' can carry state +between parses. pip parses general options twice internally, and shouldn't +pass on state. To be consistent, all options will follow this design. +""" + +# The following comment should be removed at some point in the future. +# mypy: strict-optional=False + +import importlib.util +import logging +import os +import textwrap +from functools import partial +from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values +from textwrap import dedent +from typing import Any, Callable, Dict, Optional, Tuple + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.cli.parser import ConfigOptionParser +from pip._internal.exceptions import CommandError +from pip._internal.locations import USER_CACHE_DIR, get_src_prefix +from pip._internal.models.format_control import FormatControl +from pip._internal.models.index import PyPI +from pip._internal.models.target_python import TargetPython +from pip._internal.utils.hashes import STRONG_HASHES +from pip._internal.utils.misc import strtobool + +logger = logging.getLogger(__name__) + + +def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None: + """ + Raise an option parsing error using parser.error(). + + Args: + parser: an OptionParser instance. + option: an Option instance. + msg: the error text. + """ + msg = f"{option} error: {msg}" + msg = textwrap.fill(" ".join(msg.split())) + parser.error(msg) + + +def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup: + """ + Return an OptionGroup object + group -- assumed to be dict with 'name' and 'options' keys + parser -- an optparse Parser + """ + option_group = OptionGroup(parser, group["name"]) + for option in group["options"]: + option_group.add_option(option()) + return option_group + + +def check_dist_restriction(options: Values, check_target: bool = False) -> None: + """Function for determining if custom platform options are allowed. + + :param options: The OptionParser options. + :param check_target: Whether or not to check if --target is being used. + """ + dist_restriction_set = any( + [ + options.python_version, + options.platforms, + options.abis, + options.implementation, + ] + ) + + binary_only = FormatControl(set(), {":all:"}) + sdist_dependencies_allowed = ( + options.format_control != binary_only and not options.ignore_dependencies + ) + + # Installations or downloads using dist restrictions must not combine + # source distributions and dist-specific wheels, as they are not + # guaranteed to be locally compatible. + if dist_restriction_set and sdist_dependencies_allowed: + raise CommandError( + "When restricting platform and interpreter constraints using " + "--python-version, --platform, --abi, or --implementation, " + "either --no-deps must be set, or --only-binary=:all: must be " + "set and --no-binary must not be set (or must be set to " + ":none:)." + ) + + if check_target: + if not options.dry_run and dist_restriction_set and not options.target_dir: + raise CommandError( + "Can not use any platform or abi specific options unless " + "installing via '--target' or using '--dry-run'" + ) + + +def _path_option_check(option: Option, opt: str, value: str) -> str: + return os.path.expanduser(value) + + +def _package_name_option_check(option: Option, opt: str, value: str) -> str: + return canonicalize_name(value) + + +class PipOption(Option): + TYPES = Option.TYPES + ("path", "package_name") + TYPE_CHECKER = Option.TYPE_CHECKER.copy() + TYPE_CHECKER["package_name"] = _package_name_option_check + TYPE_CHECKER["path"] = _path_option_check + + +########### +# options # +########### + +help_: Callable[..., Option] = partial( + Option, + "-h", + "--help", + dest="help", + action="help", + help="Show help.", +) + +debug_mode: Callable[..., Option] = partial( + Option, + "--debug", + dest="debug_mode", + action="store_true", + default=False, + help=( + "Let unhandled exceptions propagate outside the main subroutine, " + "instead of logging them to stderr." + ), +) + +isolated_mode: Callable[..., Option] = partial( + Option, + "--isolated", + dest="isolated_mode", + action="store_true", + default=False, + help=( + "Run pip in an isolated mode, ignoring environment variables and user " + "configuration." + ), +) + +require_virtualenv: Callable[..., Option] = partial( + Option, + "--require-virtualenv", + "--require-venv", + dest="require_venv", + action="store_true", + default=False, + help=( + "Allow pip to only run in a virtual environment; " + "exit with an error otherwise." + ), +) + +override_externally_managed: Callable[..., Option] = partial( + Option, + "--break-system-packages", + dest="override_externally_managed", + action="store_true", + help="Allow pip to modify an EXTERNALLY-MANAGED Python installation", +) + +python: Callable[..., Option] = partial( + Option, + "--python", + dest="python", + help="Run pip with the specified Python interpreter.", +) + +verbose: Callable[..., Option] = partial( + Option, + "-v", + "--verbose", + dest="verbose", + action="count", + default=0, + help="Give more output. Option is additive, and can be used up to 3 times.", +) + +no_color: Callable[..., Option] = partial( + Option, + "--no-color", + dest="no_color", + action="store_true", + default=False, + help="Suppress colored output.", +) + +version: Callable[..., Option] = partial( + Option, + "-V", + "--version", + dest="version", + action="store_true", + help="Show version and exit.", +) + +quiet: Callable[..., Option] = partial( + Option, + "-q", + "--quiet", + dest="quiet", + action="count", + default=0, + help=( + "Give less output. Option is additive, and can be used up to 3" + " times (corresponding to WARNING, ERROR, and CRITICAL logging" + " levels)." + ), +) + +progress_bar: Callable[..., Option] = partial( + Option, + "--progress-bar", + dest="progress_bar", + type="choice", + choices=["on", "off", "raw"], + default="on", + help="Specify whether the progress bar should be used [on, off, raw] (default: on)", +) + +log: Callable[..., Option] = partial( + PipOption, + "--log", + "--log-file", + "--local-log", + dest="log", + metavar="path", + type="path", + help="Path to a verbose appending log.", +) + +no_input: Callable[..., Option] = partial( + Option, + # Don't ask for input + "--no-input", + dest="no_input", + action="store_true", + default=False, + help="Disable prompting for input.", +) + +keyring_provider: Callable[..., Option] = partial( + Option, + "--keyring-provider", + dest="keyring_provider", + choices=["auto", "disabled", "import", "subprocess"], + default="auto", + help=( + "Enable the credential lookup via the keyring library if user input is allowed." + " Specify which mechanism to use [auto, disabled, import, subprocess]." + " (default: %default)" + ), +) + +proxy: Callable[..., Option] = partial( + Option, + "--proxy", + dest="proxy", + type="str", + default="", + help="Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.", +) + +retries: Callable[..., Option] = partial( + Option, + "--retries", + dest="retries", + type="int", + default=5, + help="Maximum number of retries each connection should attempt " + "(default %default times).", +) + +timeout: Callable[..., Option] = partial( + Option, + "--timeout", + "--default-timeout", + metavar="sec", + dest="timeout", + type="float", + default=15, + help="Set the socket timeout (default %default seconds).", +) + + +def exists_action() -> Option: + return Option( + # Option when path already exist + "--exists-action", + dest="exists_action", + type="choice", + choices=["s", "i", "w", "b", "a"], + default=[], + action="append", + metavar="action", + help="Default action when a path already exists: " + "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.", + ) + + +cert: Callable[..., Option] = partial( + PipOption, + "--cert", + dest="cert", + type="path", + metavar="path", + help=( + "Path to PEM-encoded CA certificate bundle. " + "If provided, overrides the default. " + "See 'SSL Certificate Verification' in pip documentation " + "for more information." + ), +) + +client_cert: Callable[..., Option] = partial( + PipOption, + "--client-cert", + dest="client_cert", + type="path", + default=None, + metavar="path", + help="Path to SSL client certificate, a single file containing the " + "private key and the certificate in PEM format.", +) + +index_url: Callable[..., Option] = partial( + Option, + "-i", + "--index-url", + "--pypi-url", + dest="index_url", + metavar="URL", + default=PyPI.simple_url, + help="Base URL of the Python Package Index (default %default). " + "This should point to a repository compliant with PEP 503 " + "(the simple repository API) or a local directory laid out " + "in the same format.", +) + + +def extra_index_url() -> Option: + return Option( + "--extra-index-url", + dest="extra_index_urls", + metavar="URL", + action="append", + default=[], + help="Extra URLs of package indexes to use in addition to " + "--index-url. Should follow the same rules as " + "--index-url.", + ) + + +no_index: Callable[..., Option] = partial( + Option, + "--no-index", + dest="no_index", + action="store_true", + default=False, + help="Ignore package index (only looking at --find-links URLs instead).", +) + + +def find_links() -> Option: + return Option( + "-f", + "--find-links", + dest="find_links", + action="append", + default=[], + metavar="url", + help="If a URL or path to an html file, then parse for links to " + "archives such as sdist (.tar.gz) or wheel (.whl) files. " + "If a local path or file:// URL that's a directory, " + "then look for archives in the directory listing. " + "Links to VCS project URLs are not supported.", + ) + + +def trusted_host() -> Option: + return Option( + "--trusted-host", + dest="trusted_hosts", + action="append", + metavar="HOSTNAME", + default=[], + help="Mark this host or host:port pair as trusted, even though it " + "does not have valid or any HTTPS.", + ) + + +def constraints() -> Option: + return Option( + "-c", + "--constraint", + dest="constraints", + action="append", + default=[], + metavar="file", + help="Constrain versions using the given constraints file. " + "This option can be used multiple times.", + ) + + +def requirements() -> Option: + return Option( + "-r", + "--requirement", + dest="requirements", + action="append", + default=[], + metavar="file", + help="Install from the given requirements file. " + "This option can be used multiple times.", + ) + + +def editable() -> Option: + return Option( + "-e", + "--editable", + dest="editables", + action="append", + default=[], + metavar="path/url", + help=( + "Install a project in editable mode (i.e. setuptools " + '"develop mode") from a local project path or a VCS url.' + ), + ) + + +def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None: + value = os.path.abspath(value) + setattr(parser.values, option.dest, value) + + +src: Callable[..., Option] = partial( + PipOption, + "--src", + "--source", + "--source-dir", + "--source-directory", + dest="src_dir", + type="path", + metavar="dir", + default=get_src_prefix(), + action="callback", + callback=_handle_src, + help="Directory to check out editable projects into. " + 'The default in a virtualenv is "/src". ' + 'The default for global installs is "/src".', +) + + +def _get_format_control(values: Values, option: Option) -> Any: + """Get a format_control object.""" + return getattr(values, option.dest) + + +def _handle_no_binary( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + existing = _get_format_control(parser.values, option) + FormatControl.handle_mutual_excludes( + value, + existing.no_binary, + existing.only_binary, + ) + + +def _handle_only_binary( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + existing = _get_format_control(parser.values, option) + FormatControl.handle_mutual_excludes( + value, + existing.only_binary, + existing.no_binary, + ) + + +def no_binary() -> Option: + format_control = FormatControl(set(), set()) + return Option( + "--no-binary", + dest="format_control", + action="callback", + callback=_handle_no_binary, + type="str", + default=format_control, + help="Do not use binary packages. Can be supplied multiple times, and " + 'each time adds to the existing value. Accepts either ":all:" to ' + 'disable all binary packages, ":none:" to empty the set (notice ' + "the colons), or one or more package names with commas between " + "them (no colons). Note that some packages are tricky to compile " + "and may fail to install when this option is used on them.", + ) + + +def only_binary() -> Option: + format_control = FormatControl(set(), set()) + return Option( + "--only-binary", + dest="format_control", + action="callback", + callback=_handle_only_binary, + type="str", + default=format_control, + help="Do not use source packages. Can be supplied multiple times, and " + 'each time adds to the existing value. Accepts either ":all:" to ' + 'disable all source packages, ":none:" to empty the set, or one ' + "or more package names with commas between them. Packages " + "without binary distributions will fail to install when this " + "option is used on them.", + ) + + +platforms: Callable[..., Option] = partial( + Option, + "--platform", + dest="platforms", + metavar="platform", + action="append", + default=None, + help=( + "Only use wheels compatible with . Defaults to the " + "platform of the running system. Use this option multiple times to " + "specify multiple platforms supported by the target interpreter." + ), +) + + +# This was made a separate function for unit-testing purposes. +def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]: + """ + Convert a version string like "3", "37", or "3.7.3" into a tuple of ints. + + :return: A 2-tuple (version_info, error_msg), where `error_msg` is + non-None if and only if there was a parsing error. + """ + if not value: + # The empty string is the same as not providing a value. + return (None, None) + + parts = value.split(".") + if len(parts) > 3: + return ((), "at most three version parts are allowed") + + if len(parts) == 1: + # Then we are in the case of "3" or "37". + value = parts[0] + if len(value) > 1: + parts = [value[0], value[1:]] + + try: + version_info = tuple(int(part) for part in parts) + except ValueError: + return ((), "each version part must be an integer") + + return (version_info, None) + + +def _handle_python_version( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + """ + Handle a provided --python-version value. + """ + version_info, error_msg = _convert_python_version(value) + if error_msg is not None: + msg = f"invalid --python-version value: {value!r}: {error_msg}" + raise_option_error(parser, option=option, msg=msg) + + parser.values.python_version = version_info + + +python_version: Callable[..., Option] = partial( + Option, + "--python-version", + dest="python_version", + metavar="python_version", + action="callback", + callback=_handle_python_version, + type="str", + default=None, + help=dedent( + """\ + The Python interpreter version to use for wheel and "Requires-Python" + compatibility checks. Defaults to a version derived from the running + interpreter. The version can be specified using up to three dot-separated + integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor + version can also be given as a string without dots (e.g. "37" for 3.7.0). + """ + ), +) + + +implementation: Callable[..., Option] = partial( + Option, + "--implementation", + dest="implementation", + metavar="implementation", + default=None, + help=( + "Only use wheels compatible with Python " + "implementation , e.g. 'pp', 'jy', 'cp', " + " or 'ip'. If not specified, then the current " + "interpreter implementation is used. Use 'py' to force " + "implementation-agnostic wheels." + ), +) + + +abis: Callable[..., Option] = partial( + Option, + "--abi", + dest="abis", + metavar="abi", + action="append", + default=None, + help=( + "Only use wheels compatible with Python abi , e.g. 'pypy_41'. " + "If not specified, then the current interpreter abi tag is used. " + "Use this option multiple times to specify multiple abis supported " + "by the target interpreter. Generally you will need to specify " + "--implementation, --platform, and --python-version when using this " + "option." + ), +) + + +def add_target_python_options(cmd_opts: OptionGroup) -> None: + cmd_opts.add_option(platforms()) + cmd_opts.add_option(python_version()) + cmd_opts.add_option(implementation()) + cmd_opts.add_option(abis()) + + +def make_target_python(options: Values) -> TargetPython: + target_python = TargetPython( + platforms=options.platforms, + py_version_info=options.python_version, + abis=options.abis, + implementation=options.implementation, + ) + + return target_python + + +def prefer_binary() -> Option: + return Option( + "--prefer-binary", + dest="prefer_binary", + action="store_true", + default=False, + help=( + "Prefer binary packages over source packages, even if the " + "source packages are newer." + ), + ) + + +cache_dir: Callable[..., Option] = partial( + PipOption, + "--cache-dir", + dest="cache_dir", + default=USER_CACHE_DIR, + metavar="dir", + type="path", + help="Store the cache data in .", +) + + +def _handle_no_cache_dir( + option: Option, opt: str, value: str, parser: OptionParser +) -> None: + """ + Process a value provided for the --no-cache-dir option. + + This is an optparse.Option callback for the --no-cache-dir option. + """ + # The value argument will be None if --no-cache-dir is passed via the + # command-line, since the option doesn't accept arguments. However, + # the value can be non-None if the option is triggered e.g. by an + # environment variable, like PIP_NO_CACHE_DIR=true. + if value is not None: + # Then parse the string value to get argument error-checking. + try: + strtobool(value) + except ValueError as exc: + raise_option_error(parser, option=option, msg=str(exc)) + + # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() + # converted to 0 (like "false" or "no") caused cache_dir to be disabled + # rather than enabled (logic would say the latter). Thus, we disable + # the cache directory not just on values that parse to True, but (for + # backwards compatibility reasons) also on values that parse to False. + # In other words, always set it to False if the option is provided in + # some (valid) form. + parser.values.cache_dir = False + + +no_cache: Callable[..., Option] = partial( + Option, + "--no-cache-dir", + dest="cache_dir", + action="callback", + callback=_handle_no_cache_dir, + help="Disable the cache.", +) + +no_deps: Callable[..., Option] = partial( + Option, + "--no-deps", + "--no-dependencies", + dest="ignore_dependencies", + action="store_true", + default=False, + help="Don't install package dependencies.", +) + +ignore_requires_python: Callable[..., Option] = partial( + Option, + "--ignore-requires-python", + dest="ignore_requires_python", + action="store_true", + help="Ignore the Requires-Python information.", +) + +no_build_isolation: Callable[..., Option] = partial( + Option, + "--no-build-isolation", + dest="build_isolation", + action="store_false", + default=True, + help="Disable isolation when building a modern source distribution. " + "Build dependencies specified by PEP 518 must be already installed " + "if this option is used.", +) + +check_build_deps: Callable[..., Option] = partial( + Option, + "--check-build-dependencies", + dest="check_build_deps", + action="store_true", + default=False, + help="Check the build dependencies when PEP517 is used.", +) + + +def _handle_no_use_pep517( + option: Option, opt: str, value: str, parser: OptionParser +) -> None: + """ + Process a value provided for the --no-use-pep517 option. + + This is an optparse.Option callback for the no_use_pep517 option. + """ + # Since --no-use-pep517 doesn't accept arguments, the value argument + # will be None if --no-use-pep517 is passed via the command-line. + # However, the value can be non-None if the option is triggered e.g. + # by an environment variable, for example "PIP_NO_USE_PEP517=true". + if value is not None: + msg = """A value was passed for --no-use-pep517, + probably using either the PIP_NO_USE_PEP517 environment variable + or the "no-use-pep517" config file option. Use an appropriate value + of the PIP_USE_PEP517 environment variable or the "use-pep517" + config file option instead. + """ + raise_option_error(parser, option=option, msg=msg) + + # If user doesn't wish to use pep517, we check if setuptools and wheel are installed + # and raise error if it is not. + packages = ("setuptools", "wheel") + if not all(importlib.util.find_spec(package) for package in packages): + msg = ( + f"It is not possible to use --no-use-pep517 " + f"without {' and '.join(packages)} installed." + ) + raise_option_error(parser, option=option, msg=msg) + + # Otherwise, --no-use-pep517 was passed via the command-line. + parser.values.use_pep517 = False + + +use_pep517: Any = partial( + Option, + "--use-pep517", + dest="use_pep517", + action="store_true", + default=None, + help="Use PEP 517 for building source distributions " + "(use --no-use-pep517 to force legacy behaviour).", +) + +no_use_pep517: Any = partial( + Option, + "--no-use-pep517", + dest="use_pep517", + action="callback", + callback=_handle_no_use_pep517, + default=None, + help=SUPPRESS_HELP, +) + + +def _handle_config_settings( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + key, sep, val = value.partition("=") + if sep != "=": + parser.error(f"Arguments to {opt_str} must be of the form KEY=VAL") + dest = getattr(parser.values, option.dest) + if dest is None: + dest = {} + setattr(parser.values, option.dest, dest) + if key in dest: + if isinstance(dest[key], list): + dest[key].append(val) + else: + dest[key] = [dest[key], val] + else: + dest[key] = val + + +config_settings: Callable[..., Option] = partial( + Option, + "-C", + "--config-settings", + dest="config_settings", + type=str, + action="callback", + callback=_handle_config_settings, + metavar="settings", + help="Configuration settings to be passed to the PEP 517 build backend. " + "Settings take the form KEY=VALUE. Use multiple --config-settings options " + "to pass multiple keys to the backend.", +) + +build_options: Callable[..., Option] = partial( + Option, + "--build-option", + dest="build_options", + metavar="options", + action="append", + help="Extra arguments to be supplied to 'setup.py bdist_wheel'.", +) + +global_options: Callable[..., Option] = partial( + Option, + "--global-option", + dest="global_options", + action="append", + metavar="options", + help="Extra global options to be supplied to the setup.py " + "call before the install or bdist_wheel command.", +) + +no_clean: Callable[..., Option] = partial( + Option, + "--no-clean", + action="store_true", + default=False, + help="Don't clean up build directories.", +) + +pre: Callable[..., Option] = partial( + Option, + "--pre", + action="store_true", + default=False, + help="Include pre-release and development versions. By default, " + "pip only finds stable versions.", +) + +disable_pip_version_check: Callable[..., Option] = partial( + Option, + "--disable-pip-version-check", + dest="disable_pip_version_check", + action="store_true", + default=False, + help="Don't periodically check PyPI to determine whether a new version " + "of pip is available for download. Implied with --no-index.", +) + +root_user_action: Callable[..., Option] = partial( + Option, + "--root-user-action", + dest="root_user_action", + default="warn", + choices=["warn", "ignore"], + help="Action if pip is run as a root user [warn, ignore] (default: warn)", +) + + +def _handle_merge_hash( + option: Option, opt_str: str, value: str, parser: OptionParser +) -> None: + """Given a value spelled "algo:digest", append the digest to a list + pointed to in a dict by the algo name.""" + if not parser.values.hashes: + parser.values.hashes = {} + try: + algo, digest = value.split(":", 1) + except ValueError: + parser.error( + f"Arguments to {opt_str} must be a hash name " + "followed by a value, like --hash=sha256:" + "abcde..." + ) + if algo not in STRONG_HASHES: + parser.error( + "Allowed hash algorithms for {} are {}.".format( + opt_str, ", ".join(STRONG_HASHES) + ) + ) + parser.values.hashes.setdefault(algo, []).append(digest) + + +hash: Callable[..., Option] = partial( + Option, + "--hash", + # Hash values eventually end up in InstallRequirement.hashes due to + # __dict__ copying in process_line(). + dest="hashes", + action="callback", + callback=_handle_merge_hash, + type="string", + help="Verify that the package's archive matches this " + "hash before installing. Example: --hash=sha256:abcdef...", +) + + +require_hashes: Callable[..., Option] = partial( + Option, + "--require-hashes", + dest="require_hashes", + action="store_true", + default=False, + help="Require a hash to check each requirement against, for " + "repeatable installs. This option is implied when any package in a " + "requirements file has a --hash option.", +) + + +list_path: Callable[..., Option] = partial( + PipOption, + "--path", + dest="path", + type="path", + action="append", + help="Restrict to the specified installation path for listing " + "packages (can be used multiple times).", +) + + +def check_list_path_option(options: Values) -> None: + if options.path and (options.user or options.local): + raise CommandError("Cannot combine '--path' with '--user' or '--local'") + + +list_exclude: Callable[..., Option] = partial( + PipOption, + "--exclude", + dest="excludes", + action="append", + metavar="package", + type="package_name", + help="Exclude specified package from the output", +) + + +no_python_version_warning: Callable[..., Option] = partial( + Option, + "--no-python-version-warning", + dest="no_python_version_warning", + action="store_true", + default=False, + help="Silence deprecation warnings for upcoming unsupported Pythons.", +) + + +# Features that are now always on. A warning is printed if they are used. +ALWAYS_ENABLED_FEATURES = [ + "truststore", # always on since 24.2 + "no-binary-enable-wheel-cache", # always on since 23.1 +] + +use_new_feature: Callable[..., Option] = partial( + Option, + "--use-feature", + dest="features_enabled", + metavar="feature", + action="append", + default=[], + choices=[ + "fast-deps", + ] + + ALWAYS_ENABLED_FEATURES, + help="Enable new functionality, that may be backward incompatible.", +) + +use_deprecated_feature: Callable[..., Option] = partial( + Option, + "--use-deprecated", + dest="deprecated_features_enabled", + metavar="feature", + action="append", + default=[], + choices=[ + "legacy-resolver", + "legacy-certs", + ], + help=("Enable deprecated functionality, that will be removed in the future."), +) + + +########## +# groups # +########## + +general_group: Dict[str, Any] = { + "name": "General Options", + "options": [ + help_, + debug_mode, + isolated_mode, + require_virtualenv, + python, + verbose, + version, + quiet, + log, + no_input, + keyring_provider, + proxy, + retries, + timeout, + exists_action, + trusted_host, + cert, + client_cert, + cache_dir, + no_cache, + disable_pip_version_check, + no_color, + no_python_version_warning, + use_new_feature, + use_deprecated_feature, + ], +} + +index_group: Dict[str, Any] = { + "name": "Package Index Options", + "options": [ + index_url, + extra_index_url, + no_index, + find_links, + ], +} diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/command_context.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/command_context.py new file mode 100644 index 0000000000000000000000000000000000000000..139995ac3f109a82664e4913f7ebc32ecf7617e1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/command_context.py @@ -0,0 +1,27 @@ +from contextlib import ExitStack, contextmanager +from typing import ContextManager, Generator, TypeVar + +_T = TypeVar("_T", covariant=True) + + +class CommandContextMixIn: + def __init__(self) -> None: + super().__init__() + self._in_main_context = False + self._main_context = ExitStack() + + @contextmanager + def main_context(self) -> Generator[None, None, None]: + assert not self._in_main_context + + self._in_main_context = True + try: + with self._main_context: + yield + finally: + self._in_main_context = False + + def enter_context(self, context_provider: ContextManager[_T]) -> _T: + assert self._in_main_context + + return self._main_context.enter_context(context_provider) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/index_command.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/index_command.py new file mode 100644 index 0000000000000000000000000000000000000000..295108ed605d678c6d26f0a489481eb381d02e7e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/index_command.py @@ -0,0 +1,171 @@ +""" +Contains command classes which may interact with an index / the network. + +Unlike its sister module, req_command, this module still uses lazy imports +so commands which don't always hit the network (e.g. list w/o --outdated or +--uptodate) don't need waste time importing PipSession and friends. +""" + +import logging +import os +import sys +from optparse import Values +from typing import TYPE_CHECKING, List, Optional + +from pip._vendor import certifi + +from pip._internal.cli.base_command import Command +from pip._internal.cli.command_context import CommandContextMixIn + +if TYPE_CHECKING: + from ssl import SSLContext + + from pip._internal.network.session import PipSession + +logger = logging.getLogger(__name__) + + +def _create_truststore_ssl_context() -> Optional["SSLContext"]: + if sys.version_info < (3, 10): + logger.debug("Disabling truststore because Python version isn't 3.10+") + return None + + try: + import ssl + except ImportError: + logger.warning("Disabling truststore since ssl support is missing") + return None + + try: + from pip._vendor import truststore + except ImportError: + logger.warning("Disabling truststore because platform isn't supported") + return None + + ctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.load_verify_locations(certifi.where()) + return ctx + + +class SessionCommandMixin(CommandContextMixIn): + """ + A class mixin for command classes needing _build_session(). + """ + + def __init__(self) -> None: + super().__init__() + self._session: Optional[PipSession] = None + + @classmethod + def _get_index_urls(cls, options: Values) -> Optional[List[str]]: + """Return a list of index urls from user-provided options.""" + index_urls = [] + if not getattr(options, "no_index", False): + url = getattr(options, "index_url", None) + if url: + index_urls.append(url) + urls = getattr(options, "extra_index_urls", None) + if urls: + index_urls.extend(urls) + # Return None rather than an empty list + return index_urls or None + + def get_default_session(self, options: Values) -> "PipSession": + """Get a default-managed session.""" + if self._session is None: + self._session = self.enter_context(self._build_session(options)) + # there's no type annotation on requests.Session, so it's + # automatically ContextManager[Any] and self._session becomes Any, + # then https://github.com/python/mypy/issues/7696 kicks in + assert self._session is not None + return self._session + + def _build_session( + self, + options: Values, + retries: Optional[int] = None, + timeout: Optional[int] = None, + ) -> "PipSession": + from pip._internal.network.session import PipSession + + cache_dir = options.cache_dir + assert not cache_dir or os.path.isabs(cache_dir) + + if "legacy-certs" not in options.deprecated_features_enabled: + ssl_context = _create_truststore_ssl_context() + else: + ssl_context = None + + session = PipSession( + cache=os.path.join(cache_dir, "http-v2") if cache_dir else None, + retries=retries if retries is not None else options.retries, + trusted_hosts=options.trusted_hosts, + index_urls=self._get_index_urls(options), + ssl_context=ssl_context, + ) + + # Handle custom ca-bundles from the user + if options.cert: + session.verify = options.cert + + # Handle SSL client certificate + if options.client_cert: + session.cert = options.client_cert + + # Handle timeouts + if options.timeout or timeout: + session.timeout = timeout if timeout is not None else options.timeout + + # Handle configured proxies + if options.proxy: + session.proxies = { + "http": options.proxy, + "https": options.proxy, + } + session.trust_env = False + session.pip_proxy = options.proxy + + # Determine if we can prompt the user for authentication or not + session.auth.prompting = not options.no_input + session.auth.keyring_provider = options.keyring_provider + + return session + + +def _pip_self_version_check(session: "PipSession", options: Values) -> None: + from pip._internal.self_outdated_check import pip_self_version_check as check + + check(session, options) + + +class IndexGroupCommand(Command, SessionCommandMixin): + """ + Abstract base class for commands with the index_group options. + + This also corresponds to the commands that permit the pip version check. + """ + + def handle_pip_version_check(self, options: Values) -> None: + """ + Do the pip version check if not disabled. + + This overrides the default behavior of not doing the check. + """ + # Make sure the index_group options are present. + assert hasattr(options, "no_index") + + if options.disable_pip_version_check or options.no_index: + return + + try: + # Otherwise, check if we're using the latest version of pip available. + session = self._build_session( + options, + retries=0, + timeout=min(5, options.timeout), + ) + with session: + _pip_self_version_check(session, options) + except Exception: + logger.warning("There was an error checking the latest version of pip.") + logger.debug("See below for error", exc_info=True) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/main.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/main.py new file mode 100644 index 0000000000000000000000000000000000000000..563ac79c98460809f8f349d254a4f16dbda2f7e0 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/main.py @@ -0,0 +1,80 @@ +"""Primary application entrypoint. +""" + +import locale +import logging +import os +import sys +import warnings +from typing import List, Optional + +from pip._internal.cli.autocompletion import autocomplete +from pip._internal.cli.main_parser import parse_command +from pip._internal.commands import create_command +from pip._internal.exceptions import PipError +from pip._internal.utils import deprecation + +logger = logging.getLogger(__name__) + + +# Do not import and use main() directly! Using it directly is actively +# discouraged by pip's maintainers. The name, location and behavior of +# this function is subject to change, so calling it directly is not +# portable across different pip versions. + +# In addition, running pip in-process is unsupported and unsafe. This is +# elaborated in detail at +# https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program. +# That document also provides suggestions that should work for nearly +# all users that are considering importing and using main() directly. + +# However, we know that certain users will still want to invoke pip +# in-process. If you understand and accept the implications of using pip +# in an unsupported manner, the best approach is to use runpy to avoid +# depending on the exact location of this entry point. + +# The following example shows how to use runpy to invoke pip in that +# case: +# +# sys.argv = ["pip", your, args, here] +# runpy.run_module("pip", run_name="__main__") +# +# Note that this will exit the process after running, unlike a direct +# call to main. As it is not safe to do any processing after calling +# main, this should not be an issue in practice. + + +def main(args: Optional[List[str]] = None) -> int: + if args is None: + args = sys.argv[1:] + + # Suppress the pkg_resources deprecation warning + # Note - we use a module of .*pkg_resources to cover + # the normal case (pip._vendor.pkg_resources) and the + # devendored case (a bare pkg_resources) + warnings.filterwarnings( + action="ignore", category=DeprecationWarning, module=".*pkg_resources" + ) + + # Configure our deprecation warnings to be sent through loggers + deprecation.install_warning_logger() + + autocomplete() + + try: + cmd_name, cmd_args = parse_command(args) + except PipError as exc: + sys.stderr.write(f"ERROR: {exc}") + sys.stderr.write(os.linesep) + sys.exit(1) + + # Needed for locale.getpreferredencoding(False) to work + # in pip._internal.utils.encoding.auto_decode + try: + locale.setlocale(locale.LC_ALL, "") + except locale.Error as e: + # setlocale can apparently crash if locale are uninitialized + logger.debug("Ignoring error %s when setting locale", e) + command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) + + return command.main(cmd_args) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/main_parser.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/main_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..5ade356b9c2f3e375bf598635627870f248c0cc3 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/main_parser.py @@ -0,0 +1,134 @@ +"""A single place for constructing and exposing the main parser +""" + +import os +import subprocess +import sys +from typing import List, Optional, Tuple + +from pip._internal.build_env import get_runnable_pip +from pip._internal.cli import cmdoptions +from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter +from pip._internal.commands import commands_dict, get_similar_commands +from pip._internal.exceptions import CommandError +from pip._internal.utils.misc import get_pip_version, get_prog + +__all__ = ["create_main_parser", "parse_command"] + + +def create_main_parser() -> ConfigOptionParser: + """Creates and returns the main parser for pip's CLI""" + + parser = ConfigOptionParser( + usage="\n%prog [options]", + add_help_option=False, + formatter=UpdatingDefaultsHelpFormatter(), + name="global", + prog=get_prog(), + ) + parser.disable_interspersed_args() + + parser.version = get_pip_version() + + # add the general options + gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser) + parser.add_option_group(gen_opts) + + # so the help formatter knows + parser.main = True # type: ignore + + # create command listing for description + description = [""] + [ + f"{name:27} {command_info.summary}" + for name, command_info in commands_dict.items() + ] + parser.description = "\n".join(description) + + return parser + + +def identify_python_interpreter(python: str) -> Optional[str]: + # If the named file exists, use it. + # If it's a directory, assume it's a virtual environment and + # look for the environment's Python executable. + if os.path.exists(python): + if os.path.isdir(python): + # bin/python for Unix, Scripts/python.exe for Windows + # Try both in case of odd cases like cygwin. + for exe in ("bin/python", "Scripts/python.exe"): + py = os.path.join(python, exe) + if os.path.exists(py): + return py + else: + return python + + # Could not find the interpreter specified + return None + + +def parse_command(args: List[str]) -> Tuple[str, List[str]]: + parser = create_main_parser() + + # Note: parser calls disable_interspersed_args(), so the result of this + # call is to split the initial args into the general options before the + # subcommand and everything else. + # For example: + # args: ['--timeout=5', 'install', '--user', 'INITools'] + # general_options: ['--timeout==5'] + # args_else: ['install', '--user', 'INITools'] + general_options, args_else = parser.parse_args(args) + + # --python + if general_options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ: + # Re-invoke pip using the specified Python interpreter + interpreter = identify_python_interpreter(general_options.python) + if interpreter is None: + raise CommandError( + f"Could not locate Python interpreter {general_options.python}" + ) + + pip_cmd = [ + interpreter, + get_runnable_pip(), + ] + pip_cmd.extend(args) + + # Set a flag so the child doesn't re-invoke itself, causing + # an infinite loop. + os.environ["_PIP_RUNNING_IN_SUBPROCESS"] = "1" + returncode = 0 + try: + proc = subprocess.run(pip_cmd) + returncode = proc.returncode + except (subprocess.SubprocessError, OSError) as exc: + raise CommandError(f"Failed to run pip under {interpreter}: {exc}") + sys.exit(returncode) + + # --version + if general_options.version: + sys.stdout.write(parser.version) + sys.stdout.write(os.linesep) + sys.exit() + + # pip || pip help -> print_help() + if not args_else or (args_else[0] == "help" and len(args_else) == 1): + parser.print_help() + sys.exit() + + # the subcommand name + cmd_name = args_else[0] + + if cmd_name not in commands_dict: + guess = get_similar_commands(cmd_name) + + msg = [f'unknown command "{cmd_name}"'] + if guess: + msg.append(f'maybe you meant "{guess}"') + + raise CommandError(" - ".join(msg)) + + # all the args without the subcommand + cmd_args = args[:] + cmd_args.remove(cmd_name) + + return cmd_name, cmd_args diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/parser.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..bc4aca032d4adddbb7b9d8b0c981187aa11e40fc --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/parser.py @@ -0,0 +1,294 @@ +"""Base option parser setup""" + +import logging +import optparse +import shutil +import sys +import textwrap +from contextlib import suppress +from typing import Any, Dict, Generator, List, NoReturn, Optional, Tuple + +from pip._internal.cli.status_codes import UNKNOWN_ERROR +from pip._internal.configuration import Configuration, ConfigurationError +from pip._internal.utils.misc import redact_auth_from_url, strtobool + +logger = logging.getLogger(__name__) + + +class PrettyHelpFormatter(optparse.IndentedHelpFormatter): + """A prettier/less verbose help formatter for optparse.""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + # help position must be aligned with __init__.parseopts.description + kwargs["max_help_position"] = 30 + kwargs["indent_increment"] = 1 + kwargs["width"] = shutil.get_terminal_size()[0] - 2 + super().__init__(*args, **kwargs) + + def format_option_strings(self, option: optparse.Option) -> str: + return self._format_option_strings(option) + + def _format_option_strings( + self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", " + ) -> str: + """ + Return a comma-separated list of option strings and metavars. + + :param option: tuple of (short opt, long opt), e.g: ('-f', '--format') + :param mvarfmt: metavar format string + :param optsep: separator + """ + opts = [] + + if option._short_opts: + opts.append(option._short_opts[0]) + if option._long_opts: + opts.append(option._long_opts[0]) + if len(opts) > 1: + opts.insert(1, optsep) + + if option.takes_value(): + assert option.dest is not None + metavar = option.metavar or option.dest.lower() + opts.append(mvarfmt.format(metavar.lower())) + + return "".join(opts) + + def format_heading(self, heading: str) -> str: + if heading == "Options": + return "" + return heading + ":\n" + + def format_usage(self, usage: str) -> str: + """ + Ensure there is only one newline between usage and the first heading + if there is no description. + """ + msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " ")) + return msg + + def format_description(self, description: Optional[str]) -> str: + # leave full control over description to us + if description: + if hasattr(self.parser, "main"): + label = "Commands" + else: + label = "Description" + # some doc strings have initial newlines, some don't + description = description.lstrip("\n") + # some doc strings have final newlines and spaces, some don't + description = description.rstrip() + # dedent, then reindent + description = self.indent_lines(textwrap.dedent(description), " ") + description = f"{label}:\n{description}\n" + return description + else: + return "" + + def format_epilog(self, epilog: Optional[str]) -> str: + # leave full control over epilog to us + if epilog: + return epilog + else: + return "" + + def indent_lines(self, text: str, indent: str) -> str: + new_lines = [indent + line for line in text.split("\n")] + return "\n".join(new_lines) + + +class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter): + """Custom help formatter for use in ConfigOptionParser. + + This is updates the defaults before expanding them, allowing + them to show up correctly in the help listing. + + Also redact auth from url type options + """ + + def expand_default(self, option: optparse.Option) -> str: + default_values = None + if self.parser is not None: + assert isinstance(self.parser, ConfigOptionParser) + self.parser._update_defaults(self.parser.defaults) + assert option.dest is not None + default_values = self.parser.defaults.get(option.dest) + help_text = super().expand_default(option) + + if default_values and option.metavar == "URL": + if isinstance(default_values, str): + default_values = [default_values] + + # If its not a list, we should abort and just return the help text + if not isinstance(default_values, list): + default_values = [] + + for val in default_values: + help_text = help_text.replace(val, redact_auth_from_url(val)) + + return help_text + + +class CustomOptionParser(optparse.OptionParser): + def insert_option_group( + self, idx: int, *args: Any, **kwargs: Any + ) -> optparse.OptionGroup: + """Insert an OptionGroup at a given position.""" + group = self.add_option_group(*args, **kwargs) + + self.option_groups.pop() + self.option_groups.insert(idx, group) + + return group + + @property + def option_list_all(self) -> List[optparse.Option]: + """Get a list of all options, including those in option groups.""" + res = self.option_list[:] + for i in self.option_groups: + res.extend(i.option_list) + + return res + + +class ConfigOptionParser(CustomOptionParser): + """Custom option parser which updates its defaults by checking the + configuration files and environmental variables""" + + def __init__( + self, + *args: Any, + name: str, + isolated: bool = False, + **kwargs: Any, + ) -> None: + self.name = name + self.config = Configuration(isolated) + + assert self.name + super().__init__(*args, **kwargs) + + def check_default(self, option: optparse.Option, key: str, val: Any) -> Any: + try: + return option.check_value(key, val) + except optparse.OptionValueError as exc: + print(f"An error occurred during configuration: {exc}") + sys.exit(3) + + def _get_ordered_configuration_items( + self, + ) -> Generator[Tuple[str, Any], None, None]: + # Configuration gives keys in an unordered manner. Order them. + override_order = ["global", self.name, ":env:"] + + # Pool the options into different groups + section_items: Dict[str, List[Tuple[str, Any]]] = { + name: [] for name in override_order + } + for section_key, val in self.config.items(): + # ignore empty values + if not val: + logger.debug( + "Ignoring configuration key '%s' as it's value is empty.", + section_key, + ) + continue + + section, key = section_key.split(".", 1) + if section in override_order: + section_items[section].append((key, val)) + + # Yield each group in their override order + for section in override_order: + for key, val in section_items[section]: + yield key, val + + def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]: + """Updates the given defaults with values from the config files and + the environ. Does a little special handling for certain types of + options (lists).""" + + # Accumulate complex default state. + self.values = optparse.Values(self.defaults) + late_eval = set() + # Then set the options with those values + for key, val in self._get_ordered_configuration_items(): + # '--' because configuration supports only long names + option = self.get_option("--" + key) + + # Ignore options not present in this parser. E.g. non-globals put + # in [global] by users that want them to apply to all applicable + # commands. + if option is None: + continue + + assert option.dest is not None + + if option.action in ("store_true", "store_false"): + try: + val = strtobool(val) + except ValueError: + self.error( + f"{val} is not a valid value for {key} option, " + "please specify a boolean value like yes/no, " + "true/false or 1/0 instead." + ) + elif option.action == "count": + with suppress(ValueError): + val = strtobool(val) + with suppress(ValueError): + val = int(val) + if not isinstance(val, int) or val < 0: + self.error( + f"{val} is not a valid value for {key} option, " + "please instead specify either a non-negative integer " + "or a boolean value like yes/no or false/true " + "which is equivalent to 1/0." + ) + elif option.action == "append": + val = val.split() + val = [self.check_default(option, key, v) for v in val] + elif option.action == "callback": + assert option.callback is not None + late_eval.add(option.dest) + opt_str = option.get_opt_string() + val = option.convert_value(opt_str, val) + # From take_action + args = option.callback_args or () + kwargs = option.callback_kwargs or {} + option.callback(option, opt_str, val, self, *args, **kwargs) + else: + val = self.check_default(option, key, val) + + defaults[option.dest] = val + + for key in late_eval: + defaults[key] = getattr(self.values, key) + self.values = None + return defaults + + def get_default_values(self) -> optparse.Values: + """Overriding to make updating the defaults after instantiation of + the option parser possible, _update_defaults() does the dirty work.""" + if not self.process_default_values: + # Old, pre-Optik 1.5 behaviour. + return optparse.Values(self.defaults) + + # Load the configuration, or error out in case of an error + try: + self.config.load() + except ConfigurationError as err: + self.exit(UNKNOWN_ERROR, str(err)) + + defaults = self._update_defaults(self.defaults.copy()) # ours + for option in self._get_all_options(): + assert option.dest is not None + default = defaults.get(option.dest) + if isinstance(default, str): + opt_str = option.get_opt_string() + defaults[option.dest] = option.check_value(opt_str, default) + return optparse.Values(defaults) + + def error(self, msg: str) -> NoReturn: + self.print_usage(sys.stderr) + self.exit(UNKNOWN_ERROR, f"{msg}\n") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/progress_bars.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/progress_bars.py new file mode 100644 index 0000000000000000000000000000000000000000..3d9dde8ed88fd36ec9b11094427201529dcd0a40 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/progress_bars.py @@ -0,0 +1,94 @@ +import functools +import sys +from typing import Callable, Generator, Iterable, Iterator, Optional, Tuple + +from pip._vendor.rich.progress import ( + BarColumn, + DownloadColumn, + FileSizeColumn, + Progress, + ProgressColumn, + SpinnerColumn, + TextColumn, + TimeElapsedColumn, + TimeRemainingColumn, + TransferSpeedColumn, +) + +from pip._internal.cli.spinners import RateLimiter +from pip._internal.utils.logging import get_indentation + +DownloadProgressRenderer = Callable[[Iterable[bytes]], Iterator[bytes]] + + +def _rich_progress_bar( + iterable: Iterable[bytes], + *, + bar_type: str, + size: Optional[int], +) -> Generator[bytes, None, None]: + assert bar_type == "on", "This should only be used in the default mode." + + if not size: + total = float("inf") + columns: Tuple[ProgressColumn, ...] = ( + TextColumn("[progress.description]{task.description}"), + SpinnerColumn("line", speed=1.5), + FileSizeColumn(), + TransferSpeedColumn(), + TimeElapsedColumn(), + ) + else: + total = size + columns = ( + TextColumn("[progress.description]{task.description}"), + BarColumn(), + DownloadColumn(), + TransferSpeedColumn(), + TextColumn("eta"), + TimeRemainingColumn(), + ) + + progress = Progress(*columns, refresh_per_second=5) + task_id = progress.add_task(" " * (get_indentation() + 2), total=total) + with progress: + for chunk in iterable: + yield chunk + progress.update(task_id, advance=len(chunk)) + + +def _raw_progress_bar( + iterable: Iterable[bytes], + *, + size: Optional[int], +) -> Generator[bytes, None, None]: + def write_progress(current: int, total: int) -> None: + sys.stdout.write(f"Progress {current} of {total}\n") + sys.stdout.flush() + + current = 0 + total = size or 0 + rate_limiter = RateLimiter(0.25) + + write_progress(current, total) + for chunk in iterable: + current += len(chunk) + if rate_limiter.ready() or current == total: + write_progress(current, total) + rate_limiter.reset() + yield chunk + + +def get_download_progress_renderer( + *, bar_type: str, size: Optional[int] = None +) -> DownloadProgressRenderer: + """Get an object that can be used to render the download progress. + + Returns a callable, that takes an iterable to "wrap". + """ + if bar_type == "on": + return functools.partial(_rich_progress_bar, bar_type=bar_type, size=size) + elif bar_type == "raw": + return functools.partial(_raw_progress_bar, size=size) + else: + return iter # no-op, when passed an iterator diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/req_command.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/req_command.py new file mode 100644 index 0000000000000000000000000000000000000000..92900f94ff4cb4b43126ca92964655fcb9016f50 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/req_command.py @@ -0,0 +1,329 @@ +"""Contains the RequirementCommand base class. + +This class is in a separate module so the commands that do not always +need PackageFinder capability don't unnecessarily import the +PackageFinder machinery and all its vendored dependencies, etc. +""" + +import logging +from functools import partial +from optparse import Values +from typing import Any, List, Optional, Tuple + +from pip._internal.cache import WheelCache +from pip._internal.cli import cmdoptions +from pip._internal.cli.index_command import IndexGroupCommand +from pip._internal.cli.index_command import SessionCommandMixin as SessionCommandMixin +from pip._internal.exceptions import CommandError, PreviousBuildDirError +from pip._internal.index.collector import LinkCollector +from pip._internal.index.package_finder import PackageFinder +from pip._internal.models.selection_prefs import SelectionPreferences +from pip._internal.models.target_python import TargetPython +from pip._internal.network.session import PipSession +from pip._internal.operations.build.build_tracker import BuildTracker +from pip._internal.operations.prepare import RequirementPreparer +from pip._internal.req.constructors import ( + install_req_from_editable, + install_req_from_line, + install_req_from_parsed_requirement, + install_req_from_req_string, +) +from pip._internal.req.req_file import parse_requirements +from pip._internal.req.req_install import InstallRequirement +from pip._internal.resolution.base import BaseResolver +from pip._internal.utils.temp_dir import ( + TempDirectory, + TempDirectoryTypeRegistry, + tempdir_kinds, +) + +logger = logging.getLogger(__name__) + + +KEEPABLE_TEMPDIR_TYPES = [ + tempdir_kinds.BUILD_ENV, + tempdir_kinds.EPHEM_WHEEL_CACHE, + tempdir_kinds.REQ_BUILD, +] + + +def with_cleanup(func: Any) -> Any: + """Decorator for common logic related to managing temporary + directories. + """ + + def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None: + for t in KEEPABLE_TEMPDIR_TYPES: + registry.set_delete(t, False) + + def wrapper( + self: RequirementCommand, options: Values, args: List[Any] + ) -> Optional[int]: + assert self.tempdir_registry is not None + if options.no_clean: + configure_tempdir_registry(self.tempdir_registry) + + try: + return func(self, options, args) + except PreviousBuildDirError: + # This kind of conflict can occur when the user passes an explicit + # build directory with a pre-existing folder. In that case we do + # not want to accidentally remove it. + configure_tempdir_registry(self.tempdir_registry) + raise + + return wrapper + + +class RequirementCommand(IndexGroupCommand): + def __init__(self, *args: Any, **kw: Any) -> None: + super().__init__(*args, **kw) + + self.cmd_opts.add_option(cmdoptions.no_clean()) + + @staticmethod + def determine_resolver_variant(options: Values) -> str: + """Determines which resolver should be used, based on the given options.""" + if "legacy-resolver" in options.deprecated_features_enabled: + return "legacy" + + return "resolvelib" + + @classmethod + def make_requirement_preparer( + cls, + temp_build_dir: TempDirectory, + options: Values, + build_tracker: BuildTracker, + session: PipSession, + finder: PackageFinder, + use_user_site: bool, + download_dir: Optional[str] = None, + verbosity: int = 0, + ) -> RequirementPreparer: + """ + Create a RequirementPreparer instance for the given parameters. + """ + temp_build_dir_path = temp_build_dir.path + assert temp_build_dir_path is not None + legacy_resolver = False + + resolver_variant = cls.determine_resolver_variant(options) + if resolver_variant == "resolvelib": + lazy_wheel = "fast-deps" in options.features_enabled + if lazy_wheel: + logger.warning( + "pip is using lazily downloaded wheels using HTTP " + "range requests to obtain dependency information. " + "This experimental feature is enabled through " + "--use-feature=fast-deps and it is not ready for " + "production." + ) + else: + legacy_resolver = True + lazy_wheel = False + if "fast-deps" in options.features_enabled: + logger.warning( + "fast-deps has no effect when used with the legacy resolver." + ) + + return RequirementPreparer( + build_dir=temp_build_dir_path, + src_dir=options.src_dir, + download_dir=download_dir, + build_isolation=options.build_isolation, + check_build_deps=options.check_build_deps, + build_tracker=build_tracker, + session=session, + progress_bar=options.progress_bar, + finder=finder, + require_hashes=options.require_hashes, + use_user_site=use_user_site, + lazy_wheel=lazy_wheel, + verbosity=verbosity, + legacy_resolver=legacy_resolver, + ) + + @classmethod + def make_resolver( + cls, + preparer: RequirementPreparer, + finder: PackageFinder, + options: Values, + wheel_cache: Optional[WheelCache] = None, + use_user_site: bool = False, + ignore_installed: bool = True, + ignore_requires_python: bool = False, + force_reinstall: bool = False, + upgrade_strategy: str = "to-satisfy-only", + use_pep517: Optional[bool] = None, + py_version_info: Optional[Tuple[int, ...]] = None, + ) -> BaseResolver: + """ + Create a Resolver instance for the given parameters. + """ + make_install_req = partial( + install_req_from_req_string, + isolated=options.isolated_mode, + use_pep517=use_pep517, + ) + resolver_variant = cls.determine_resolver_variant(options) + # The long import name and duplicated invocation is needed to convince + # Mypy into correctly typechecking. Otherwise it would complain the + # "Resolver" class being redefined. + if resolver_variant == "resolvelib": + import pip._internal.resolution.resolvelib.resolver + + return pip._internal.resolution.resolvelib.resolver.Resolver( + preparer=preparer, + finder=finder, + wheel_cache=wheel_cache, + make_install_req=make_install_req, + use_user_site=use_user_site, + ignore_dependencies=options.ignore_dependencies, + ignore_installed=ignore_installed, + ignore_requires_python=ignore_requires_python, + force_reinstall=force_reinstall, + upgrade_strategy=upgrade_strategy, + py_version_info=py_version_info, + ) + import pip._internal.resolution.legacy.resolver + + return pip._internal.resolution.legacy.resolver.Resolver( + preparer=preparer, + finder=finder, + wheel_cache=wheel_cache, + make_install_req=make_install_req, + use_user_site=use_user_site, + ignore_dependencies=options.ignore_dependencies, + ignore_installed=ignore_installed, + ignore_requires_python=ignore_requires_python, + force_reinstall=force_reinstall, + upgrade_strategy=upgrade_strategy, + py_version_info=py_version_info, + ) + + def get_requirements( + self, + args: List[str], + options: Values, + finder: PackageFinder, + session: PipSession, + ) -> List[InstallRequirement]: + """ + Parse command-line arguments into the corresponding requirements. + """ + requirements: List[InstallRequirement] = [] + for filename in options.constraints: + for parsed_req in parse_requirements( + filename, + constraint=True, + finder=finder, + options=options, + session=session, + ): + req_to_add = install_req_from_parsed_requirement( + parsed_req, + isolated=options.isolated_mode, + user_supplied=False, + ) + requirements.append(req_to_add) + + for req in args: + req_to_add = install_req_from_line( + req, + comes_from=None, + isolated=options.isolated_mode, + use_pep517=options.use_pep517, + user_supplied=True, + config_settings=getattr(options, "config_settings", None), + ) + requirements.append(req_to_add) + + for req in options.editables: + req_to_add = install_req_from_editable( + req, + user_supplied=True, + isolated=options.isolated_mode, + use_pep517=options.use_pep517, + config_settings=getattr(options, "config_settings", None), + ) + requirements.append(req_to_add) + + # NOTE: options.require_hashes may be set if --require-hashes is True + for filename in options.requirements: + for parsed_req in parse_requirements( + filename, finder=finder, options=options, session=session + ): + req_to_add = install_req_from_parsed_requirement( + parsed_req, + isolated=options.isolated_mode, + use_pep517=options.use_pep517, + user_supplied=True, + config_settings=( + parsed_req.options.get("config_settings") + if parsed_req.options + else None + ), + ) + requirements.append(req_to_add) + + # If any requirement has hash options, enable hash checking. + if any(req.has_hash_options for req in requirements): + options.require_hashes = True + + if not (args or options.editables or options.requirements): + opts = {"name": self.name} + if options.find_links: + raise CommandError( + "You must give at least one requirement to {name} " + '(maybe you meant "pip {name} {links}"?)'.format( + **dict(opts, links=" ".join(options.find_links)) + ) + ) + else: + raise CommandError( + "You must give at least one requirement to {name} " + '(see "pip help {name}")'.format(**opts) + ) + + return requirements + + @staticmethod + def trace_basic_info(finder: PackageFinder) -> None: + """ + Trace basic information about the provided objects. + """ + # Display where finder is looking for packages + search_scope = finder.search_scope + locations = search_scope.get_formatted_locations() + if locations: + logger.info(locations) + + def _build_package_finder( + self, + options: Values, + session: PipSession, + target_python: Optional[TargetPython] = None, + ignore_requires_python: Optional[bool] = None, + ) -> PackageFinder: + """ + Create a package finder appropriate to this requirement command. + + :param ignore_requires_python: Whether to ignore incompatible + "Requires-Python" values in links. Defaults to False. + """ + link_collector = LinkCollector.create(session, options=options) + selection_prefs = SelectionPreferences( + allow_yanked=True, + format_control=options.format_control, + allow_all_prereleases=options.pre, + prefer_binary=options.prefer_binary, + ignore_requires_python=ignore_requires_python, + ) + + return PackageFinder.create( + link_collector=link_collector, + selection_prefs=selection_prefs, + target_python=target_python, + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/spinners.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/spinners.py new file mode 100644 index 0000000000000000000000000000000000000000..cf2b976f377c2656afb3d84add8d30b0fc280c03 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/spinners.py @@ -0,0 +1,159 @@ +import contextlib +import itertools +import logging +import sys +import time +from typing import IO, Generator, Optional + +from pip._internal.utils.compat import WINDOWS +from pip._internal.utils.logging import get_indentation + +logger = logging.getLogger(__name__) + + +class SpinnerInterface: + def spin(self) -> None: + raise NotImplementedError() + + def finish(self, final_status: str) -> None: + raise NotImplementedError() + + +class InteractiveSpinner(SpinnerInterface): + def __init__( + self, + message: str, + file: Optional[IO[str]] = None, + spin_chars: str = "-\\|/", + # Empirically, 8 updates/second looks nice + min_update_interval_seconds: float = 0.125, + ): + self._message = message + if file is None: + file = sys.stdout + self._file = file + self._rate_limiter = RateLimiter(min_update_interval_seconds) + self._finished = False + + self._spin_cycle = itertools.cycle(spin_chars) + + self._file.write(" " * get_indentation() + self._message + " ... ") + self._width = 0 + + def _write(self, status: str) -> None: + assert not self._finished + # Erase what we wrote before by backspacing to the beginning, writing + # spaces to overwrite the old text, and then backspacing again + backup = "\b" * self._width + self._file.write(backup + " " * self._width + backup) + # Now we have a blank slate to add our status + self._file.write(status) + self._width = len(status) + self._file.flush() + self._rate_limiter.reset() + + def spin(self) -> None: + if self._finished: + return + if not self._rate_limiter.ready(): + return + self._write(next(self._spin_cycle)) + + def finish(self, final_status: str) -> None: + if self._finished: + return + self._write(final_status) + self._file.write("\n") + self._file.flush() + self._finished = True + + +# Used for dumb terminals, non-interactive installs (no tty), etc. +# We still print updates occasionally (once every 60 seconds by default) to +# act as a keep-alive for systems like Travis-CI that take lack-of-output as +# an indication that a task has frozen. +class NonInteractiveSpinner(SpinnerInterface): + def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None: + self._message = message + self._finished = False + self._rate_limiter = RateLimiter(min_update_interval_seconds) + self._update("started") + + def _update(self, status: str) -> None: + assert not self._finished + self._rate_limiter.reset() + logger.info("%s: %s", self._message, status) + + def spin(self) -> None: + if self._finished: + return + if not self._rate_limiter.ready(): + return + self._update("still running...") + + def finish(self, final_status: str) -> None: + if self._finished: + return + self._update(f"finished with status '{final_status}'") + self._finished = True + + +class RateLimiter: + def __init__(self, min_update_interval_seconds: float) -> None: + self._min_update_interval_seconds = min_update_interval_seconds + self._last_update: float = 0 + + def ready(self) -> bool: + now = time.time() + delta = now - self._last_update + return delta >= self._min_update_interval_seconds + + def reset(self) -> None: + self._last_update = time.time() + + +@contextlib.contextmanager +def open_spinner(message: str) -> Generator[SpinnerInterface, None, None]: + # Interactive spinner goes directly to sys.stdout rather than being routed + # through the logging system, but it acts like it has level INFO, + # i.e. it's only displayed if we're at level INFO or better. + # Non-interactive spinner goes through the logging system, so it is always + # in sync with logging configuration. + if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO: + spinner: SpinnerInterface = InteractiveSpinner(message) + else: + spinner = NonInteractiveSpinner(message) + try: + with hidden_cursor(sys.stdout): + yield spinner + except KeyboardInterrupt: + spinner.finish("canceled") + raise + except Exception: + spinner.finish("error") + raise + else: + spinner.finish("done") + + +HIDE_CURSOR = "\x1b[?25l" +SHOW_CURSOR = "\x1b[?25h" + + +@contextlib.contextmanager +def hidden_cursor(file: IO[str]) -> Generator[None, None, None]: + # The Windows terminal does not support the hide/show cursor ANSI codes, + # even via colorama. So don't even try. + if WINDOWS: + yield + # We don't want to clutter the output with control characters if we're + # writing to a file, or if the user is running with --quiet. + # See https://github.com/pypa/pip/issues/3418 + elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO: + yield + else: + file.write(HIDE_CURSOR) + try: + yield + finally: + file.write(SHOW_CURSOR) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/status_codes.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/status_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..5e29502cddfa9a9887a93399ab4193fb75dfe605 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/cli/status_codes.py @@ -0,0 +1,6 @@ +SUCCESS = 0 +ERROR = 1 +UNKNOWN_ERROR = 2 +VIRTUALENV_NOT_FOUND = 3 +PREVIOUS_BUILD_DIR_ERROR = 4 +NO_MATCHES_FOUND = 23 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..858a41014169b8f0eb1b905fa3bb69c753a1bda5 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__init__.py @@ -0,0 +1,132 @@ +""" +Package containing all pip commands +""" + +import importlib +from collections import namedtuple +from typing import Any, Dict, Optional + +from pip._internal.cli.base_command import Command + +CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary") + +# This dictionary does a bunch of heavy lifting for help output: +# - Enables avoiding additional (costly) imports for presenting `--help`. +# - The ordering matters for help display. +# +# Even though the module path starts with the same "pip._internal.commands" +# prefix, the full path makes testing easier (specifically when modifying +# `commands_dict` in test setup / teardown). +commands_dict: Dict[str, CommandInfo] = { + "install": CommandInfo( + "pip._internal.commands.install", + "InstallCommand", + "Install packages.", + ), + "download": CommandInfo( + "pip._internal.commands.download", + "DownloadCommand", + "Download packages.", + ), + "uninstall": CommandInfo( + "pip._internal.commands.uninstall", + "UninstallCommand", + "Uninstall packages.", + ), + "freeze": CommandInfo( + "pip._internal.commands.freeze", + "FreezeCommand", + "Output installed packages in requirements format.", + ), + "inspect": CommandInfo( + "pip._internal.commands.inspect", + "InspectCommand", + "Inspect the python environment.", + ), + "list": CommandInfo( + "pip._internal.commands.list", + "ListCommand", + "List installed packages.", + ), + "show": CommandInfo( + "pip._internal.commands.show", + "ShowCommand", + "Show information about installed packages.", + ), + "check": CommandInfo( + "pip._internal.commands.check", + "CheckCommand", + "Verify installed packages have compatible dependencies.", + ), + "config": CommandInfo( + "pip._internal.commands.configuration", + "ConfigurationCommand", + "Manage local and global configuration.", + ), + "search": CommandInfo( + "pip._internal.commands.search", + "SearchCommand", + "Search PyPI for packages.", + ), + "cache": CommandInfo( + "pip._internal.commands.cache", + "CacheCommand", + "Inspect and manage pip's wheel cache.", + ), + "index": CommandInfo( + "pip._internal.commands.index", + "IndexCommand", + "Inspect information available from package indexes.", + ), + "wheel": CommandInfo( + "pip._internal.commands.wheel", + "WheelCommand", + "Build wheels from your requirements.", + ), + "hash": CommandInfo( + "pip._internal.commands.hash", + "HashCommand", + "Compute hashes of package archives.", + ), + "completion": CommandInfo( + "pip._internal.commands.completion", + "CompletionCommand", + "A helper command used for command completion.", + ), + "debug": CommandInfo( + "pip._internal.commands.debug", + "DebugCommand", + "Show information useful for debugging.", + ), + "help": CommandInfo( + "pip._internal.commands.help", + "HelpCommand", + "Show help for commands.", + ), +} + + +def create_command(name: str, **kwargs: Any) -> Command: + """ + Create an instance of the Command class with the given name. + """ + module_path, class_name, summary = commands_dict[name] + module = importlib.import_module(module_path) + command_class = getattr(module, class_name) + command = command_class(name=name, summary=summary, **kwargs) + + return command + + +def get_similar_commands(name: str) -> Optional[str]: + """Command name auto-correct.""" + from difflib import get_close_matches + + name = name.lower() + + close_commands = get_close_matches(name, commands_dict.keys()) + + if close_commands: + return close_commands[0] + else: + return None diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42d3f0b7ea532497e874da9068d2a9cf41b9170b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/cache.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c496464ec50e47f7ae8d14eb63c337cb3c2423f1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/cache.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/check.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/check.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3cc738260522f6fdb632b9200ba2b8deceafe1b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/check.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/completion.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/completion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..084c42ce764fa6a213da96b0537188f6c2194bd3 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/completion.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/configuration.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/configuration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8d9bbd785cecd2b5badc929dab3e63367bff38a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/configuration.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/debug.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/debug.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d134b628b1c9d56ca051bbce079acd0990396a58 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/debug.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/download.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/download.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32deb0312125a2e85f0a81186997129416c59137 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/download.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/freeze.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/freeze.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a9877b66eeec7a246c712064be7b4c2970b9526 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/freeze.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/hash.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/hash.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..618b482d02e6e71a57bd2e920175d79a2e03017a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/hash.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/help.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/help.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bf599433178cd45f02af6f29ddd5554d1f87a4d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/help.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/index.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/index.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7dbdacf7ff35b40df63afb7b80a0b65c4bb8f63 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/index.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/inspect.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/inspect.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8141f4db3b3f792a39e6c795c5efd654339d4cc Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/inspect.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/install.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/install.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..381017149260b0106fe9766a6e616b2f9cd5e057 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/install.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/list.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/list.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a59d06762a821dd0ac72304fbd1f0b491cc7081c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/list.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/search.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/search.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78173ca9345530c2dbe6a58095689c99d79a3372 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/search.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/show.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/show.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cf739307233e5e4d0c5fbacf1d9cd3d16450bcf Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/show.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/uninstall.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/uninstall.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a19fe2b8bd3920d87422343159bea67cdfbfaa6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/uninstall.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/wheel.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/wheel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca426c2b3fa62a27758c1c095bfb4b6b90927b8a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/__pycache__/wheel.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/cache.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..ad65641edb262fd85c5065c76d6a81aae1168192 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/cache.py @@ -0,0 +1,228 @@ +import os +import textwrap +from optparse import Values +from typing import Any, List + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.exceptions import CommandError, PipError +from pip._internal.utils import filesystem +from pip._internal.utils.logging import getLogger +from pip._internal.utils.misc import format_size + +logger = getLogger(__name__) + + +class CacheCommand(Command): + """ + Inspect and manage pip's wheel cache. + + Subcommands: + + - dir: Show the cache directory. + - info: Show information about the cache. + - list: List filenames of packages stored in the cache. + - remove: Remove one or more package from the cache. + - purge: Remove all items from the cache. + + ```` can be a glob expression or a package name. + """ + + ignore_require_venv = True + usage = """ + %prog dir + %prog info + %prog list [] [--format=[human, abspath]] + %prog remove + %prog purge + """ + + def add_options(self) -> None: + self.cmd_opts.add_option( + "--format", + action="store", + dest="list_format", + default="human", + choices=("human", "abspath"), + help="Select the output format among: human (default) or abspath", + ) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + handlers = { + "dir": self.get_cache_dir, + "info": self.get_cache_info, + "list": self.list_cache_items, + "remove": self.remove_cache_items, + "purge": self.purge_cache, + } + + if not options.cache_dir: + logger.error("pip cache commands can not function since cache is disabled.") + return ERROR + + # Determine action + if not args or args[0] not in handlers: + logger.error( + "Need an action (%s) to perform.", + ", ".join(sorted(handlers)), + ) + return ERROR + + action = args[0] + + # Error handling happens here, not in the action-handlers. + try: + handlers[action](options, args[1:]) + except PipError as e: + logger.error(e.args[0]) + return ERROR + + return SUCCESS + + def get_cache_dir(self, options: Values, args: List[Any]) -> None: + if args: + raise CommandError("Too many arguments") + + logger.info(options.cache_dir) + + def get_cache_info(self, options: Values, args: List[Any]) -> None: + if args: + raise CommandError("Too many arguments") + + num_http_files = len(self._find_http_files(options)) + num_packages = len(self._find_wheels(options, "*")) + + http_cache_location = self._cache_dir(options, "http-v2") + old_http_cache_location = self._cache_dir(options, "http") + wheels_cache_location = self._cache_dir(options, "wheels") + http_cache_size = filesystem.format_size( + filesystem.directory_size(http_cache_location) + + filesystem.directory_size(old_http_cache_location) + ) + wheels_cache_size = filesystem.format_directory_size(wheels_cache_location) + + message = ( + textwrap.dedent( + """ + Package index page cache location (pip v23.3+): {http_cache_location} + Package index page cache location (older pips): {old_http_cache_location} + Package index page cache size: {http_cache_size} + Number of HTTP files: {num_http_files} + Locally built wheels location: {wheels_cache_location} + Locally built wheels size: {wheels_cache_size} + Number of locally built wheels: {package_count} + """ # noqa: E501 + ) + .format( + http_cache_location=http_cache_location, + old_http_cache_location=old_http_cache_location, + http_cache_size=http_cache_size, + num_http_files=num_http_files, + wheels_cache_location=wheels_cache_location, + package_count=num_packages, + wheels_cache_size=wheels_cache_size, + ) + .strip() + ) + + logger.info(message) + + def list_cache_items(self, options: Values, args: List[Any]) -> None: + if len(args) > 1: + raise CommandError("Too many arguments") + + if args: + pattern = args[0] + else: + pattern = "*" + + files = self._find_wheels(options, pattern) + if options.list_format == "human": + self.format_for_human(files) + else: + self.format_for_abspath(files) + + def format_for_human(self, files: List[str]) -> None: + if not files: + logger.info("No locally built wheels cached.") + return + + results = [] + for filename in files: + wheel = os.path.basename(filename) + size = filesystem.format_file_size(filename) + results.append(f" - {wheel} ({size})") + logger.info("Cache contents:\n") + logger.info("\n".join(sorted(results))) + + def format_for_abspath(self, files: List[str]) -> None: + if files: + logger.info("\n".join(sorted(files))) + + def remove_cache_items(self, options: Values, args: List[Any]) -> None: + if len(args) > 1: + raise CommandError("Too many arguments") + + if not args: + raise CommandError("Please provide a pattern") + + files = self._find_wheels(options, args[0]) + + no_matching_msg = "No matching packages" + if args[0] == "*": + # Only fetch http files if no specific pattern given + files += self._find_http_files(options) + else: + # Add the pattern to the log message + no_matching_msg += f' for pattern "{args[0]}"' + + if not files: + logger.warning(no_matching_msg) + + bytes_removed = 0 + for filename in files: + bytes_removed += os.stat(filename).st_size + os.unlink(filename) + logger.verbose("Removed %s", filename) + logger.info("Files removed: %s (%s)", len(files), format_size(bytes_removed)) + + def purge_cache(self, options: Values, args: List[Any]) -> None: + if args: + raise CommandError("Too many arguments") + + return self.remove_cache_items(options, ["*"]) + + def _cache_dir(self, options: Values, subdir: str) -> str: + return os.path.join(options.cache_dir, subdir) + + def _find_http_files(self, options: Values) -> List[str]: + old_http_dir = self._cache_dir(options, "http") + new_http_dir = self._cache_dir(options, "http-v2") + return filesystem.find_files(old_http_dir, "*") + filesystem.find_files( + new_http_dir, "*" + ) + + def _find_wheels(self, options: Values, pattern: str) -> List[str]: + wheel_dir = self._cache_dir(options, "wheels") + + # The wheel filename format, as specified in PEP 427, is: + # {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl + # + # Additionally, non-alphanumeric values in the distribution are + # normalized to underscores (_), meaning hyphens can never occur + # before `-{version}`. + # + # Given that information: + # - If the pattern we're given contains a hyphen (-), the user is + # providing at least the version. Thus, we can just append `*.whl` + # to match the rest of it. + # - If the pattern we're given doesn't contain a hyphen (-), the + # user is only providing the name. Thus, we append `-*.whl` to + # match the hyphen before the version, followed by anything else. + # + # PEP 427: https://www.python.org/dev/peps/pep-0427/ + pattern = pattern + ("*.whl" if "-" in pattern else "-*.whl") + + return filesystem.find_files(wheel_dir, pattern) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/check.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/check.py new file mode 100644 index 0000000000000000000000000000000000000000..f54a16dc0a15892d935a5e79679bab3510c8b0d5 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/check.py @@ -0,0 +1,67 @@ +import logging +from optparse import Values +from typing import List + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.metadata import get_default_environment +from pip._internal.operations.check import ( + check_package_set, + check_unsupported, + create_package_set_from_installed, +) +from pip._internal.utils.compatibility_tags import get_supported +from pip._internal.utils.misc import write_output + +logger = logging.getLogger(__name__) + + +class CheckCommand(Command): + """Verify installed packages have compatible dependencies.""" + + ignore_require_venv = True + usage = """ + %prog [options]""" + + def run(self, options: Values, args: List[str]) -> int: + package_set, parsing_probs = create_package_set_from_installed() + missing, conflicting = check_package_set(package_set) + unsupported = list( + check_unsupported( + get_default_environment().iter_installed_distributions(), + get_supported(), + ) + ) + + for project_name in missing: + version = package_set[project_name].version + for dependency in missing[project_name]: + write_output( + "%s %s requires %s, which is not installed.", + project_name, + version, + dependency[0], + ) + + for project_name in conflicting: + version = package_set[project_name].version + for dep_name, dep_version, req in conflicting[project_name]: + write_output( + "%s %s has requirement %s, but you have %s %s.", + project_name, + version, + req, + dep_name, + dep_version, + ) + for package in unsupported: + write_output( + "%s %s is not supported on this platform", + package.raw_name, + package.version, + ) + if missing or conflicting or parsing_probs or unsupported: + return ERROR + else: + write_output("No broken requirements found.") + return SUCCESS diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/completion.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/completion.py new file mode 100644 index 0000000000000000000000000000000000000000..9e89e27988368821f6936cd1e94ac9395ca0312d --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/completion.py @@ -0,0 +1,130 @@ +import sys +import textwrap +from optparse import Values +from typing import List + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.utils.misc import get_prog + +BASE_COMPLETION = """ +# pip {shell} completion start{script}# pip {shell} completion end +""" + +COMPLETION_SCRIPTS = { + "bash": """ + _pip_completion() + {{ + COMPREPLY=( $( COMP_WORDS="${{COMP_WORDS[*]}}" \\ + COMP_CWORD=$COMP_CWORD \\ + PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) ) + }} + complete -o default -F _pip_completion {prog} + """, + "zsh": """ + #compdef -P pip[0-9.]# + __pip() {{ + compadd $( COMP_WORDS="$words[*]" \\ + COMP_CWORD=$((CURRENT-1)) \\ + PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null ) + }} + if [[ $zsh_eval_context[-1] == loadautofunc ]]; then + # autoload from fpath, call function directly + __pip "$@" + else + # eval/source/. command, register function for later + compdef __pip -P 'pip[0-9.]#' + fi + """, + "fish": """ + function __fish_complete_pip + set -lx COMP_WORDS (commandline -o) "" + set -lx COMP_CWORD ( \\ + math (contains -i -- (commandline -t) $COMP_WORDS)-1 \\ + ) + set -lx PIP_AUTO_COMPLETE 1 + string split \\ -- (eval $COMP_WORDS[1]) + end + complete -fa "(__fish_complete_pip)" -c {prog} + """, + "powershell": """ + if ((Test-Path Function:\\TabExpansion) -and -not ` + (Test-Path Function:\\_pip_completeBackup)) {{ + Rename-Item Function:\\TabExpansion _pip_completeBackup + }} + function TabExpansion($line, $lastWord) {{ + $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart() + if ($lastBlock.StartsWith("{prog} ")) {{ + $Env:COMP_WORDS=$lastBlock + $Env:COMP_CWORD=$lastBlock.Split().Length - 1 + $Env:PIP_AUTO_COMPLETE=1 + (& {prog}).Split() + Remove-Item Env:COMP_WORDS + Remove-Item Env:COMP_CWORD + Remove-Item Env:PIP_AUTO_COMPLETE + }} + elseif (Test-Path Function:\\_pip_completeBackup) {{ + # Fall back on existing tab expansion + _pip_completeBackup $line $lastWord + }} + }} + """, +} + + +class CompletionCommand(Command): + """A helper command to be used for command completion.""" + + ignore_require_venv = True + + def add_options(self) -> None: + self.cmd_opts.add_option( + "--bash", + "-b", + action="store_const", + const="bash", + dest="shell", + help="Emit completion code for bash", + ) + self.cmd_opts.add_option( + "--zsh", + "-z", + action="store_const", + const="zsh", + dest="shell", + help="Emit completion code for zsh", + ) + self.cmd_opts.add_option( + "--fish", + "-f", + action="store_const", + const="fish", + dest="shell", + help="Emit completion code for fish", + ) + self.cmd_opts.add_option( + "--powershell", + "-p", + action="store_const", + const="powershell", + dest="shell", + help="Emit completion code for powershell", + ) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + """Prints the completion code of the given shell""" + shells = COMPLETION_SCRIPTS.keys() + shell_options = ["--" + shell for shell in sorted(shells)] + if options.shell in shells: + script = textwrap.dedent( + COMPLETION_SCRIPTS.get(options.shell, "").format(prog=get_prog()) + ) + print(BASE_COMPLETION.format(script=script, shell=options.shell)) + return SUCCESS + else: + sys.stderr.write( + "ERROR: You must pass {}\n".format(" or ".join(shell_options)) + ) + return SUCCESS diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/configuration.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..1a1dc6b6cd841dc2a9f5666fb34d8120e612346e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/configuration.py @@ -0,0 +1,280 @@ +import logging +import os +import subprocess +from optparse import Values +from typing import Any, List, Optional + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.configuration import ( + Configuration, + Kind, + get_configuration_files, + kinds, +) +from pip._internal.exceptions import PipError +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import get_prog, write_output + +logger = logging.getLogger(__name__) + + +class ConfigurationCommand(Command): + """ + Manage local and global configuration. + + Subcommands: + + - list: List the active configuration (or from the file specified) + - edit: Edit the configuration file in an editor + - get: Get the value associated with command.option + - set: Set the command.option=value + - unset: Unset the value associated with command.option + - debug: List the configuration files and values defined under them + + Configuration keys should be dot separated command and option name, + with the special prefix "global" affecting any command. For example, + "pip config set global.index-url https://example.org/" would configure + the index url for all commands, but "pip config set download.timeout 10" + would configure a 10 second timeout only for "pip download" commands. + + If none of --user, --global and --site are passed, a virtual + environment configuration file is used if one is active and the file + exists. Otherwise, all modifications happen to the user file by + default. + """ + + ignore_require_venv = True + usage = """ + %prog [] list + %prog [] [--editor ] edit + + %prog [] get command.option + %prog [] set command.option value + %prog [] unset command.option + %prog [] debug + """ + + def add_options(self) -> None: + self.cmd_opts.add_option( + "--editor", + dest="editor", + action="store", + default=None, + help=( + "Editor to use to edit the file. Uses VISUAL or EDITOR " + "environment variables if not provided." + ), + ) + + self.cmd_opts.add_option( + "--global", + dest="global_file", + action="store_true", + default=False, + help="Use the system-wide configuration file only", + ) + + self.cmd_opts.add_option( + "--user", + dest="user_file", + action="store_true", + default=False, + help="Use the user configuration file only", + ) + + self.cmd_opts.add_option( + "--site", + dest="site_file", + action="store_true", + default=False, + help="Use the current environment configuration file only", + ) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + handlers = { + "list": self.list_values, + "edit": self.open_in_editor, + "get": self.get_name, + "set": self.set_name_value, + "unset": self.unset_name, + "debug": self.list_config_values, + } + + # Determine action + if not args or args[0] not in handlers: + logger.error( + "Need an action (%s) to perform.", + ", ".join(sorted(handlers)), + ) + return ERROR + + action = args[0] + + # Determine which configuration files are to be loaded + # Depends on whether the command is modifying. + try: + load_only = self._determine_file( + options, need_value=(action in ["get", "set", "unset", "edit"]) + ) + except PipError as e: + logger.error(e.args[0]) + return ERROR + + # Load a new configuration + self.configuration = Configuration( + isolated=options.isolated_mode, load_only=load_only + ) + self.configuration.load() + + # Error handling happens here, not in the action-handlers. + try: + handlers[action](options, args[1:]) + except PipError as e: + logger.error(e.args[0]) + return ERROR + + return SUCCESS + + def _determine_file(self, options: Values, need_value: bool) -> Optional[Kind]: + file_options = [ + key + for key, value in ( + (kinds.USER, options.user_file), + (kinds.GLOBAL, options.global_file), + (kinds.SITE, options.site_file), + ) + if value + ] + + if not file_options: + if not need_value: + return None + # Default to user, unless there's a site file. + elif any( + os.path.exists(site_config_file) + for site_config_file in get_configuration_files()[kinds.SITE] + ): + return kinds.SITE + else: + return kinds.USER + elif len(file_options) == 1: + return file_options[0] + + raise PipError( + "Need exactly one file to operate upon " + "(--user, --site, --global) to perform." + ) + + def list_values(self, options: Values, args: List[str]) -> None: + self._get_n_args(args, "list", n=0) + + for key, value in sorted(self.configuration.items()): + write_output("%s=%r", key, value) + + def get_name(self, options: Values, args: List[str]) -> None: + key = self._get_n_args(args, "get [name]", n=1) + value = self.configuration.get_value(key) + + write_output("%s", value) + + def set_name_value(self, options: Values, args: List[str]) -> None: + key, value = self._get_n_args(args, "set [name] [value]", n=2) + self.configuration.set_value(key, value) + + self._save_configuration() + + def unset_name(self, options: Values, args: List[str]) -> None: + key = self._get_n_args(args, "unset [name]", n=1) + self.configuration.unset_value(key) + + self._save_configuration() + + def list_config_values(self, options: Values, args: List[str]) -> None: + """List config key-value pairs across different config files""" + self._get_n_args(args, "debug", n=0) + + self.print_env_var_values() + # Iterate over config files and print if they exist, and the + # key-value pairs present in them if they do + for variant, files in sorted(self.configuration.iter_config_files()): + write_output("%s:", variant) + for fname in files: + with indent_log(): + file_exists = os.path.exists(fname) + write_output("%s, exists: %r", fname, file_exists) + if file_exists: + self.print_config_file_values(variant) + + def print_config_file_values(self, variant: Kind) -> None: + """Get key-value pairs from the file of a variant""" + for name, value in self.configuration.get_values_in_config(variant).items(): + with indent_log(): + write_output("%s: %s", name, value) + + def print_env_var_values(self) -> None: + """Get key-values pairs present as environment variables""" + write_output("%s:", "env_var") + with indent_log(): + for key, value in sorted(self.configuration.get_environ_vars()): + env_var = f"PIP_{key.upper()}" + write_output("%s=%r", env_var, value) + + def open_in_editor(self, options: Values, args: List[str]) -> None: + editor = self._determine_editor(options) + + fname = self.configuration.get_file_to_edit() + if fname is None: + raise PipError("Could not determine appropriate file.") + elif '"' in fname: + # This shouldn't happen, unless we see a username like that. + # If that happens, we'd appreciate a pull request fixing this. + raise PipError( + f'Can not open an editor for a file name containing "\n{fname}' + ) + + try: + subprocess.check_call(f'{editor} "{fname}"', shell=True) + except FileNotFoundError as e: + if not e.filename: + e.filename = editor + raise + except subprocess.CalledProcessError as e: + raise PipError(f"Editor Subprocess exited with exit code {e.returncode}") + + def _get_n_args(self, args: List[str], example: str, n: int) -> Any: + """Helper to make sure the command got the right number of arguments""" + if len(args) != n: + msg = ( + f"Got unexpected number of arguments, expected {n}. " + f'(example: "{get_prog()} config {example}")' + ) + raise PipError(msg) + + if n == 1: + return args[0] + else: + return args + + def _save_configuration(self) -> None: + # We successfully ran a modifying command. Need to save the + # configuration. + try: + self.configuration.save() + except Exception: + logger.exception( + "Unable to save configuration. Please report this as a bug." + ) + raise PipError("Internal Error.") + + def _determine_editor(self, options: Values) -> str: + if options.editor is not None: + return options.editor + elif "VISUAL" in os.environ: + return os.environ["VISUAL"] + elif "EDITOR" in os.environ: + return os.environ["EDITOR"] + else: + raise PipError("Could not determine editor to use.") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/debug.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..567ca967e5b64478d17455288b79dd80301b4888 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/debug.py @@ -0,0 +1,201 @@ +import locale +import logging +import os +import sys +from optparse import Values +from types import ModuleType +from typing import Any, Dict, List, Optional + +import pip._vendor +from pip._vendor.certifi import where +from pip._vendor.packaging.version import parse as parse_version + +from pip._internal.cli import cmdoptions +from pip._internal.cli.base_command import Command +from pip._internal.cli.cmdoptions import make_target_python +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.configuration import Configuration +from pip._internal.metadata import get_environment +from pip._internal.utils.compat import open_text_resource +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import get_pip_version + +logger = logging.getLogger(__name__) + + +def show_value(name: str, value: Any) -> None: + logger.info("%s: %s", name, value) + + +def show_sys_implementation() -> None: + logger.info("sys.implementation:") + implementation_name = sys.implementation.name + with indent_log(): + show_value("name", implementation_name) + + +def create_vendor_txt_map() -> Dict[str, str]: + with open_text_resource("pip._vendor", "vendor.txt") as f: + # Purge non version specifying lines. + # Also, remove any space prefix or suffixes (including comments). + lines = [ + line.strip().split(" ", 1)[0] for line in f.readlines() if "==" in line + ] + + # Transform into "module" -> version dict. + return dict(line.split("==", 1) for line in lines) + + +def get_module_from_module_name(module_name: str) -> Optional[ModuleType]: + # Module name can be uppercase in vendor.txt for some reason... + module_name = module_name.lower().replace("-", "_") + # PATCH: setuptools is actually only pkg_resources. + if module_name == "setuptools": + module_name = "pkg_resources" + + try: + __import__(f"pip._vendor.{module_name}", globals(), locals(), level=0) + return getattr(pip._vendor, module_name) + except ImportError: + # We allow 'truststore' to fail to import due + # to being unavailable on Python 3.9 and earlier. + if module_name == "truststore" and sys.version_info < (3, 10): + return None + raise + + +def get_vendor_version_from_module(module_name: str) -> Optional[str]: + module = get_module_from_module_name(module_name) + version = getattr(module, "__version__", None) + + if module and not version: + # Try to find version in debundled module info. + assert module.__file__ is not None + env = get_environment([os.path.dirname(module.__file__)]) + dist = env.get_distribution(module_name) + if dist: + version = str(dist.version) + + return version + + +def show_actual_vendor_versions(vendor_txt_versions: Dict[str, str]) -> None: + """Log the actual version and print extra info if there is + a conflict or if the actual version could not be imported. + """ + for module_name, expected_version in vendor_txt_versions.items(): + extra_message = "" + actual_version = get_vendor_version_from_module(module_name) + if not actual_version: + extra_message = ( + " (Unable to locate actual module version, using" + " vendor.txt specified version)" + ) + actual_version = expected_version + elif parse_version(actual_version) != parse_version(expected_version): + extra_message = ( + " (CONFLICT: vendor.txt suggests version should" + f" be {expected_version})" + ) + logger.info("%s==%s%s", module_name, actual_version, extra_message) + + +def show_vendor_versions() -> None: + logger.info("vendored library versions:") + + vendor_txt_versions = create_vendor_txt_map() + with indent_log(): + show_actual_vendor_versions(vendor_txt_versions) + + +def show_tags(options: Values) -> None: + tag_limit = 10 + + target_python = make_target_python(options) + tags = target_python.get_sorted_tags() + + # Display the target options that were explicitly provided. + formatted_target = target_python.format_given() + suffix = "" + if formatted_target: + suffix = f" (target: {formatted_target})" + + msg = f"Compatible tags: {len(tags)}{suffix}" + logger.info(msg) + + if options.verbose < 1 and len(tags) > tag_limit: + tags_limited = True + tags = tags[:tag_limit] + else: + tags_limited = False + + with indent_log(): + for tag in tags: + logger.info(str(tag)) + + if tags_limited: + msg = f"...\n[First {tag_limit} tags shown. Pass --verbose to show all.]" + logger.info(msg) + + +def ca_bundle_info(config: Configuration) -> str: + levels = {key.split(".", 1)[0] for key, _ in config.items()} + if not levels: + return "Not specified" + + levels_that_override_global = ["install", "wheel", "download"] + global_overriding_level = [ + level for level in levels if level in levels_that_override_global + ] + if not global_overriding_level: + return "global" + + if "global" in levels: + levels.remove("global") + return ", ".join(levels) + + +class DebugCommand(Command): + """ + Display debug information. + """ + + usage = """ + %prog """ + ignore_require_venv = True + + def add_options(self) -> None: + cmdoptions.add_target_python_options(self.cmd_opts) + self.parser.insert_option_group(0, self.cmd_opts) + self.parser.config.load() + + def run(self, options: Values, args: List[str]) -> int: + logger.warning( + "This command is only meant for debugging. " + "Do not use this with automation for parsing and getting these " + "details, since the output and options of this command may " + "change without notice." + ) + show_value("pip version", get_pip_version()) + show_value("sys.version", sys.version) + show_value("sys.executable", sys.executable) + show_value("sys.getdefaultencoding", sys.getdefaultencoding()) + show_value("sys.getfilesystemencoding", sys.getfilesystemencoding()) + show_value( + "locale.getpreferredencoding", + locale.getpreferredencoding(), + ) + show_value("sys.platform", sys.platform) + show_sys_implementation() + + show_value("'cert' config value", ca_bundle_info(self.parser.config)) + show_value("REQUESTS_CA_BUNDLE", os.environ.get("REQUESTS_CA_BUNDLE")) + show_value("CURL_CA_BUNDLE", os.environ.get("CURL_CA_BUNDLE")) + show_value("pip._vendor.certifi.where()", where()) + show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED) + + show_vendor_versions() + + show_tags(options) + + return SUCCESS diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/download.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/download.py new file mode 100644 index 0000000000000000000000000000000000000000..917bbb91d83cbb81a5814d510b5dd3bdd6c0f510 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/download.py @@ -0,0 +1,146 @@ +import logging +import os +from optparse import Values +from typing import List + +from pip._internal.cli import cmdoptions +from pip._internal.cli.cmdoptions import make_target_python +from pip._internal.cli.req_command import RequirementCommand, with_cleanup +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.operations.build.build_tracker import get_build_tracker +from pip._internal.req.req_install import check_legacy_setup_py_options +from pip._internal.utils.misc import ensure_dir, normalize_path, write_output +from pip._internal.utils.temp_dir import TempDirectory + +logger = logging.getLogger(__name__) + + +class DownloadCommand(RequirementCommand): + """ + Download packages from: + + - PyPI (and other indexes) using requirement specifiers. + - VCS project urls. + - Local project directories. + - Local or remote source archives. + + pip also supports downloading from "requirements files", which provide + an easy way to specify a whole environment to be downloaded. + """ + + usage = """ + %prog [options] [package-index-options] ... + %prog [options] -r [package-index-options] ... + %prog [options] ... + %prog [options] ... + %prog [options] ...""" + + def add_options(self) -> None: + self.cmd_opts.add_option(cmdoptions.constraints()) + self.cmd_opts.add_option(cmdoptions.requirements()) + self.cmd_opts.add_option(cmdoptions.no_deps()) + self.cmd_opts.add_option(cmdoptions.global_options()) + self.cmd_opts.add_option(cmdoptions.no_binary()) + self.cmd_opts.add_option(cmdoptions.only_binary()) + self.cmd_opts.add_option(cmdoptions.prefer_binary()) + self.cmd_opts.add_option(cmdoptions.src()) + self.cmd_opts.add_option(cmdoptions.pre()) + self.cmd_opts.add_option(cmdoptions.require_hashes()) + self.cmd_opts.add_option(cmdoptions.progress_bar()) + self.cmd_opts.add_option(cmdoptions.no_build_isolation()) + self.cmd_opts.add_option(cmdoptions.use_pep517()) + self.cmd_opts.add_option(cmdoptions.no_use_pep517()) + self.cmd_opts.add_option(cmdoptions.check_build_deps()) + self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) + + self.cmd_opts.add_option( + "-d", + "--dest", + "--destination-dir", + "--destination-directory", + dest="download_dir", + metavar="dir", + default=os.curdir, + help="Download packages into .", + ) + + cmdoptions.add_target_python_options(self.cmd_opts) + + index_opts = cmdoptions.make_option_group( + cmdoptions.index_group, + self.parser, + ) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + @with_cleanup + def run(self, options: Values, args: List[str]) -> int: + options.ignore_installed = True + # editable doesn't really make sense for `pip download`, but the bowels + # of the RequirementSet code require that property. + options.editables = [] + + cmdoptions.check_dist_restriction(options) + + options.download_dir = normalize_path(options.download_dir) + ensure_dir(options.download_dir) + + session = self.get_default_session(options) + + target_python = make_target_python(options) + finder = self._build_package_finder( + options=options, + session=session, + target_python=target_python, + ignore_requires_python=options.ignore_requires_python, + ) + + build_tracker = self.enter_context(get_build_tracker()) + + directory = TempDirectory( + delete=not options.no_clean, + kind="download", + globally_managed=True, + ) + + reqs = self.get_requirements(args, options, finder, session) + check_legacy_setup_py_options(options, reqs) + + preparer = self.make_requirement_preparer( + temp_build_dir=directory, + options=options, + build_tracker=build_tracker, + session=session, + finder=finder, + download_dir=options.download_dir, + use_user_site=False, + verbosity=self.verbosity, + ) + + resolver = self.make_resolver( + preparer=preparer, + finder=finder, + options=options, + ignore_requires_python=options.ignore_requires_python, + use_pep517=options.use_pep517, + py_version_info=options.python_version, + ) + + self.trace_basic_info(finder) + + requirement_set = resolver.resolve(reqs, check_supported_wheels=True) + + downloaded: List[str] = [] + for req in requirement_set.requirements.values(): + if req.satisfied_by is None: + assert req.name is not None + preparer.save_linked_requirement(req) + downloaded.append(req.name) + + preparer.prepare_linked_requirements_more(requirement_set.requirements.values()) + + if downloaded: + write_output("Successfully downloaded %s", " ".join(downloaded)) + + return SUCCESS diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/freeze.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/freeze.py new file mode 100644 index 0000000000000000000000000000000000000000..885fdfeb83b837b27db08e4abc3df2e7b580dc2b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/freeze.py @@ -0,0 +1,109 @@ +import sys +from optparse import Values +from typing import AbstractSet, List + +from pip._internal.cli import cmdoptions +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.operations.freeze import freeze +from pip._internal.utils.compat import stdlib_pkgs + + +def _should_suppress_build_backends() -> bool: + return sys.version_info < (3, 12) + + +def _dev_pkgs() -> AbstractSet[str]: + pkgs = {"pip"} + + if _should_suppress_build_backends(): + pkgs |= {"setuptools", "distribute", "wheel"} + + return pkgs + + +class FreezeCommand(Command): + """ + Output installed packages in requirements format. + + packages are listed in a case-insensitive sorted order. + """ + + ignore_require_venv = True + usage = """ + %prog [options]""" + log_streams = ("ext://sys.stderr", "ext://sys.stderr") + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-r", + "--requirement", + dest="requirements", + action="append", + default=[], + metavar="file", + help=( + "Use the order in the given requirements file and its " + "comments when generating output. This option can be " + "used multiple times." + ), + ) + self.cmd_opts.add_option( + "-l", + "--local", + dest="local", + action="store_true", + default=False, + help=( + "If in a virtualenv that has global access, do not output " + "globally-installed packages." + ), + ) + self.cmd_opts.add_option( + "--user", + dest="user", + action="store_true", + default=False, + help="Only output packages installed in user-site.", + ) + self.cmd_opts.add_option(cmdoptions.list_path()) + self.cmd_opts.add_option( + "--all", + dest="freeze_all", + action="store_true", + help=( + "Do not skip these packages in the output:" + " {}".format(", ".join(_dev_pkgs())) + ), + ) + self.cmd_opts.add_option( + "--exclude-editable", + dest="exclude_editable", + action="store_true", + help="Exclude editable package from output.", + ) + self.cmd_opts.add_option(cmdoptions.list_exclude()) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + skip = set(stdlib_pkgs) + if not options.freeze_all: + skip.update(_dev_pkgs()) + + if options.excludes: + skip.update(options.excludes) + + cmdoptions.check_list_path_option(options) + + for line in freeze( + requirement=options.requirements, + local_only=options.local, + user_only=options.user, + paths=options.path, + isolated=options.isolated_mode, + skip=skip, + exclude_editable=options.exclude_editable, + ): + sys.stdout.write(line + "\n") + return SUCCESS diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/hash.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/hash.py new file mode 100644 index 0000000000000000000000000000000000000000..042dac813e74b8187c3754cb9a937c7f7183e331 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/hash.py @@ -0,0 +1,59 @@ +import hashlib +import logging +import sys +from optparse import Values +from typing import List + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES +from pip._internal.utils.misc import read_chunks, write_output + +logger = logging.getLogger(__name__) + + +class HashCommand(Command): + """ + Compute a hash of a local package archive. + + These can be used with --hash in a requirements file to do repeatable + installs. + """ + + usage = "%prog [options] ..." + ignore_require_venv = True + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-a", + "--algorithm", + dest="algorithm", + choices=STRONG_HASHES, + action="store", + default=FAVORITE_HASH, + help="The hash algorithm to use: one of {}".format( + ", ".join(STRONG_HASHES) + ), + ) + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + if not args: + self.parser.print_usage(sys.stderr) + return ERROR + + algorithm = options.algorithm + for path in args: + write_output( + "%s:\n--hash=%s:%s", path, algorithm, _hash_of_file(path, algorithm) + ) + return SUCCESS + + +def _hash_of_file(path: str, algorithm: str) -> str: + """Return the hash digest of a file.""" + with open(path, "rb") as archive: + hash = hashlib.new(algorithm) + for chunk in read_chunks(archive): + hash.update(chunk) + return hash.hexdigest() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/help.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/help.py new file mode 100644 index 0000000000000000000000000000000000000000..62066318b74dcc5c32bcd24b9493fb34d1ce52d7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/help.py @@ -0,0 +1,41 @@ +from optparse import Values +from typing import List + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.exceptions import CommandError + + +class HelpCommand(Command): + """Show help for commands""" + + usage = """ + %prog """ + ignore_require_venv = True + + def run(self, options: Values, args: List[str]) -> int: + from pip._internal.commands import ( + commands_dict, + create_command, + get_similar_commands, + ) + + try: + # 'pip help' with no args is handled by pip.__init__.parseopt() + cmd_name = args[0] # the command we need help for + except IndexError: + return SUCCESS + + if cmd_name not in commands_dict: + guess = get_similar_commands(cmd_name) + + msg = [f'unknown command "{cmd_name}"'] + if guess: + msg.append(f'maybe you meant "{guess}"') + + raise CommandError(" - ".join(msg)) + + command = create_command(cmd_name) + command.parser.print_help() + + return SUCCESS diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/index.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/index.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2661bba710fb2cc255ba6ee01ea743fdbf540e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/index.py @@ -0,0 +1,139 @@ +import logging +from optparse import Values +from typing import Any, Iterable, List, Optional + +from pip._vendor.packaging.version import Version + +from pip._internal.cli import cmdoptions +from pip._internal.cli.req_command import IndexGroupCommand +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.commands.search import print_dist_installation_info +from pip._internal.exceptions import CommandError, DistributionNotFound, PipError +from pip._internal.index.collector import LinkCollector +from pip._internal.index.package_finder import PackageFinder +from pip._internal.models.selection_prefs import SelectionPreferences +from pip._internal.models.target_python import TargetPython +from pip._internal.network.session import PipSession +from pip._internal.utils.misc import write_output + +logger = logging.getLogger(__name__) + + +class IndexCommand(IndexGroupCommand): + """ + Inspect information available from package indexes. + """ + + ignore_require_venv = True + usage = """ + %prog versions + """ + + def add_options(self) -> None: + cmdoptions.add_target_python_options(self.cmd_opts) + + self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) + self.cmd_opts.add_option(cmdoptions.pre()) + self.cmd_opts.add_option(cmdoptions.no_binary()) + self.cmd_opts.add_option(cmdoptions.only_binary()) + + index_opts = cmdoptions.make_option_group( + cmdoptions.index_group, + self.parser, + ) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + handlers = { + "versions": self.get_available_package_versions, + } + + logger.warning( + "pip index is currently an experimental command. " + "It may be removed/changed in a future release " + "without prior warning." + ) + + # Determine action + if not args or args[0] not in handlers: + logger.error( + "Need an action (%s) to perform.", + ", ".join(sorted(handlers)), + ) + return ERROR + + action = args[0] + + # Error handling happens here, not in the action-handlers. + try: + handlers[action](options, args[1:]) + except PipError as e: + logger.error(e.args[0]) + return ERROR + + return SUCCESS + + def _build_package_finder( + self, + options: Values, + session: PipSession, + target_python: Optional[TargetPython] = None, + ignore_requires_python: Optional[bool] = None, + ) -> PackageFinder: + """ + Create a package finder appropriate to the index command. + """ + link_collector = LinkCollector.create(session, options=options) + + # Pass allow_yanked=False to ignore yanked versions. + selection_prefs = SelectionPreferences( + allow_yanked=False, + allow_all_prereleases=options.pre, + ignore_requires_python=ignore_requires_python, + ) + + return PackageFinder.create( + link_collector=link_collector, + selection_prefs=selection_prefs, + target_python=target_python, + ) + + def get_available_package_versions(self, options: Values, args: List[Any]) -> None: + if len(args) != 1: + raise CommandError("You need to specify exactly one argument") + + target_python = cmdoptions.make_target_python(options) + query = args[0] + + with self._build_session(options) as session: + finder = self._build_package_finder( + options=options, + session=session, + target_python=target_python, + ignore_requires_python=options.ignore_requires_python, + ) + + versions: Iterable[Version] = ( + candidate.version for candidate in finder.find_all_candidates(query) + ) + + if not options.pre: + # Remove prereleases + versions = ( + version for version in versions if not version.is_prerelease + ) + versions = set(versions) + + if not versions: + raise DistributionNotFound( + f"No matching distribution found for {query}" + ) + + formatted_versions = [str(ver) for ver in sorted(versions, reverse=True)] + latest = formatted_versions[0] + + write_output(f"{query} ({latest})") + write_output("Available versions: {}".format(", ".join(formatted_versions))) + print_dist_installation_info(query, latest) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/inspect.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/inspect.py new file mode 100644 index 0000000000000000000000000000000000000000..e810c13166bbdf0e38c94bc3ef66af7aeda2bba7 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/inspect.py @@ -0,0 +1,92 @@ +import logging +from optparse import Values +from typing import Any, Dict, List + +from pip._vendor.packaging.markers import default_environment +from pip._vendor.rich import print_json + +from pip import __version__ +from pip._internal.cli import cmdoptions +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.metadata import BaseDistribution, get_environment +from pip._internal.utils.compat import stdlib_pkgs +from pip._internal.utils.urls import path_to_url + +logger = logging.getLogger(__name__) + + +class InspectCommand(Command): + """ + Inspect the content of a Python environment and produce a report in JSON format. + """ + + ignore_require_venv = True + usage = """ + %prog [options]""" + + def add_options(self) -> None: + self.cmd_opts.add_option( + "--local", + action="store_true", + default=False, + help=( + "If in a virtualenv that has global access, do not list " + "globally-installed packages." + ), + ) + self.cmd_opts.add_option( + "--user", + dest="user", + action="store_true", + default=False, + help="Only output packages installed in user-site.", + ) + self.cmd_opts.add_option(cmdoptions.list_path()) + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + cmdoptions.check_list_path_option(options) + dists = get_environment(options.path).iter_installed_distributions( + local_only=options.local, + user_only=options.user, + skip=set(stdlib_pkgs), + ) + output = { + "version": "1", + "pip_version": __version__, + "installed": [self._dist_to_dict(dist) for dist in dists], + "environment": default_environment(), + # TODO tags? scheme? + } + print_json(data=output) + return SUCCESS + + def _dist_to_dict(self, dist: BaseDistribution) -> Dict[str, Any]: + res: Dict[str, Any] = { + "metadata": dist.metadata_dict, + "metadata_location": dist.info_location, + } + # direct_url. Note that we don't have download_info (as in the installation + # report) since it is not recorded in installed metadata. + direct_url = dist.direct_url + if direct_url is not None: + res["direct_url"] = direct_url.to_dict() + else: + # Emulate direct_url for legacy editable installs. + editable_project_location = dist.editable_project_location + if editable_project_location is not None: + res["direct_url"] = { + "url": path_to_url(editable_project_location), + "dir_info": { + "editable": True, + }, + } + # installer + installer = dist.installer + if dist.installer: + res["installer"] = installer + # requested + if dist.installed_with_dist_info: + res["requested"] = dist.requested + return res diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/install.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/install.py new file mode 100644 index 0000000000000000000000000000000000000000..232a34a6d3e5eac0ee8e80ff1b7477b987b425f8 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/install.py @@ -0,0 +1,784 @@ +import errno +import json +import operator +import os +import shutil +import site +from optparse import SUPPRESS_HELP, Values +from typing import List, Optional + +from pip._vendor.packaging.utils import canonicalize_name +from pip._vendor.rich import print_json + +# Eagerly import self_outdated_check to avoid crashes. Otherwise, +# this module would be imported *after* pip was replaced, resulting +# in crashes if the new self_outdated_check module was incompatible +# with the rest of pip that's already imported, or allowing a +# wheel to execute arbitrary code on install by replacing +# self_outdated_check. +import pip._internal.self_outdated_check # noqa: F401 +from pip._internal.cache import WheelCache +from pip._internal.cli import cmdoptions +from pip._internal.cli.cmdoptions import make_target_python +from pip._internal.cli.req_command import ( + RequirementCommand, + with_cleanup, +) +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.exceptions import CommandError, InstallationError +from pip._internal.locations import get_scheme +from pip._internal.metadata import get_environment +from pip._internal.models.installation_report import InstallationReport +from pip._internal.operations.build.build_tracker import get_build_tracker +from pip._internal.operations.check import ConflictDetails, check_install_conflicts +from pip._internal.req import install_given_reqs +from pip._internal.req.req_install import ( + InstallRequirement, + check_legacy_setup_py_options, +) +from pip._internal.utils.compat import WINDOWS +from pip._internal.utils.filesystem import test_writable_dir +from pip._internal.utils.logging import getLogger +from pip._internal.utils.misc import ( + check_externally_managed, + ensure_dir, + get_pip_version, + protect_pip_from_modification_on_windows, + warn_if_run_as_root, + write_output, +) +from pip._internal.utils.temp_dir import TempDirectory +from pip._internal.utils.virtualenv import ( + running_under_virtualenv, + virtualenv_no_global, +) +from pip._internal.wheel_builder import build, should_build_for_install_command + +logger = getLogger(__name__) + + +class InstallCommand(RequirementCommand): + """ + Install packages from: + + - PyPI (and other indexes) using requirement specifiers. + - VCS project urls. + - Local project directories. + - Local or remote source archives. + + pip also supports installing from "requirements files", which provide + an easy way to specify a whole environment to be installed. + """ + + usage = """ + %prog [options] [package-index-options] ... + %prog [options] -r [package-index-options] ... + %prog [options] [-e] ... + %prog [options] [-e] ... + %prog [options] ...""" + + def add_options(self) -> None: + self.cmd_opts.add_option(cmdoptions.requirements()) + self.cmd_opts.add_option(cmdoptions.constraints()) + self.cmd_opts.add_option(cmdoptions.no_deps()) + self.cmd_opts.add_option(cmdoptions.pre()) + + self.cmd_opts.add_option(cmdoptions.editable()) + self.cmd_opts.add_option( + "--dry-run", + action="store_true", + dest="dry_run", + default=False, + help=( + "Don't actually install anything, just print what would be. " + "Can be used in combination with --ignore-installed " + "to 'resolve' the requirements." + ), + ) + self.cmd_opts.add_option( + "-t", + "--target", + dest="target_dir", + metavar="dir", + default=None, + help=( + "Install packages into . " + "By default this will not replace existing files/folders in " + ". Use --upgrade to replace existing packages in " + "with new versions." + ), + ) + cmdoptions.add_target_python_options(self.cmd_opts) + + self.cmd_opts.add_option( + "--user", + dest="use_user_site", + action="store_true", + help=( + "Install to the Python user install directory for your " + "platform. Typically ~/.local/, or %APPDATA%\\Python on " + "Windows. (See the Python documentation for site.USER_BASE " + "for full details.)" + ), + ) + self.cmd_opts.add_option( + "--no-user", + dest="use_user_site", + action="store_false", + help=SUPPRESS_HELP, + ) + self.cmd_opts.add_option( + "--root", + dest="root_path", + metavar="dir", + default=None, + help="Install everything relative to this alternate root directory.", + ) + self.cmd_opts.add_option( + "--prefix", + dest="prefix_path", + metavar="dir", + default=None, + help=( + "Installation prefix where lib, bin and other top-level " + "folders are placed. Note that the resulting installation may " + "contain scripts and other resources which reference the " + "Python interpreter of pip, and not that of ``--prefix``. " + "See also the ``--python`` option if the intention is to " + "install packages into another (possibly pip-free) " + "environment." + ), + ) + + self.cmd_opts.add_option(cmdoptions.src()) + + self.cmd_opts.add_option( + "-U", + "--upgrade", + dest="upgrade", + action="store_true", + help=( + "Upgrade all specified packages to the newest available " + "version. The handling of dependencies depends on the " + "upgrade-strategy used." + ), + ) + + self.cmd_opts.add_option( + "--upgrade-strategy", + dest="upgrade_strategy", + default="only-if-needed", + choices=["only-if-needed", "eager"], + help=( + "Determines how dependency upgrading should be handled " + "[default: %default]. " + '"eager" - dependencies are upgraded regardless of ' + "whether the currently installed version satisfies the " + "requirements of the upgraded package(s). " + '"only-if-needed" - are upgraded only when they do not ' + "satisfy the requirements of the upgraded package(s)." + ), + ) + + self.cmd_opts.add_option( + "--force-reinstall", + dest="force_reinstall", + action="store_true", + help="Reinstall all packages even if they are already up-to-date.", + ) + + self.cmd_opts.add_option( + "-I", + "--ignore-installed", + dest="ignore_installed", + action="store_true", + help=( + "Ignore the installed packages, overwriting them. " + "This can break your system if the existing package " + "is of a different version or was installed " + "with a different package manager!" + ), + ) + + self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) + self.cmd_opts.add_option(cmdoptions.no_build_isolation()) + self.cmd_opts.add_option(cmdoptions.use_pep517()) + self.cmd_opts.add_option(cmdoptions.no_use_pep517()) + self.cmd_opts.add_option(cmdoptions.check_build_deps()) + self.cmd_opts.add_option(cmdoptions.override_externally_managed()) + + self.cmd_opts.add_option(cmdoptions.config_settings()) + self.cmd_opts.add_option(cmdoptions.global_options()) + + self.cmd_opts.add_option( + "--compile", + action="store_true", + dest="compile", + default=True, + help="Compile Python source files to bytecode", + ) + + self.cmd_opts.add_option( + "--no-compile", + action="store_false", + dest="compile", + help="Do not compile Python source files to bytecode", + ) + + self.cmd_opts.add_option( + "--no-warn-script-location", + action="store_false", + dest="warn_script_location", + default=True, + help="Do not warn when installing scripts outside PATH", + ) + self.cmd_opts.add_option( + "--no-warn-conflicts", + action="store_false", + dest="warn_about_conflicts", + default=True, + help="Do not warn about broken dependencies", + ) + self.cmd_opts.add_option(cmdoptions.no_binary()) + self.cmd_opts.add_option(cmdoptions.only_binary()) + self.cmd_opts.add_option(cmdoptions.prefer_binary()) + self.cmd_opts.add_option(cmdoptions.require_hashes()) + self.cmd_opts.add_option(cmdoptions.progress_bar()) + self.cmd_opts.add_option(cmdoptions.root_user_action()) + + index_opts = cmdoptions.make_option_group( + cmdoptions.index_group, + self.parser, + ) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + self.cmd_opts.add_option( + "--report", + dest="json_report_file", + metavar="file", + default=None, + help=( + "Generate a JSON file describing what pip did to install " + "the provided requirements. " + "Can be used in combination with --dry-run and --ignore-installed " + "to 'resolve' the requirements. " + "When - is used as file name it writes to stdout. " + "When writing to stdout, please combine with the --quiet option " + "to avoid mixing pip logging output with JSON output." + ), + ) + + @with_cleanup + def run(self, options: Values, args: List[str]) -> int: + if options.use_user_site and options.target_dir is not None: + raise CommandError("Can not combine '--user' and '--target'") + + # Check whether the environment we're installing into is externally + # managed, as specified in PEP 668. Specifying --root, --target, or + # --prefix disables the check, since there's no reliable way to locate + # the EXTERNALLY-MANAGED file for those cases. An exception is also + # made specifically for "--dry-run --report" for convenience. + installing_into_current_environment = ( + not (options.dry_run and options.json_report_file) + and options.root_path is None + and options.target_dir is None + and options.prefix_path is None + ) + if ( + installing_into_current_environment + and not options.override_externally_managed + ): + check_externally_managed() + + upgrade_strategy = "to-satisfy-only" + if options.upgrade: + upgrade_strategy = options.upgrade_strategy + + cmdoptions.check_dist_restriction(options, check_target=True) + + logger.verbose("Using %s", get_pip_version()) + options.use_user_site = decide_user_install( + options.use_user_site, + prefix_path=options.prefix_path, + target_dir=options.target_dir, + root_path=options.root_path, + isolated_mode=options.isolated_mode, + ) + + target_temp_dir: Optional[TempDirectory] = None + target_temp_dir_path: Optional[str] = None + if options.target_dir: + options.ignore_installed = True + options.target_dir = os.path.abspath(options.target_dir) + if ( + # fmt: off + os.path.exists(options.target_dir) and + not os.path.isdir(options.target_dir) + # fmt: on + ): + raise CommandError( + "Target path exists but is not a directory, will not continue." + ) + + # Create a target directory for using with the target option + target_temp_dir = TempDirectory(kind="target") + target_temp_dir_path = target_temp_dir.path + self.enter_context(target_temp_dir) + + global_options = options.global_options or [] + + session = self.get_default_session(options) + + target_python = make_target_python(options) + finder = self._build_package_finder( + options=options, + session=session, + target_python=target_python, + ignore_requires_python=options.ignore_requires_python, + ) + build_tracker = self.enter_context(get_build_tracker()) + + directory = TempDirectory( + delete=not options.no_clean, + kind="install", + globally_managed=True, + ) + + try: + reqs = self.get_requirements(args, options, finder, session) + check_legacy_setup_py_options(options, reqs) + + wheel_cache = WheelCache(options.cache_dir) + + # Only when installing is it permitted to use PEP 660. + # In other circumstances (pip wheel, pip download) we generate + # regular (i.e. non editable) metadata and wheels. + for req in reqs: + req.permit_editable_wheels = True + + preparer = self.make_requirement_preparer( + temp_build_dir=directory, + options=options, + build_tracker=build_tracker, + session=session, + finder=finder, + use_user_site=options.use_user_site, + verbosity=self.verbosity, + ) + resolver = self.make_resolver( + preparer=preparer, + finder=finder, + options=options, + wheel_cache=wheel_cache, + use_user_site=options.use_user_site, + ignore_installed=options.ignore_installed, + ignore_requires_python=options.ignore_requires_python, + force_reinstall=options.force_reinstall, + upgrade_strategy=upgrade_strategy, + use_pep517=options.use_pep517, + py_version_info=options.python_version, + ) + + self.trace_basic_info(finder) + + requirement_set = resolver.resolve( + reqs, check_supported_wheels=not options.target_dir + ) + + if options.json_report_file: + report = InstallationReport(requirement_set.requirements_to_install) + if options.json_report_file == "-": + print_json(data=report.to_dict()) + else: + with open(options.json_report_file, "w", encoding="utf-8") as f: + json.dump(report.to_dict(), f, indent=2, ensure_ascii=False) + + if options.dry_run: + would_install_items = sorted( + (r.metadata["name"], r.metadata["version"]) + for r in requirement_set.requirements_to_install + ) + if would_install_items: + write_output( + "Would install %s", + " ".join("-".join(item) for item in would_install_items), + ) + return SUCCESS + + try: + pip_req = requirement_set.get_requirement("pip") + except KeyError: + modifying_pip = False + else: + # If we're not replacing an already installed pip, + # we're not modifying it. + modifying_pip = pip_req.satisfied_by is None + protect_pip_from_modification_on_windows(modifying_pip=modifying_pip) + + reqs_to_build = [ + r + for r in requirement_set.requirements.values() + if should_build_for_install_command(r) + ] + + _, build_failures = build( + reqs_to_build, + wheel_cache=wheel_cache, + verify=True, + build_options=[], + global_options=global_options, + ) + + if build_failures: + raise InstallationError( + "Failed to build installable wheels for some " + "pyproject.toml based projects ({})".format( + ", ".join(r.name for r in build_failures) # type: ignore + ) + ) + + to_install = resolver.get_installation_order(requirement_set) + + # Check for conflicts in the package set we're installing. + conflicts: Optional[ConflictDetails] = None + should_warn_about_conflicts = ( + not options.ignore_dependencies and options.warn_about_conflicts + ) + if should_warn_about_conflicts: + conflicts = self._determine_conflicts(to_install) + + # Don't warn about script install locations if + # --target or --prefix has been specified + warn_script_location = options.warn_script_location + if options.target_dir or options.prefix_path: + warn_script_location = False + + installed = install_given_reqs( + to_install, + global_options, + root=options.root_path, + home=target_temp_dir_path, + prefix=options.prefix_path, + warn_script_location=warn_script_location, + use_user_site=options.use_user_site, + pycompile=options.compile, + ) + + lib_locations = get_lib_location_guesses( + user=options.use_user_site, + home=target_temp_dir_path, + root=options.root_path, + prefix=options.prefix_path, + isolated=options.isolated_mode, + ) + env = get_environment(lib_locations) + + # Display a summary of installed packages, with extra care to + # display a package name as it was requested by the user. + installed.sort(key=operator.attrgetter("name")) + summary = [] + installed_versions = {} + for distribution in env.iter_all_distributions(): + installed_versions[distribution.canonical_name] = distribution.version + for package in installed: + display_name = package.name + version = installed_versions.get(canonicalize_name(display_name), None) + if version: + text = f"{display_name}-{version}" + else: + text = display_name + summary.append(text) + + if conflicts is not None: + self._warn_about_conflicts( + conflicts, + resolver_variant=self.determine_resolver_variant(options), + ) + + installed_desc = " ".join(summary) + if installed_desc: + write_output( + "Successfully installed %s", + installed_desc, + ) + except OSError as error: + show_traceback = self.verbosity >= 1 + + message = create_os_error_message( + error, + show_traceback, + options.use_user_site, + ) + logger.error(message, exc_info=show_traceback) + + return ERROR + + if options.target_dir: + assert target_temp_dir + self._handle_target_dir( + options.target_dir, target_temp_dir, options.upgrade + ) + if options.root_user_action == "warn": + warn_if_run_as_root() + return SUCCESS + + def _handle_target_dir( + self, target_dir: str, target_temp_dir: TempDirectory, upgrade: bool + ) -> None: + ensure_dir(target_dir) + + # Checking both purelib and platlib directories for installed + # packages to be moved to target directory + lib_dir_list = [] + + # Checking both purelib and platlib directories for installed + # packages to be moved to target directory + scheme = get_scheme("", home=target_temp_dir.path) + purelib_dir = scheme.purelib + platlib_dir = scheme.platlib + data_dir = scheme.data + + if os.path.exists(purelib_dir): + lib_dir_list.append(purelib_dir) + if os.path.exists(platlib_dir) and platlib_dir != purelib_dir: + lib_dir_list.append(platlib_dir) + if os.path.exists(data_dir): + lib_dir_list.append(data_dir) + + for lib_dir in lib_dir_list: + for item in os.listdir(lib_dir): + if lib_dir == data_dir: + ddir = os.path.join(data_dir, item) + if any(s.startswith(ddir) for s in lib_dir_list[:-1]): + continue + target_item_dir = os.path.join(target_dir, item) + if os.path.exists(target_item_dir): + if not upgrade: + logger.warning( + "Target directory %s already exists. Specify " + "--upgrade to force replacement.", + target_item_dir, + ) + continue + if os.path.islink(target_item_dir): + logger.warning( + "Target directory %s already exists and is " + "a link. pip will not automatically replace " + "links, please remove if replacement is " + "desired.", + target_item_dir, + ) + continue + if os.path.isdir(target_item_dir): + shutil.rmtree(target_item_dir) + else: + os.remove(target_item_dir) + + shutil.move(os.path.join(lib_dir, item), target_item_dir) + + def _determine_conflicts( + self, to_install: List[InstallRequirement] + ) -> Optional[ConflictDetails]: + try: + return check_install_conflicts(to_install) + except Exception: + logger.exception( + "Error while checking for conflicts. Please file an issue on " + "pip's issue tracker: https://github.com/pypa/pip/issues/new" + ) + return None + + def _warn_about_conflicts( + self, conflict_details: ConflictDetails, resolver_variant: str + ) -> None: + package_set, (missing, conflicting) = conflict_details + if not missing and not conflicting: + return + + parts: List[str] = [] + if resolver_variant == "legacy": + parts.append( + "pip's legacy dependency resolver does not consider dependency " + "conflicts when selecting packages. This behaviour is the " + "source of the following dependency conflicts." + ) + else: + assert resolver_variant == "resolvelib" + parts.append( + "pip's dependency resolver does not currently take into account " + "all the packages that are installed. This behaviour is the " + "source of the following dependency conflicts." + ) + + # NOTE: There is some duplication here, with commands/check.py + for project_name in missing: + version = package_set[project_name][0] + for dependency in missing[project_name]: + message = ( + f"{project_name} {version} requires {dependency[1]}, " + "which is not installed." + ) + parts.append(message) + + for project_name in conflicting: + version = package_set[project_name][0] + for dep_name, dep_version, req in conflicting[project_name]: + message = ( + "{name} {version} requires {requirement}, but {you} have " + "{dep_name} {dep_version} which is incompatible." + ).format( + name=project_name, + version=version, + requirement=req, + dep_name=dep_name, + dep_version=dep_version, + you=("you" if resolver_variant == "resolvelib" else "you'll"), + ) + parts.append(message) + + logger.critical("\n".join(parts)) + + +def get_lib_location_guesses( + user: bool = False, + home: Optional[str] = None, + root: Optional[str] = None, + isolated: bool = False, + prefix: Optional[str] = None, +) -> List[str]: + scheme = get_scheme( + "", + user=user, + home=home, + root=root, + isolated=isolated, + prefix=prefix, + ) + return [scheme.purelib, scheme.platlib] + + +def site_packages_writable(root: Optional[str], isolated: bool) -> bool: + return all( + test_writable_dir(d) + for d in set(get_lib_location_guesses(root=root, isolated=isolated)) + ) + + +def decide_user_install( + use_user_site: Optional[bool], + prefix_path: Optional[str] = None, + target_dir: Optional[str] = None, + root_path: Optional[str] = None, + isolated_mode: bool = False, +) -> bool: + """Determine whether to do a user install based on the input options. + + If use_user_site is False, no additional checks are done. + If use_user_site is True, it is checked for compatibility with other + options. + If use_user_site is None, the default behaviour depends on the environment, + which is provided by the other arguments. + """ + # In some cases (config from tox), use_user_site can be set to an integer + # rather than a bool, which 'use_user_site is False' wouldn't catch. + if (use_user_site is not None) and (not use_user_site): + logger.debug("Non-user install by explicit request") + return False + + if use_user_site: + if prefix_path: + raise CommandError( + "Can not combine '--user' and '--prefix' as they imply " + "different installation locations" + ) + if virtualenv_no_global(): + raise InstallationError( + "Can not perform a '--user' install. User site-packages " + "are not visible in this virtualenv." + ) + logger.debug("User install by explicit request") + return True + + # If we are here, user installs have not been explicitly requested/avoided + assert use_user_site is None + + # user install incompatible with --prefix/--target + if prefix_path or target_dir: + logger.debug("Non-user install due to --prefix or --target option") + return False + + # If user installs are not enabled, choose a non-user install + if not site.ENABLE_USER_SITE: + logger.debug("Non-user install because user site-packages disabled") + return False + + # If we have permission for a non-user install, do that, + # otherwise do a user install. + if site_packages_writable(root=root_path, isolated=isolated_mode): + logger.debug("Non-user install because site-packages writeable") + return False + + logger.info( + "Defaulting to user installation because normal site-packages " + "is not writeable" + ) + return True + + +def create_os_error_message( + error: OSError, show_traceback: bool, using_user_site: bool +) -> str: + """Format an error message for an OSError + + It may occur anytime during the execution of the install command. + """ + parts = [] + + # Mention the error if we are not going to show a traceback + parts.append("Could not install packages due to an OSError") + if not show_traceback: + parts.append(": ") + parts.append(str(error)) + else: + parts.append(".") + + # Spilt the error indication from a helper message (if any) + parts[-1] += "\n" + + # Suggest useful actions to the user: + # (1) using user site-packages or (2) verifying the permissions + if error.errno == errno.EACCES: + user_option_part = "Consider using the `--user` option" + permissions_part = "Check the permissions" + + if not running_under_virtualenv() and not using_user_site: + parts.extend( + [ + user_option_part, + " or ", + permissions_part.lower(), + ] + ) + else: + parts.append(permissions_part) + parts.append(".\n") + + # Suggest the user to enable Long Paths if path length is + # more than 260 + if ( + WINDOWS + and error.errno == errno.ENOENT + and error.filename + and len(error.filename) > 260 + ): + parts.append( + "HINT: This error might have occurred since " + "this system does not have Windows Long Path " + "support enabled. You can find information on " + "how to enable this at " + "https://pip.pypa.io/warnings/enable-long-paths\n" + ) + + return "".join(parts).strip() + "\n" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/list.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/list.py new file mode 100644 index 0000000000000000000000000000000000000000..8494370241064698d5aa891a10fce6bf3b8c1722 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/list.py @@ -0,0 +1,375 @@ +import json +import logging +from optparse import Values +from typing import TYPE_CHECKING, Generator, List, Optional, Sequence, Tuple, cast + +from pip._vendor.packaging.utils import canonicalize_name +from pip._vendor.packaging.version import Version + +from pip._internal.cli import cmdoptions +from pip._internal.cli.index_command import IndexGroupCommand +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.exceptions import CommandError +from pip._internal.metadata import BaseDistribution, get_environment +from pip._internal.models.selection_prefs import SelectionPreferences +from pip._internal.utils.compat import stdlib_pkgs +from pip._internal.utils.misc import tabulate, write_output + +if TYPE_CHECKING: + from pip._internal.index.package_finder import PackageFinder + from pip._internal.network.session import PipSession + + class _DistWithLatestInfo(BaseDistribution): + """Give the distribution object a couple of extra fields. + + These will be populated during ``get_outdated()``. This is dirty but + makes the rest of the code much cleaner. + """ + + latest_version: Version + latest_filetype: str + + _ProcessedDists = Sequence[_DistWithLatestInfo] + + +logger = logging.getLogger(__name__) + + +class ListCommand(IndexGroupCommand): + """ + List installed packages, including editables. + + Packages are listed in a case-insensitive sorted order. + """ + + ignore_require_venv = True + usage = """ + %prog [options]""" + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-o", + "--outdated", + action="store_true", + default=False, + help="List outdated packages", + ) + self.cmd_opts.add_option( + "-u", + "--uptodate", + action="store_true", + default=False, + help="List uptodate packages", + ) + self.cmd_opts.add_option( + "-e", + "--editable", + action="store_true", + default=False, + help="List editable projects.", + ) + self.cmd_opts.add_option( + "-l", + "--local", + action="store_true", + default=False, + help=( + "If in a virtualenv that has global access, do not list " + "globally-installed packages." + ), + ) + self.cmd_opts.add_option( + "--user", + dest="user", + action="store_true", + default=False, + help="Only output packages installed in user-site.", + ) + self.cmd_opts.add_option(cmdoptions.list_path()) + self.cmd_opts.add_option( + "--pre", + action="store_true", + default=False, + help=( + "Include pre-release and development versions. By default, " + "pip only finds stable versions." + ), + ) + + self.cmd_opts.add_option( + "--format", + action="store", + dest="list_format", + default="columns", + choices=("columns", "freeze", "json"), + help=( + "Select the output format among: columns (default), freeze, or json. " + "The 'freeze' format cannot be used with the --outdated option." + ), + ) + + self.cmd_opts.add_option( + "--not-required", + action="store_true", + dest="not_required", + help="List packages that are not dependencies of installed packages.", + ) + + self.cmd_opts.add_option( + "--exclude-editable", + action="store_false", + dest="include_editable", + help="Exclude editable package from output.", + ) + self.cmd_opts.add_option( + "--include-editable", + action="store_true", + dest="include_editable", + help="Include editable package from output.", + default=True, + ) + self.cmd_opts.add_option(cmdoptions.list_exclude()) + index_opts = cmdoptions.make_option_group(cmdoptions.index_group, self.parser) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + def handle_pip_version_check(self, options: Values) -> None: + if options.outdated or options.uptodate: + super().handle_pip_version_check(options) + + def _build_package_finder( + self, options: Values, session: "PipSession" + ) -> "PackageFinder": + """ + Create a package finder appropriate to this list command. + """ + # Lazy import the heavy index modules as most list invocations won't need 'em. + from pip._internal.index.collector import LinkCollector + from pip._internal.index.package_finder import PackageFinder + + link_collector = LinkCollector.create(session, options=options) + + # Pass allow_yanked=False to ignore yanked versions. + selection_prefs = SelectionPreferences( + allow_yanked=False, + allow_all_prereleases=options.pre, + ) + + return PackageFinder.create( + link_collector=link_collector, + selection_prefs=selection_prefs, + ) + + def run(self, options: Values, args: List[str]) -> int: + if options.outdated and options.uptodate: + raise CommandError("Options --outdated and --uptodate cannot be combined.") + + if options.outdated and options.list_format == "freeze": + raise CommandError( + "List format 'freeze' cannot be used with the --outdated option." + ) + + cmdoptions.check_list_path_option(options) + + skip = set(stdlib_pkgs) + if options.excludes: + skip.update(canonicalize_name(n) for n in options.excludes) + + packages: _ProcessedDists = [ + cast("_DistWithLatestInfo", d) + for d in get_environment(options.path).iter_installed_distributions( + local_only=options.local, + user_only=options.user, + editables_only=options.editable, + include_editables=options.include_editable, + skip=skip, + ) + ] + + # get_not_required must be called firstly in order to find and + # filter out all dependencies correctly. Otherwise a package + # can't be identified as requirement because some parent packages + # could be filtered out before. + if options.not_required: + packages = self.get_not_required(packages, options) + + if options.outdated: + packages = self.get_outdated(packages, options) + elif options.uptodate: + packages = self.get_uptodate(packages, options) + + self.output_package_listing(packages, options) + return SUCCESS + + def get_outdated( + self, packages: "_ProcessedDists", options: Values + ) -> "_ProcessedDists": + return [ + dist + for dist in self.iter_packages_latest_infos(packages, options) + if dist.latest_version > dist.version + ] + + def get_uptodate( + self, packages: "_ProcessedDists", options: Values + ) -> "_ProcessedDists": + return [ + dist + for dist in self.iter_packages_latest_infos(packages, options) + if dist.latest_version == dist.version + ] + + def get_not_required( + self, packages: "_ProcessedDists", options: Values + ) -> "_ProcessedDists": + dep_keys = { + canonicalize_name(dep.name) + for dist in packages + for dep in (dist.iter_dependencies() or ()) + } + + # Create a set to remove duplicate packages, and cast it to a list + # to keep the return type consistent with get_outdated and + # get_uptodate + return list({pkg for pkg in packages if pkg.canonical_name not in dep_keys}) + + def iter_packages_latest_infos( + self, packages: "_ProcessedDists", options: Values + ) -> Generator["_DistWithLatestInfo", None, None]: + with self._build_session(options) as session: + finder = self._build_package_finder(options, session) + + def latest_info( + dist: "_DistWithLatestInfo", + ) -> Optional["_DistWithLatestInfo"]: + all_candidates = finder.find_all_candidates(dist.canonical_name) + if not options.pre: + # Remove prereleases + all_candidates = [ + candidate + for candidate in all_candidates + if not candidate.version.is_prerelease + ] + + evaluator = finder.make_candidate_evaluator( + project_name=dist.canonical_name, + ) + best_candidate = evaluator.sort_best_candidate(all_candidates) + if best_candidate is None: + return None + + remote_version = best_candidate.version + if best_candidate.link.is_wheel: + typ = "wheel" + else: + typ = "sdist" + dist.latest_version = remote_version + dist.latest_filetype = typ + return dist + + for dist in map(latest_info, packages): + if dist is not None: + yield dist + + def output_package_listing( + self, packages: "_ProcessedDists", options: Values + ) -> None: + packages = sorted( + packages, + key=lambda dist: dist.canonical_name, + ) + if options.list_format == "columns" and packages: + data, header = format_for_columns(packages, options) + self.output_package_listing_columns(data, header) + elif options.list_format == "freeze": + for dist in packages: + if options.verbose >= 1: + write_output( + "%s==%s (%s)", dist.raw_name, dist.version, dist.location + ) + else: + write_output("%s==%s", dist.raw_name, dist.version) + elif options.list_format == "json": + write_output(format_for_json(packages, options)) + + def output_package_listing_columns( + self, data: List[List[str]], header: List[str] + ) -> None: + # insert the header first: we need to know the size of column names + if len(data) > 0: + data.insert(0, header) + + pkg_strings, sizes = tabulate(data) + + # Create and add a separator. + if len(data) > 0: + pkg_strings.insert(1, " ".join("-" * x for x in sizes)) + + for val in pkg_strings: + write_output(val) + + +def format_for_columns( + pkgs: "_ProcessedDists", options: Values +) -> Tuple[List[List[str]], List[str]]: + """ + Convert the package data into something usable + by output_package_listing_columns. + """ + header = ["Package", "Version"] + + running_outdated = options.outdated + if running_outdated: + header.extend(["Latest", "Type"]) + + has_editables = any(x.editable for x in pkgs) + if has_editables: + header.append("Editable project location") + + if options.verbose >= 1: + header.append("Location") + if options.verbose >= 1: + header.append("Installer") + + data = [] + for proj in pkgs: + # if we're working on the 'outdated' list, separate out the + # latest_version and type + row = [proj.raw_name, proj.raw_version] + + if running_outdated: + row.append(str(proj.latest_version)) + row.append(proj.latest_filetype) + + if has_editables: + row.append(proj.editable_project_location or "") + + if options.verbose >= 1: + row.append(proj.location or "") + if options.verbose >= 1: + row.append(proj.installer) + + data.append(row) + + return data, header + + +def format_for_json(packages: "_ProcessedDists", options: Values) -> str: + data = [] + for dist in packages: + info = { + "name": dist.raw_name, + "version": str(dist.version), + } + if options.verbose >= 1: + info["location"] = dist.location or "" + info["installer"] = dist.installer + if options.outdated: + info["latest_version"] = str(dist.latest_version) + info["latest_filetype"] = dist.latest_filetype + editable_project_location = dist.editable_project_location + if editable_project_location: + info["editable_project_location"] = editable_project_location + data.append(info) + return json.dumps(data) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/search.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/search.py new file mode 100644 index 0000000000000000000000000000000000000000..74b8d656b4749d15cc47aebccd9ca22f74357f25 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/search.py @@ -0,0 +1,172 @@ +import logging +import shutil +import sys +import textwrap +import xmlrpc.client +from collections import OrderedDict +from optparse import Values +from typing import TYPE_CHECKING, Dict, List, Optional, TypedDict + +from pip._vendor.packaging.version import parse as parse_version + +from pip._internal.cli.base_command import Command +from pip._internal.cli.req_command import SessionCommandMixin +from pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS +from pip._internal.exceptions import CommandError +from pip._internal.metadata import get_default_environment +from pip._internal.models.index import PyPI +from pip._internal.network.xmlrpc import PipXmlrpcTransport +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import write_output + +if TYPE_CHECKING: + + class TransformedHit(TypedDict): + name: str + summary: str + versions: List[str] + + +logger = logging.getLogger(__name__) + + +class SearchCommand(Command, SessionCommandMixin): + """Search for PyPI packages whose name or summary contains .""" + + usage = """ + %prog [options] """ + ignore_require_venv = True + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-i", + "--index", + dest="index", + metavar="URL", + default=PyPI.pypi_url, + help="Base URL of Python Package Index (default %default)", + ) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + if not args: + raise CommandError("Missing required argument (search query).") + query = args + pypi_hits = self.search(query, options) + hits = transform_hits(pypi_hits) + + terminal_width = None + if sys.stdout.isatty(): + terminal_width = shutil.get_terminal_size()[0] + + print_results(hits, terminal_width=terminal_width) + if pypi_hits: + return SUCCESS + return NO_MATCHES_FOUND + + def search(self, query: List[str], options: Values) -> List[Dict[str, str]]: + index_url = options.index + + session = self.get_default_session(options) + + transport = PipXmlrpcTransport(index_url, session) + pypi = xmlrpc.client.ServerProxy(index_url, transport) + try: + hits = pypi.search({"name": query, "summary": query}, "or") + except xmlrpc.client.Fault as fault: + message = ( + f"XMLRPC request failed [code: {fault.faultCode}]\n{fault.faultString}" + ) + raise CommandError(message) + assert isinstance(hits, list) + return hits + + +def transform_hits(hits: List[Dict[str, str]]) -> List["TransformedHit"]: + """ + The list from pypi is really a list of versions. We want a list of + packages with the list of versions stored inline. This converts the + list from pypi into one we can use. + """ + packages: Dict[str, TransformedHit] = OrderedDict() + for hit in hits: + name = hit["name"] + summary = hit["summary"] + version = hit["version"] + + if name not in packages.keys(): + packages[name] = { + "name": name, + "summary": summary, + "versions": [version], + } + else: + packages[name]["versions"].append(version) + + # if this is the highest version, replace summary and score + if version == highest_version(packages[name]["versions"]): + packages[name]["summary"] = summary + + return list(packages.values()) + + +def print_dist_installation_info(name: str, latest: str) -> None: + env = get_default_environment() + dist = env.get_distribution(name) + if dist is not None: + with indent_log(): + if dist.version == latest: + write_output("INSTALLED: %s (latest)", dist.version) + else: + write_output("INSTALLED: %s", dist.version) + if parse_version(latest).pre: + write_output( + "LATEST: %s (pre-release; install" + " with `pip install --pre`)", + latest, + ) + else: + write_output("LATEST: %s", latest) + + +def print_results( + hits: List["TransformedHit"], + name_column_width: Optional[int] = None, + terminal_width: Optional[int] = None, +) -> None: + if not hits: + return + if name_column_width is None: + name_column_width = ( + max( + [ + len(hit["name"]) + len(highest_version(hit.get("versions", ["-"]))) + for hit in hits + ] + ) + + 4 + ) + + for hit in hits: + name = hit["name"] + summary = hit["summary"] or "" + latest = highest_version(hit.get("versions", ["-"])) + if terminal_width is not None: + target_width = terminal_width - name_column_width - 5 + if target_width > 10: + # wrap and indent summary to fit terminal + summary_lines = textwrap.wrap(summary, target_width) + summary = ("\n" + " " * (name_column_width + 3)).join(summary_lines) + + name_latest = f"{name} ({latest})" + line = f"{name_latest:{name_column_width}} - {summary}" + try: + write_output(line) + print_dist_installation_info(name, latest) + except UnicodeEncodeError: + pass + + +def highest_version(versions: List[str]) -> str: + return max(versions, key=parse_version) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/show.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/show.py new file mode 100644 index 0000000000000000000000000000000000000000..b47500cf8b47598a001fd9a20eb2e5e1f3788cda --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/show.py @@ -0,0 +1,224 @@ +import logging +from optparse import Values +from typing import Generator, Iterable, Iterator, List, NamedTuple, Optional + +from pip._vendor.packaging.requirements import InvalidRequirement +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.metadata import BaseDistribution, get_default_environment +from pip._internal.utils.misc import write_output + +logger = logging.getLogger(__name__) + + +class ShowCommand(Command): + """ + Show information about one or more installed packages. + + The output is in RFC-compliant mail header format. + """ + + usage = """ + %prog [options] ...""" + ignore_require_venv = True + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-f", + "--files", + dest="files", + action="store_true", + default=False, + help="Show the full list of installed files for each package.", + ) + + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + if not args: + logger.warning("ERROR: Please provide a package name or names.") + return ERROR + query = args + + results = search_packages_info(query) + if not print_results( + results, list_files=options.files, verbose=options.verbose + ): + return ERROR + return SUCCESS + + +class _PackageInfo(NamedTuple): + name: str + version: str + location: str + editable_project_location: Optional[str] + requires: List[str] + required_by: List[str] + installer: str + metadata_version: str + classifiers: List[str] + summary: str + homepage: str + project_urls: List[str] + author: str + author_email: str + license: str + license_expression: str + entry_points: List[str] + files: Optional[List[str]] + + +def search_packages_info(query: List[str]) -> Generator[_PackageInfo, None, None]: + """ + Gather details from installed distributions. Print distribution name, + version, location, and installed files. Installed files requires a + pip generated 'installed-files.txt' in the distributions '.egg-info' + directory. + """ + env = get_default_environment() + + installed = {dist.canonical_name: dist for dist in env.iter_all_distributions()} + query_names = [canonicalize_name(name) for name in query] + missing = sorted( + [name for name, pkg in zip(query, query_names) if pkg not in installed] + ) + if missing: + logger.warning("Package(s) not found: %s", ", ".join(missing)) + + def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]: + return ( + dist.metadata["Name"] or "UNKNOWN" + for dist in installed.values() + if current_dist.canonical_name + in {canonicalize_name(d.name) for d in dist.iter_dependencies()} + ) + + for query_name in query_names: + try: + dist = installed[query_name] + except KeyError: + continue + + try: + requires = sorted( + # Avoid duplicates in requirements (e.g. due to environment markers). + {req.name for req in dist.iter_dependencies()}, + key=str.lower, + ) + except InvalidRequirement: + requires = sorted(dist.iter_raw_dependencies(), key=str.lower) + + try: + required_by = sorted(_get_requiring_packages(dist), key=str.lower) + except InvalidRequirement: + required_by = ["#N/A"] + + try: + entry_points_text = dist.read_text("entry_points.txt") + entry_points = entry_points_text.splitlines(keepends=False) + except FileNotFoundError: + entry_points = [] + + files_iter = dist.iter_declared_entries() + if files_iter is None: + files: Optional[List[str]] = None + else: + files = sorted(files_iter) + + metadata = dist.metadata + + project_urls = metadata.get_all("Project-URL", []) + homepage = metadata.get("Home-page", "") + if not homepage: + # It's common that there is a "homepage" Project-URL, but Home-page + # remains unset (especially as PEP 621 doesn't surface the field). + # + # This logic was taken from PyPI's codebase. + for url in project_urls: + url_label, url = url.split(",", maxsplit=1) + normalized_label = ( + url_label.casefold().replace("-", "").replace("_", "").strip() + ) + if normalized_label == "homepage": + homepage = url.strip() + break + + yield _PackageInfo( + name=dist.raw_name, + version=dist.raw_version, + location=dist.location or "", + editable_project_location=dist.editable_project_location, + requires=requires, + required_by=required_by, + installer=dist.installer, + metadata_version=dist.metadata_version or "", + classifiers=metadata.get_all("Classifier", []), + summary=metadata.get("Summary", ""), + homepage=homepage, + project_urls=project_urls, + author=metadata.get("Author", ""), + author_email=metadata.get("Author-email", ""), + license=metadata.get("License", ""), + license_expression=metadata.get("License-Expression", ""), + entry_points=entry_points, + files=files, + ) + + +def print_results( + distributions: Iterable[_PackageInfo], + list_files: bool, + verbose: bool, +) -> bool: + """ + Print the information from installed distributions found. + """ + results_printed = False + for i, dist in enumerate(distributions): + results_printed = True + if i > 0: + write_output("---") + + metadata_version_tuple = tuple(map(int, dist.metadata_version.split("."))) + + write_output("Name: %s", dist.name) + write_output("Version: %s", dist.version) + write_output("Summary: %s", dist.summary) + write_output("Home-page: %s", dist.homepage) + write_output("Author: %s", dist.author) + write_output("Author-email: %s", dist.author_email) + if metadata_version_tuple >= (2, 4) and dist.license_expression: + write_output("License-Expression: %s", dist.license_expression) + else: + write_output("License: %s", dist.license) + write_output("Location: %s", dist.location) + if dist.editable_project_location is not None: + write_output( + "Editable project location: %s", dist.editable_project_location + ) + write_output("Requires: %s", ", ".join(dist.requires)) + write_output("Required-by: %s", ", ".join(dist.required_by)) + + if verbose: + write_output("Metadata-Version: %s", dist.metadata_version) + write_output("Installer: %s", dist.installer) + write_output("Classifiers:") + for classifier in dist.classifiers: + write_output(" %s", classifier) + write_output("Entry-points:") + for entry in dist.entry_points: + write_output(" %s", entry.strip()) + write_output("Project-URLs:") + for project_url in dist.project_urls: + write_output(" %s", project_url) + if list_files: + write_output("Files:") + if dist.files is None: + write_output("Cannot locate RECORD or installed-files.txt") + else: + for line in dist.files: + write_output(" %s", line.strip()) + return results_printed diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/uninstall.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/uninstall.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0edeac9fb74e4dfb6d7a095483c11557d268ba --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/uninstall.py @@ -0,0 +1,114 @@ +import logging +from optparse import Values +from typing import List + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.cli import cmdoptions +from pip._internal.cli.base_command import Command +from pip._internal.cli.index_command import SessionCommandMixin +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.exceptions import InstallationError +from pip._internal.req import parse_requirements +from pip._internal.req.constructors import ( + install_req_from_line, + install_req_from_parsed_requirement, +) +from pip._internal.utils.misc import ( + check_externally_managed, + protect_pip_from_modification_on_windows, + warn_if_run_as_root, +) + +logger = logging.getLogger(__name__) + + +class UninstallCommand(Command, SessionCommandMixin): + """ + Uninstall packages. + + pip is able to uninstall most installed packages. Known exceptions are: + + - Pure distutils packages installed with ``python setup.py install``, which + leave behind no metadata to determine what files were installed. + - Script wrappers installed by ``python setup.py develop``. + """ + + usage = """ + %prog [options] ... + %prog [options] -r ...""" + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-r", + "--requirement", + dest="requirements", + action="append", + default=[], + metavar="file", + help=( + "Uninstall all the packages listed in the given requirements " + "file. This option can be used multiple times." + ), + ) + self.cmd_opts.add_option( + "-y", + "--yes", + dest="yes", + action="store_true", + help="Don't ask for confirmation of uninstall deletions.", + ) + self.cmd_opts.add_option(cmdoptions.root_user_action()) + self.cmd_opts.add_option(cmdoptions.override_externally_managed()) + self.parser.insert_option_group(0, self.cmd_opts) + + def run(self, options: Values, args: List[str]) -> int: + session = self.get_default_session(options) + + reqs_to_uninstall = {} + for name in args: + req = install_req_from_line( + name, + isolated=options.isolated_mode, + ) + if req.name: + reqs_to_uninstall[canonicalize_name(req.name)] = req + else: + logger.warning( + "Invalid requirement: %r ignored -" + " the uninstall command expects named" + " requirements.", + name, + ) + for filename in options.requirements: + for parsed_req in parse_requirements( + filename, options=options, session=session + ): + req = install_req_from_parsed_requirement( + parsed_req, isolated=options.isolated_mode + ) + if req.name: + reqs_to_uninstall[canonicalize_name(req.name)] = req + if not reqs_to_uninstall: + raise InstallationError( + f"You must give at least one requirement to {self.name} (see " + f'"pip help {self.name}")' + ) + + if not options.override_externally_managed: + check_externally_managed() + + protect_pip_from_modification_on_windows( + modifying_pip="pip" in reqs_to_uninstall + ) + + for req in reqs_to_uninstall.values(): + uninstall_pathset = req.uninstall( + auto_confirm=options.yes, + verbose=self.verbosity > 0, + ) + if uninstall_pathset: + uninstall_pathset.commit() + if options.root_user_action == "warn": + warn_if_run_as_root() + return SUCCESS diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/wheel.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..278719f4e0c6643e5f01bccdd440b1504bf5f7c9 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/commands/wheel.py @@ -0,0 +1,182 @@ +import logging +import os +import shutil +from optparse import Values +from typing import List + +from pip._internal.cache import WheelCache +from pip._internal.cli import cmdoptions +from pip._internal.cli.req_command import RequirementCommand, with_cleanup +from pip._internal.cli.status_codes import SUCCESS +from pip._internal.exceptions import CommandError +from pip._internal.operations.build.build_tracker import get_build_tracker +from pip._internal.req.req_install import ( + InstallRequirement, + check_legacy_setup_py_options, +) +from pip._internal.utils.misc import ensure_dir, normalize_path +from pip._internal.utils.temp_dir import TempDirectory +from pip._internal.wheel_builder import build, should_build_for_wheel_command + +logger = logging.getLogger(__name__) + + +class WheelCommand(RequirementCommand): + """ + Build Wheel archives for your requirements and dependencies. + + Wheel is a built-package format, and offers the advantage of not + recompiling your software during every install. For more details, see the + wheel docs: https://wheel.readthedocs.io/en/latest/ + + 'pip wheel' uses the build system interface as described here: + https://pip.pypa.io/en/stable/reference/build-system/ + + """ + + usage = """ + %prog [options] ... + %prog [options] -r ... + %prog [options] [-e] ... + %prog [options] [-e] ... + %prog [options] ...""" + + def add_options(self) -> None: + self.cmd_opts.add_option( + "-w", + "--wheel-dir", + dest="wheel_dir", + metavar="dir", + default=os.curdir, + help=( + "Build wheels into , where the default is the " + "current working directory." + ), + ) + self.cmd_opts.add_option(cmdoptions.no_binary()) + self.cmd_opts.add_option(cmdoptions.only_binary()) + self.cmd_opts.add_option(cmdoptions.prefer_binary()) + self.cmd_opts.add_option(cmdoptions.no_build_isolation()) + self.cmd_opts.add_option(cmdoptions.use_pep517()) + self.cmd_opts.add_option(cmdoptions.no_use_pep517()) + self.cmd_opts.add_option(cmdoptions.check_build_deps()) + self.cmd_opts.add_option(cmdoptions.constraints()) + self.cmd_opts.add_option(cmdoptions.editable()) + self.cmd_opts.add_option(cmdoptions.requirements()) + self.cmd_opts.add_option(cmdoptions.src()) + self.cmd_opts.add_option(cmdoptions.ignore_requires_python()) + self.cmd_opts.add_option(cmdoptions.no_deps()) + self.cmd_opts.add_option(cmdoptions.progress_bar()) + + self.cmd_opts.add_option( + "--no-verify", + dest="no_verify", + action="store_true", + default=False, + help="Don't verify if built wheel is valid.", + ) + + self.cmd_opts.add_option(cmdoptions.config_settings()) + self.cmd_opts.add_option(cmdoptions.build_options()) + self.cmd_opts.add_option(cmdoptions.global_options()) + + self.cmd_opts.add_option( + "--pre", + action="store_true", + default=False, + help=( + "Include pre-release and development versions. By default, " + "pip only finds stable versions." + ), + ) + + self.cmd_opts.add_option(cmdoptions.require_hashes()) + + index_opts = cmdoptions.make_option_group( + cmdoptions.index_group, + self.parser, + ) + + self.parser.insert_option_group(0, index_opts) + self.parser.insert_option_group(0, self.cmd_opts) + + @with_cleanup + def run(self, options: Values, args: List[str]) -> int: + session = self.get_default_session(options) + + finder = self._build_package_finder(options, session) + + options.wheel_dir = normalize_path(options.wheel_dir) + ensure_dir(options.wheel_dir) + + build_tracker = self.enter_context(get_build_tracker()) + + directory = TempDirectory( + delete=not options.no_clean, + kind="wheel", + globally_managed=True, + ) + + reqs = self.get_requirements(args, options, finder, session) + check_legacy_setup_py_options(options, reqs) + + wheel_cache = WheelCache(options.cache_dir) + + preparer = self.make_requirement_preparer( + temp_build_dir=directory, + options=options, + build_tracker=build_tracker, + session=session, + finder=finder, + download_dir=options.wheel_dir, + use_user_site=False, + verbosity=self.verbosity, + ) + + resolver = self.make_resolver( + preparer=preparer, + finder=finder, + options=options, + wheel_cache=wheel_cache, + ignore_requires_python=options.ignore_requires_python, + use_pep517=options.use_pep517, + ) + + self.trace_basic_info(finder) + + requirement_set = resolver.resolve(reqs, check_supported_wheels=True) + + reqs_to_build: List[InstallRequirement] = [] + for req in requirement_set.requirements.values(): + if req.is_wheel: + preparer.save_linked_requirement(req) + elif should_build_for_wheel_command(req): + reqs_to_build.append(req) + + preparer.prepare_linked_requirements_more(requirement_set.requirements.values()) + + # build wheels + build_successes, build_failures = build( + reqs_to_build, + wheel_cache=wheel_cache, + verify=(not options.no_verify), + build_options=options.build_options or [], + global_options=options.global_options or [], + ) + for req in build_successes: + assert req.link and req.link.is_wheel + assert req.local_file_path + # copy from cache to target directory + try: + shutil.copy(req.local_file_path, options.wheel_dir) + except OSError as e: + logger.warning( + "Building wheel for %s failed: %s", + req.name, + e, + ) + build_failures.append(req) + if len(build_failures) != 0: + raise CommandError("Failed to build one or more wheels") + + return SUCCESS diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/configuration.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..ffeda1d47a1bd2ec27174ed46b34ce9c7676bbca --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/configuration.py @@ -0,0 +1,383 @@ +"""Configuration management setup + +Some terminology: +- name + As written in config files. +- value + Value associated with a name +- key + Name combined with it's section (section.name) +- variant + A single word describing where the configuration key-value pair came from +""" + +import configparser +import locale +import os +import sys +from typing import Any, Dict, Iterable, List, NewType, Optional, Tuple + +from pip._internal.exceptions import ( + ConfigurationError, + ConfigurationFileCouldNotBeLoaded, +) +from pip._internal.utils import appdirs +from pip._internal.utils.compat import WINDOWS +from pip._internal.utils.logging import getLogger +from pip._internal.utils.misc import ensure_dir, enum + +RawConfigParser = configparser.RawConfigParser # Shorthand +Kind = NewType("Kind", str) + +CONFIG_BASENAME = "pip.ini" if WINDOWS else "pip.conf" +ENV_NAMES_IGNORED = "version", "help" + +# The kinds of configurations there are. +kinds = enum( + USER="user", # User Specific + GLOBAL="global", # System Wide + SITE="site", # [Virtual] Environment Specific + ENV="env", # from PIP_CONFIG_FILE + ENV_VAR="env-var", # from Environment Variables +) +OVERRIDE_ORDER = kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR +VALID_LOAD_ONLY = kinds.USER, kinds.GLOBAL, kinds.SITE + +logger = getLogger(__name__) + + +# NOTE: Maybe use the optionx attribute to normalize keynames. +def _normalize_name(name: str) -> str: + """Make a name consistent regardless of source (environment or file)""" + name = name.lower().replace("_", "-") + if name.startswith("--"): + name = name[2:] # only prefer long opts + return name + + +def _disassemble_key(name: str) -> List[str]: + if "." not in name: + error_message = ( + "Key does not contain dot separated section and key. " + f"Perhaps you wanted to use 'global.{name}' instead?" + ) + raise ConfigurationError(error_message) + return name.split(".", 1) + + +def get_configuration_files() -> Dict[Kind, List[str]]: + global_config_files = [ + os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs("pip") + ] + + site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME) + legacy_config_file = os.path.join( + os.path.expanduser("~"), + "pip" if WINDOWS else ".pip", + CONFIG_BASENAME, + ) + new_config_file = os.path.join(appdirs.user_config_dir("pip"), CONFIG_BASENAME) + return { + kinds.GLOBAL: global_config_files, + kinds.SITE: [site_config_file], + kinds.USER: [legacy_config_file, new_config_file], + } + + +class Configuration: + """Handles management of configuration. + + Provides an interface to accessing and managing configuration files. + + This class converts provides an API that takes "section.key-name" style + keys and stores the value associated with it as "key-name" under the + section "section". + + This allows for a clean interface wherein the both the section and the + key-name are preserved in an easy to manage form in the configuration files + and the data stored is also nice. + """ + + def __init__(self, isolated: bool, load_only: Optional[Kind] = None) -> None: + super().__init__() + + if load_only is not None and load_only not in VALID_LOAD_ONLY: + raise ConfigurationError( + "Got invalid value for load_only - should be one of {}".format( + ", ".join(map(repr, VALID_LOAD_ONLY)) + ) + ) + self.isolated = isolated + self.load_only = load_only + + # Because we keep track of where we got the data from + self._parsers: Dict[Kind, List[Tuple[str, RawConfigParser]]] = { + variant: [] for variant in OVERRIDE_ORDER + } + self._config: Dict[Kind, Dict[str, Any]] = { + variant: {} for variant in OVERRIDE_ORDER + } + self._modified_parsers: List[Tuple[str, RawConfigParser]] = [] + + def load(self) -> None: + """Loads configuration from configuration files and environment""" + self._load_config_files() + if not self.isolated: + self._load_environment_vars() + + def get_file_to_edit(self) -> Optional[str]: + """Returns the file with highest priority in configuration""" + assert self.load_only is not None, "Need to be specified a file to be editing" + + try: + return self._get_parser_to_modify()[0] + except IndexError: + return None + + def items(self) -> Iterable[Tuple[str, Any]]: + """Returns key-value pairs like dict.items() representing the loaded + configuration + """ + return self._dictionary.items() + + def get_value(self, key: str) -> Any: + """Get a value from the configuration.""" + orig_key = key + key = _normalize_name(key) + try: + return self._dictionary[key] + except KeyError: + # disassembling triggers a more useful error message than simply + # "No such key" in the case that the key isn't in the form command.option + _disassemble_key(key) + raise ConfigurationError(f"No such key - {orig_key}") + + def set_value(self, key: str, value: Any) -> None: + """Modify a value in the configuration.""" + key = _normalize_name(key) + self._ensure_have_load_only() + + assert self.load_only + fname, parser = self._get_parser_to_modify() + + if parser is not None: + section, name = _disassemble_key(key) + + # Modify the parser and the configuration + if not parser.has_section(section): + parser.add_section(section) + parser.set(section, name, value) + + self._config[self.load_only][key] = value + self._mark_as_modified(fname, parser) + + def unset_value(self, key: str) -> None: + """Unset a value in the configuration.""" + orig_key = key + key = _normalize_name(key) + self._ensure_have_load_only() + + assert self.load_only + if key not in self._config[self.load_only]: + raise ConfigurationError(f"No such key - {orig_key}") + + fname, parser = self._get_parser_to_modify() + + if parser is not None: + section, name = _disassemble_key(key) + if not ( + parser.has_section(section) and parser.remove_option(section, name) + ): + # The option was not removed. + raise ConfigurationError( + "Fatal Internal error [id=1]. Please report as a bug." + ) + + # The section may be empty after the option was removed. + if not parser.items(section): + parser.remove_section(section) + self._mark_as_modified(fname, parser) + + del self._config[self.load_only][key] + + def save(self) -> None: + """Save the current in-memory state.""" + self._ensure_have_load_only() + + for fname, parser in self._modified_parsers: + logger.info("Writing to %s", fname) + + # Ensure directory exists. + ensure_dir(os.path.dirname(fname)) + + # Ensure directory's permission(need to be writeable) + try: + with open(fname, "w") as f: + parser.write(f) + except OSError as error: + raise ConfigurationError( + f"An error occurred while writing to the configuration file " + f"{fname}: {error}" + ) + + # + # Private routines + # + + def _ensure_have_load_only(self) -> None: + if self.load_only is None: + raise ConfigurationError("Needed a specific file to be modifying.") + logger.debug("Will be working with %s variant only", self.load_only) + + @property + def _dictionary(self) -> Dict[str, Any]: + """A dictionary representing the loaded configuration.""" + # NOTE: Dictionaries are not populated if not loaded. So, conditionals + # are not needed here. + retval = {} + + for variant in OVERRIDE_ORDER: + retval.update(self._config[variant]) + + return retval + + def _load_config_files(self) -> None: + """Loads configuration from configuration files""" + config_files = dict(self.iter_config_files()) + if config_files[kinds.ENV][0:1] == [os.devnull]: + logger.debug( + "Skipping loading configuration files due to " + "environment's PIP_CONFIG_FILE being os.devnull" + ) + return + + for variant, files in config_files.items(): + for fname in files: + # If there's specific variant set in `load_only`, load only + # that variant, not the others. + if self.load_only is not None and variant != self.load_only: + logger.debug("Skipping file '%s' (variant: %s)", fname, variant) + continue + + parser = self._load_file(variant, fname) + + # Keeping track of the parsers used + self._parsers[variant].append((fname, parser)) + + def _load_file(self, variant: Kind, fname: str) -> RawConfigParser: + logger.verbose("For variant '%s', will try loading '%s'", variant, fname) + parser = self._construct_parser(fname) + + for section in parser.sections(): + items = parser.items(section) + self._config[variant].update(self._normalized_keys(section, items)) + + return parser + + def _construct_parser(self, fname: str) -> RawConfigParser: + parser = configparser.RawConfigParser() + # If there is no such file, don't bother reading it but create the + # parser anyway, to hold the data. + # Doing this is useful when modifying and saving files, where we don't + # need to construct a parser. + if os.path.exists(fname): + locale_encoding = locale.getpreferredencoding(False) + try: + parser.read(fname, encoding=locale_encoding) + except UnicodeDecodeError: + # See https://github.com/pypa/pip/issues/4963 + raise ConfigurationFileCouldNotBeLoaded( + reason=f"contains invalid {locale_encoding} characters", + fname=fname, + ) + except configparser.Error as error: + # See https://github.com/pypa/pip/issues/4893 + raise ConfigurationFileCouldNotBeLoaded(error=error) + return parser + + def _load_environment_vars(self) -> None: + """Loads configuration from environment variables""" + self._config[kinds.ENV_VAR].update( + self._normalized_keys(":env:", self.get_environ_vars()) + ) + + def _normalized_keys( + self, section: str, items: Iterable[Tuple[str, Any]] + ) -> Dict[str, Any]: + """Normalizes items to construct a dictionary with normalized keys. + + This routine is where the names become keys and are made the same + regardless of source - configuration files or environment. + """ + normalized = {} + for name, val in items: + key = section + "." + _normalize_name(name) + normalized[key] = val + return normalized + + def get_environ_vars(self) -> Iterable[Tuple[str, str]]: + """Returns a generator with all environmental vars with prefix PIP_""" + for key, val in os.environ.items(): + if key.startswith("PIP_"): + name = key[4:].lower() + if name not in ENV_NAMES_IGNORED: + yield name, val + + # XXX: This is patched in the tests. + def iter_config_files(self) -> Iterable[Tuple[Kind, List[str]]]: + """Yields variant and configuration files associated with it. + + This should be treated like items of a dictionary. The order + here doesn't affect what gets overridden. That is controlled + by OVERRIDE_ORDER. However this does control the order they are + displayed to the user. It's probably most ergonomic to display + things in the same order as OVERRIDE_ORDER + """ + # SMELL: Move the conditions out of this function + + env_config_file = os.environ.get("PIP_CONFIG_FILE", None) + config_files = get_configuration_files() + + yield kinds.GLOBAL, config_files[kinds.GLOBAL] + + # per-user config is not loaded when env_config_file exists + should_load_user_config = not self.isolated and not ( + env_config_file and os.path.exists(env_config_file) + ) + if should_load_user_config: + # The legacy config file is overridden by the new config file + yield kinds.USER, config_files[kinds.USER] + + # virtualenv config + yield kinds.SITE, config_files[kinds.SITE] + + if env_config_file is not None: + yield kinds.ENV, [env_config_file] + else: + yield kinds.ENV, [] + + def get_values_in_config(self, variant: Kind) -> Dict[str, Any]: + """Get values present in a config file""" + return self._config[variant] + + def _get_parser_to_modify(self) -> Tuple[str, RawConfigParser]: + # Determine which parser to modify + assert self.load_only + parsers = self._parsers[self.load_only] + if not parsers: + # This should not happen if everything works correctly. + raise ConfigurationError( + "Fatal Internal error [id=2]. Please report as a bug." + ) + + # Use the highest priority parser. + return parsers[-1] + + # XXX: This is patched in the tests. + def _mark_as_modified(self, fname: str, parser: RawConfigParser) -> None: + file_parser_tuple = (fname, parser) + if file_parser_tuple not in self._modified_parsers: + self._modified_parsers.append(file_parser_tuple) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self._dictionary!r})" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a89a838b9a5cb264e9ae9d269fbedca6e2d6333 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__init__.py @@ -0,0 +1,21 @@ +from pip._internal.distributions.base import AbstractDistribution +from pip._internal.distributions.sdist import SourceDistribution +from pip._internal.distributions.wheel import WheelDistribution +from pip._internal.req.req_install import InstallRequirement + + +def make_distribution_for_install_requirement( + install_req: InstallRequirement, +) -> AbstractDistribution: + """Returns a Distribution for the given InstallRequirement""" + # Editable requirements will always be source distributions. They use the + # legacy logic until we create a modern standard for them. + if install_req.editable: + return SourceDistribution(install_req) + + # If it's a wheel, it's a WheelDistribution + if install_req.is_wheel: + return WheelDistribution(install_req) + + # Otherwise, a SourceDistribution + return SourceDistribution(install_req) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..531b53b3094098fc7e4022a9e80c6f8d430c4880 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/base.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebbd07eca650c1bc5b237d7957b1faf4e1b333a7 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/base.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffc1e28abdd9bcfc0f06c9f924b4e83446548b72 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bad767806d0595d2bfd15d194b69aa02ded69d6c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53b709657f24b6d4cd5e3f120922fec913976aaa Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/base.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/base.py new file mode 100644 index 0000000000000000000000000000000000000000..6e4d0c91a901c46ab20be813af083cd19809318a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/base.py @@ -0,0 +1,53 @@ +import abc +from typing import TYPE_CHECKING, Optional + +from pip._internal.metadata.base import BaseDistribution +from pip._internal.req import InstallRequirement + +if TYPE_CHECKING: + from pip._internal.index.package_finder import PackageFinder + + +class AbstractDistribution(metaclass=abc.ABCMeta): + """A base class for handling installable artifacts. + + The requirements for anything installable are as follows: + + - we must be able to determine the requirement name + (or we can't correctly handle the non-upgrade case). + + - for packages with setup requirements, we must also be able + to determine their requirements without installing additional + packages (for the same reason as run-time dependencies) + + - we must be able to create a Distribution object exposing the + above metadata. + + - if we need to do work in the build tracker, we must be able to generate a unique + string to identify the requirement in the build tracker. + """ + + def __init__(self, req: InstallRequirement) -> None: + super().__init__() + self.req = req + + @abc.abstractproperty + def build_tracker_id(self) -> Optional[str]: + """A string that uniquely identifies this requirement to the build tracker. + + If None, then this dist has no work to do in the build tracker, and + ``.prepare_distribution_metadata()`` will not be called.""" + raise NotImplementedError() + + @abc.abstractmethod + def get_metadata_distribution(self) -> BaseDistribution: + raise NotImplementedError() + + @abc.abstractmethod + def prepare_distribution_metadata( + self, + finder: "PackageFinder", + build_isolation: bool, + check_build_deps: bool, + ) -> None: + raise NotImplementedError() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/installed.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/installed.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8d53be7408626719c27aa29fdc2e143b7c380a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/installed.py @@ -0,0 +1,29 @@ +from typing import Optional + +from pip._internal.distributions.base import AbstractDistribution +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata import BaseDistribution + + +class InstalledDistribution(AbstractDistribution): + """Represents an installed package. + + This does not need any preparation as the required information has already + been computed. + """ + + @property + def build_tracker_id(self) -> Optional[str]: + return None + + def get_metadata_distribution(self) -> BaseDistribution: + assert self.req.satisfied_by is not None, "not actually installed" + return self.req.satisfied_by + + def prepare_distribution_metadata( + self, + finder: PackageFinder, + build_isolation: bool, + check_build_deps: bool, + ) -> None: + pass diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..28ea5cea16cdf9b740809553cbf2d3bf8d626e1e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/sdist.py @@ -0,0 +1,158 @@ +import logging +from typing import TYPE_CHECKING, Iterable, Optional, Set, Tuple + +from pip._internal.build_env import BuildEnvironment +from pip._internal.distributions.base import AbstractDistribution +from pip._internal.exceptions import InstallationError +from pip._internal.metadata import BaseDistribution +from pip._internal.utils.subprocess import runner_with_spinner_message + +if TYPE_CHECKING: + from pip._internal.index.package_finder import PackageFinder + +logger = logging.getLogger(__name__) + + +class SourceDistribution(AbstractDistribution): + """Represents a source distribution. + + The preparation step for these needs metadata for the packages to be + generated, either using PEP 517 or using the legacy `setup.py egg_info`. + """ + + @property + def build_tracker_id(self) -> Optional[str]: + """Identify this requirement uniquely by its link.""" + assert self.req.link + return self.req.link.url_without_fragment + + def get_metadata_distribution(self) -> BaseDistribution: + return self.req.get_dist() + + def prepare_distribution_metadata( + self, + finder: "PackageFinder", + build_isolation: bool, + check_build_deps: bool, + ) -> None: + # Load pyproject.toml, to determine whether PEP 517 is to be used + self.req.load_pyproject_toml() + + # Set up the build isolation, if this requirement should be isolated + should_isolate = self.req.use_pep517 and build_isolation + if should_isolate: + # Setup an isolated environment and install the build backend static + # requirements in it. + self._prepare_build_backend(finder) + # Check that if the requirement is editable, it either supports PEP 660 or + # has a setup.py or a setup.cfg. This cannot be done earlier because we need + # to setup the build backend to verify it supports build_editable, nor can + # it be done later, because we want to avoid installing build requirements + # needlessly. Doing it here also works around setuptools generating + # UNKNOWN.egg-info when running get_requires_for_build_wheel on a directory + # without setup.py nor setup.cfg. + self.req.isolated_editable_sanity_check() + # Install the dynamic build requirements. + self._install_build_reqs(finder) + # Check if the current environment provides build dependencies + should_check_deps = self.req.use_pep517 and check_build_deps + if should_check_deps: + pyproject_requires = self.req.pyproject_requires + assert pyproject_requires is not None + conflicting, missing = self.req.build_env.check_requirements( + pyproject_requires + ) + if conflicting: + self._raise_conflicts("the backend dependencies", conflicting) + if missing: + self._raise_missing_reqs(missing) + self.req.prepare_metadata() + + def _prepare_build_backend(self, finder: "PackageFinder") -> None: + # Isolate in a BuildEnvironment and install the build-time + # requirements. + pyproject_requires = self.req.pyproject_requires + assert pyproject_requires is not None + + self.req.build_env = BuildEnvironment() + self.req.build_env.install_requirements( + finder, pyproject_requires, "overlay", kind="build dependencies" + ) + conflicting, missing = self.req.build_env.check_requirements( + self.req.requirements_to_check + ) + if conflicting: + self._raise_conflicts("PEP 517/518 supported requirements", conflicting) + if missing: + logger.warning( + "Missing build requirements in pyproject.toml for %s.", + self.req, + ) + logger.warning( + "The project does not specify a build backend, and " + "pip cannot fall back to setuptools without %s.", + " and ".join(map(repr, sorted(missing))), + ) + + def _get_build_requires_wheel(self) -> Iterable[str]: + with self.req.build_env: + runner = runner_with_spinner_message("Getting requirements to build wheel") + backend = self.req.pep517_backend + assert backend is not None + with backend.subprocess_runner(runner): + return backend.get_requires_for_build_wheel() + + def _get_build_requires_editable(self) -> Iterable[str]: + with self.req.build_env: + runner = runner_with_spinner_message( + "Getting requirements to build editable" + ) + backend = self.req.pep517_backend + assert backend is not None + with backend.subprocess_runner(runner): + return backend.get_requires_for_build_editable() + + def _install_build_reqs(self, finder: "PackageFinder") -> None: + # Install any extra build dependencies that the backend requests. + # This must be done in a second pass, as the pyproject.toml + # dependencies must be installed before we can call the backend. + if ( + self.req.editable + and self.req.permit_editable_wheels + and self.req.supports_pyproject_editable + ): + build_reqs = self._get_build_requires_editable() + else: + build_reqs = self._get_build_requires_wheel() + conflicting, missing = self.req.build_env.check_requirements(build_reqs) + if conflicting: + self._raise_conflicts("the backend dependencies", conflicting) + self.req.build_env.install_requirements( + finder, missing, "normal", kind="backend dependencies" + ) + + def _raise_conflicts( + self, conflicting_with: str, conflicting_reqs: Set[Tuple[str, str]] + ) -> None: + format_string = ( + "Some build dependencies for {requirement} " + "conflict with {conflicting_with}: {description}." + ) + error_message = format_string.format( + requirement=self.req, + conflicting_with=conflicting_with, + description=", ".join( + f"{installed} is incompatible with {wanted}" + for installed, wanted in sorted(conflicting_reqs) + ), + ) + raise InstallationError(error_message) + + def _raise_missing_reqs(self, missing: Set[str]) -> None: + format_string = ( + "Some build dependencies for {requirement} are missing: {missing}." + ) + error_message = format_string.format( + requirement=self.req, missing=", ".join(map(repr, sorted(missing))) + ) + raise InstallationError(error_message) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/wheel.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..bfadd39dcb77dfdaa2cca24e8a6db7e5beac181e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/distributions/wheel.py @@ -0,0 +1,42 @@ +from typing import TYPE_CHECKING, Optional + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.distributions.base import AbstractDistribution +from pip._internal.metadata import ( + BaseDistribution, + FilesystemWheel, + get_wheel_distribution, +) + +if TYPE_CHECKING: + from pip._internal.index.package_finder import PackageFinder + + +class WheelDistribution(AbstractDistribution): + """Represents a wheel distribution. + + This does not need any preparation as wheels can be directly unpacked. + """ + + @property + def build_tracker_id(self) -> Optional[str]: + return None + + def get_metadata_distribution(self) -> BaseDistribution: + """Loads the metadata from the wheel file into memory and returns a + Distribution that uses it, not relying on the wheel file or + requirement. + """ + assert self.req.local_file_path, "Set as part of preparation during download" + assert self.req.name, "Wheels are never unnamed" + wheel = FilesystemWheel(self.req.local_file_path) + return get_wheel_distribution(wheel, canonicalize_name(self.req.name)) + + def prepare_distribution_metadata( + self, + finder: "PackageFinder", + build_isolation: bool, + check_build_deps: bool, + ) -> None: + pass diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/exceptions.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..45a876a850dfec2295ea982e1eadd5ab26364cd4 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/exceptions.py @@ -0,0 +1,809 @@ +"""Exceptions used throughout package. + +This module MUST NOT try to import from anything within `pip._internal` to +operate. This is expected to be importable from any/all files within the +subpackage and, thus, should not depend on them. +""" + +import configparser +import contextlib +import locale +import logging +import pathlib +import re +import sys +from itertools import chain, groupby, repeat +from typing import TYPE_CHECKING, Dict, Iterator, List, Literal, Optional, Union + +from pip._vendor.packaging.requirements import InvalidRequirement +from pip._vendor.packaging.version import InvalidVersion +from pip._vendor.rich.console import Console, ConsoleOptions, RenderResult +from pip._vendor.rich.markup import escape +from pip._vendor.rich.text import Text + +if TYPE_CHECKING: + from hashlib import _Hash + + from pip._vendor.requests.models import Request, Response + + from pip._internal.metadata import BaseDistribution + from pip._internal.req.req_install import InstallRequirement + +logger = logging.getLogger(__name__) + + +# +# Scaffolding +# +def _is_kebab_case(s: str) -> bool: + return re.match(r"^[a-z]+(-[a-z]+)*$", s) is not None + + +def _prefix_with_indent( + s: Union[Text, str], + console: Console, + *, + prefix: str, + indent: str, +) -> Text: + if isinstance(s, Text): + text = s + else: + text = console.render_str(s) + + return console.render_str(prefix, overflow="ignore") + console.render_str( + f"\n{indent}", overflow="ignore" + ).join(text.split(allow_blank=True)) + + +class PipError(Exception): + """The base pip error.""" + + +class DiagnosticPipError(PipError): + """An error, that presents diagnostic information to the user. + + This contains a bunch of logic, to enable pretty presentation of our error + messages. Each error gets a unique reference. Each error can also include + additional context, a hint and/or a note -- which are presented with the + main error message in a consistent style. + + This is adapted from the error output styling in `sphinx-theme-builder`. + """ + + reference: str + + def __init__( + self, + *, + kind: 'Literal["error", "warning"]' = "error", + reference: Optional[str] = None, + message: Union[str, Text], + context: Optional[Union[str, Text]], + hint_stmt: Optional[Union[str, Text]], + note_stmt: Optional[Union[str, Text]] = None, + link: Optional[str] = None, + ) -> None: + # Ensure a proper reference is provided. + if reference is None: + assert hasattr(self, "reference"), "error reference not provided!" + reference = self.reference + assert _is_kebab_case(reference), "error reference must be kebab-case!" + + self.kind = kind + self.reference = reference + + self.message = message + self.context = context + + self.note_stmt = note_stmt + self.hint_stmt = hint_stmt + + self.link = link + + super().__init__(f"<{self.__class__.__name__}: {self.reference}>") + + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__}(" + f"reference={self.reference!r}, " + f"message={self.message!r}, " + f"context={self.context!r}, " + f"note_stmt={self.note_stmt!r}, " + f"hint_stmt={self.hint_stmt!r}" + ")>" + ) + + def __rich_console__( + self, + console: Console, + options: ConsoleOptions, + ) -> RenderResult: + colour = "red" if self.kind == "error" else "yellow" + + yield f"[{colour} bold]{self.kind}[/]: [bold]{self.reference}[/]" + yield "" + + if not options.ascii_only: + # Present the main message, with relevant context indented. + if self.context is not None: + yield _prefix_with_indent( + self.message, + console, + prefix=f"[{colour}]×[/] ", + indent=f"[{colour}]│[/] ", + ) + yield _prefix_with_indent( + self.context, + console, + prefix=f"[{colour}]╰─>[/] ", + indent=f"[{colour}] [/] ", + ) + else: + yield _prefix_with_indent( + self.message, + console, + prefix="[red]×[/] ", + indent=" ", + ) + else: + yield self.message + if self.context is not None: + yield "" + yield self.context + + if self.note_stmt is not None or self.hint_stmt is not None: + yield "" + + if self.note_stmt is not None: + yield _prefix_with_indent( + self.note_stmt, + console, + prefix="[magenta bold]note[/]: ", + indent=" ", + ) + if self.hint_stmt is not None: + yield _prefix_with_indent( + self.hint_stmt, + console, + prefix="[cyan bold]hint[/]: ", + indent=" ", + ) + + if self.link is not None: + yield "" + yield f"Link: {self.link}" + + +# +# Actual Errors +# +class ConfigurationError(PipError): + """General exception in configuration""" + + +class InstallationError(PipError): + """General exception during installation""" + + +class MissingPyProjectBuildRequires(DiagnosticPipError): + """Raised when pyproject.toml has `build-system`, but no `build-system.requires`.""" + + reference = "missing-pyproject-build-system-requires" + + def __init__(self, *, package: str) -> None: + super().__init__( + message=f"Can not process {escape(package)}", + context=Text( + "This package has an invalid pyproject.toml file.\n" + "The [build-system] table is missing the mandatory `requires` key." + ), + note_stmt="This is an issue with the package mentioned above, not pip.", + hint_stmt=Text("See PEP 518 for the detailed specification."), + ) + + +class InvalidPyProjectBuildRequires(DiagnosticPipError): + """Raised when pyproject.toml an invalid `build-system.requires`.""" + + reference = "invalid-pyproject-build-system-requires" + + def __init__(self, *, package: str, reason: str) -> None: + super().__init__( + message=f"Can not process {escape(package)}", + context=Text( + "This package has an invalid `build-system.requires` key in " + f"pyproject.toml.\n{reason}" + ), + note_stmt="This is an issue with the package mentioned above, not pip.", + hint_stmt=Text("See PEP 518 for the detailed specification."), + ) + + +class NoneMetadataError(PipError): + """Raised when accessing a Distribution's "METADATA" or "PKG-INFO". + + This signifies an inconsistency, when the Distribution claims to have + the metadata file (if not, raise ``FileNotFoundError`` instead), but is + not actually able to produce its content. This may be due to permission + errors. + """ + + def __init__( + self, + dist: "BaseDistribution", + metadata_name: str, + ) -> None: + """ + :param dist: A Distribution object. + :param metadata_name: The name of the metadata being accessed + (can be "METADATA" or "PKG-INFO"). + """ + self.dist = dist + self.metadata_name = metadata_name + + def __str__(self) -> str: + # Use `dist` in the error message because its stringification + # includes more information, like the version and location. + return f"None {self.metadata_name} metadata found for distribution: {self.dist}" + + +class UserInstallationInvalid(InstallationError): + """A --user install is requested on an environment without user site.""" + + def __str__(self) -> str: + return "User base directory is not specified" + + +class InvalidSchemeCombination(InstallationError): + def __str__(self) -> str: + before = ", ".join(str(a) for a in self.args[:-1]) + return f"Cannot set {before} and {self.args[-1]} together" + + +class DistributionNotFound(InstallationError): + """Raised when a distribution cannot be found to satisfy a requirement""" + + +class RequirementsFileParseError(InstallationError): + """Raised when a general error occurs parsing a requirements file line.""" + + +class BestVersionAlreadyInstalled(PipError): + """Raised when the most up-to-date version of a package is already + installed.""" + + +class BadCommand(PipError): + """Raised when virtualenv or a command is not found""" + + +class CommandError(PipError): + """Raised when there is an error in command-line arguments""" + + +class PreviousBuildDirError(PipError): + """Raised when there's a previous conflicting build directory""" + + +class NetworkConnectionError(PipError): + """HTTP connection error""" + + def __init__( + self, + error_msg: str, + response: Optional["Response"] = None, + request: Optional["Request"] = None, + ) -> None: + """ + Initialize NetworkConnectionError with `request` and `response` + objects. + """ + self.response = response + self.request = request + self.error_msg = error_msg + if ( + self.response is not None + and not self.request + and hasattr(response, "request") + ): + self.request = self.response.request + super().__init__(error_msg, response, request) + + def __str__(self) -> str: + return str(self.error_msg) + + +class InvalidWheelFilename(InstallationError): + """Invalid wheel filename.""" + + +class UnsupportedWheel(InstallationError): + """Unsupported wheel.""" + + +class InvalidWheel(InstallationError): + """Invalid (e.g. corrupt) wheel.""" + + def __init__(self, location: str, name: str): + self.location = location + self.name = name + + def __str__(self) -> str: + return f"Wheel '{self.name}' located at {self.location} is invalid." + + +class MetadataInconsistent(InstallationError): + """Built metadata contains inconsistent information. + + This is raised when the metadata contains values (e.g. name and version) + that do not match the information previously obtained from sdist filename, + user-supplied ``#egg=`` value, or an install requirement name. + """ + + def __init__( + self, ireq: "InstallRequirement", field: str, f_val: str, m_val: str + ) -> None: + self.ireq = ireq + self.field = field + self.f_val = f_val + self.m_val = m_val + + def __str__(self) -> str: + return ( + f"Requested {self.ireq} has inconsistent {self.field}: " + f"expected {self.f_val!r}, but metadata has {self.m_val!r}" + ) + + +class MetadataInvalid(InstallationError): + """Metadata is invalid.""" + + def __init__(self, ireq: "InstallRequirement", error: str) -> None: + self.ireq = ireq + self.error = error + + def __str__(self) -> str: + return f"Requested {self.ireq} has invalid metadata: {self.error}" + + +class InstallationSubprocessError(DiagnosticPipError, InstallationError): + """A subprocess call failed.""" + + reference = "subprocess-exited-with-error" + + def __init__( + self, + *, + command_description: str, + exit_code: int, + output_lines: Optional[List[str]], + ) -> None: + if output_lines is None: + output_prompt = Text("See above for output.") + else: + output_prompt = ( + Text.from_markup(f"[red][{len(output_lines)} lines of output][/]\n") + + Text("".join(output_lines)) + + Text.from_markup(R"[red]\[end of output][/]") + ) + + super().__init__( + message=( + f"[green]{escape(command_description)}[/] did not run successfully.\n" + f"exit code: {exit_code}" + ), + context=output_prompt, + hint_stmt=None, + note_stmt=( + "This error originates from a subprocess, and is likely not a " + "problem with pip." + ), + ) + + self.command_description = command_description + self.exit_code = exit_code + + def __str__(self) -> str: + return f"{self.command_description} exited with {self.exit_code}" + + +class MetadataGenerationFailed(InstallationSubprocessError, InstallationError): + reference = "metadata-generation-failed" + + def __init__( + self, + *, + package_details: str, + ) -> None: + super(InstallationSubprocessError, self).__init__( + message="Encountered error while generating package metadata.", + context=escape(package_details), + hint_stmt="See above for details.", + note_stmt="This is an issue with the package mentioned above, not pip.", + ) + + def __str__(self) -> str: + return "metadata generation failed" + + +class HashErrors(InstallationError): + """Multiple HashError instances rolled into one for reporting""" + + def __init__(self) -> None: + self.errors: List[HashError] = [] + + def append(self, error: "HashError") -> None: + self.errors.append(error) + + def __str__(self) -> str: + lines = [] + self.errors.sort(key=lambda e: e.order) + for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__): + lines.append(cls.head) + lines.extend(e.body() for e in errors_of_cls) + if lines: + return "\n".join(lines) + return "" + + def __bool__(self) -> bool: + return bool(self.errors) + + +class HashError(InstallationError): + """ + A failure to verify a package against known-good hashes + + :cvar order: An int sorting hash exception classes by difficulty of + recovery (lower being harder), so the user doesn't bother fretting + about unpinned packages when he has deeper issues, like VCS + dependencies, to deal with. Also keeps error reports in a + deterministic order. + :cvar head: A section heading for display above potentially many + exceptions of this kind + :ivar req: The InstallRequirement that triggered this error. This is + pasted on after the exception is instantiated, because it's not + typically available earlier. + + """ + + req: Optional["InstallRequirement"] = None + head = "" + order: int = -1 + + def body(self) -> str: + """Return a summary of me for display under the heading. + + This default implementation simply prints a description of the + triggering requirement. + + :param req: The InstallRequirement that provoked this error, with + its link already populated by the resolver's _populate_link(). + + """ + return f" {self._requirement_name()}" + + def __str__(self) -> str: + return f"{self.head}\n{self.body()}" + + def _requirement_name(self) -> str: + """Return a description of the requirement that triggered me. + + This default implementation returns long description of the req, with + line numbers + + """ + return str(self.req) if self.req else "unknown package" + + +class VcsHashUnsupported(HashError): + """A hash was provided for a version-control-system-based requirement, but + we don't have a method for hashing those.""" + + order = 0 + head = ( + "Can't verify hashes for these requirements because we don't " + "have a way to hash version control repositories:" + ) + + +class DirectoryUrlHashUnsupported(HashError): + """A hash was provided for a version-control-system-based requirement, but + we don't have a method for hashing those.""" + + order = 1 + head = ( + "Can't verify hashes for these file:// requirements because they " + "point to directories:" + ) + + +class HashMissing(HashError): + """A hash was needed for a requirement but is absent.""" + + order = 2 + head = ( + "Hashes are required in --require-hashes mode, but they are " + "missing from some requirements. Here is a list of those " + "requirements along with the hashes their downloaded archives " + "actually had. Add lines like these to your requirements files to " + "prevent tampering. (If you did not enable --require-hashes " + "manually, note that it turns on automatically when any package " + "has a hash.)" + ) + + def __init__(self, gotten_hash: str) -> None: + """ + :param gotten_hash: The hash of the (possibly malicious) archive we + just downloaded + """ + self.gotten_hash = gotten_hash + + def body(self) -> str: + # Dodge circular import. + from pip._internal.utils.hashes import FAVORITE_HASH + + package = None + if self.req: + # In the case of URL-based requirements, display the original URL + # seen in the requirements file rather than the package name, + # so the output can be directly copied into the requirements file. + package = ( + self.req.original_link + if self.req.is_direct + # In case someone feeds something downright stupid + # to InstallRequirement's constructor. + else getattr(self.req, "req", None) + ) + return " {} --hash={}:{}".format( + package or "unknown package", FAVORITE_HASH, self.gotten_hash + ) + + +class HashUnpinned(HashError): + """A requirement had a hash specified but was not pinned to a specific + version.""" + + order = 3 + head = ( + "In --require-hashes mode, all requirements must have their " + "versions pinned with ==. These do not:" + ) + + +class HashMismatch(HashError): + """ + Distribution file hash values don't match. + + :ivar package_name: The name of the package that triggered the hash + mismatch. Feel free to write to this after the exception is raise to + improve its error message. + + """ + + order = 4 + head = ( + "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS " + "FILE. If you have updated the package versions, please update " + "the hashes. Otherwise, examine the package contents carefully; " + "someone may have tampered with them." + ) + + def __init__(self, allowed: Dict[str, List[str]], gots: Dict[str, "_Hash"]) -> None: + """ + :param allowed: A dict of algorithm names pointing to lists of allowed + hex digests + :param gots: A dict of algorithm names pointing to hashes we + actually got from the files under suspicion + """ + self.allowed = allowed + self.gots = gots + + def body(self) -> str: + return f" {self._requirement_name()}:\n{self._hash_comparison()}" + + def _hash_comparison(self) -> str: + """ + Return a comparison of actual and expected hash values. + + Example:: + + Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde + or 123451234512345123451234512345123451234512345 + Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef + + """ + + def hash_then_or(hash_name: str) -> "chain[str]": + # For now, all the decent hashes have 6-char names, so we can get + # away with hard-coding space literals. + return chain([hash_name], repeat(" or")) + + lines: List[str] = [] + for hash_name, expecteds in self.allowed.items(): + prefix = hash_then_or(hash_name) + lines.extend((f" Expected {next(prefix)} {e}") for e in expecteds) + lines.append( + f" Got {self.gots[hash_name].hexdigest()}\n" + ) + return "\n".join(lines) + + +class UnsupportedPythonVersion(InstallationError): + """Unsupported python version according to Requires-Python package + metadata.""" + + +class ConfigurationFileCouldNotBeLoaded(ConfigurationError): + """When there are errors while loading a configuration file""" + + def __init__( + self, + reason: str = "could not be loaded", + fname: Optional[str] = None, + error: Optional[configparser.Error] = None, + ) -> None: + super().__init__(error) + self.reason = reason + self.fname = fname + self.error = error + + def __str__(self) -> str: + if self.fname is not None: + message_part = f" in {self.fname}." + else: + assert self.error is not None + message_part = f".\n{self.error}\n" + return f"Configuration file {self.reason}{message_part}" + + +_DEFAULT_EXTERNALLY_MANAGED_ERROR = f"""\ +The Python environment under {sys.prefix} is managed externally, and may not be +manipulated by the user. Please use specific tooling from the distributor of +the Python installation to interact with this environment instead. +""" + + +class ExternallyManagedEnvironment(DiagnosticPipError): + """The current environment is externally managed. + + This is raised when the current environment is externally managed, as + defined by `PEP 668`_. The ``EXTERNALLY-MANAGED`` configuration is checked + and displayed when the error is bubbled up to the user. + + :param error: The error message read from ``EXTERNALLY-MANAGED``. + """ + + reference = "externally-managed-environment" + + def __init__(self, error: Optional[str]) -> None: + if error is None: + context = Text(_DEFAULT_EXTERNALLY_MANAGED_ERROR) + else: + context = Text(error) + super().__init__( + message="This environment is externally managed", + context=context, + note_stmt=( + "If you believe this is a mistake, please contact your " + "Python installation or OS distribution provider. " + "You can override this, at the risk of breaking your Python " + "installation or OS, by passing --break-system-packages." + ), + hint_stmt=Text("See PEP 668 for the detailed specification."), + ) + + @staticmethod + def _iter_externally_managed_error_keys() -> Iterator[str]: + # LC_MESSAGES is in POSIX, but not the C standard. The most common + # platform that does not implement this category is Windows, where + # using other categories for console message localization is equally + # unreliable, so we fall back to the locale-less vendor message. This + # can always be re-evaluated when a vendor proposes a new alternative. + try: + category = locale.LC_MESSAGES + except AttributeError: + lang: Optional[str] = None + else: + lang, _ = locale.getlocale(category) + if lang is not None: + yield f"Error-{lang}" + for sep in ("-", "_"): + before, found, _ = lang.partition(sep) + if not found: + continue + yield f"Error-{before}" + yield "Error" + + @classmethod + def from_config( + cls, + config: Union[pathlib.Path, str], + ) -> "ExternallyManagedEnvironment": + parser = configparser.ConfigParser(interpolation=None) + try: + parser.read(config, encoding="utf-8") + section = parser["externally-managed"] + for key in cls._iter_externally_managed_error_keys(): + with contextlib.suppress(KeyError): + return cls(section[key]) + except KeyError: + pass + except (OSError, UnicodeDecodeError, configparser.ParsingError): + from pip._internal.utils._log import VERBOSE + + exc_info = logger.isEnabledFor(VERBOSE) + logger.warning("Failed to read %s", config, exc_info=exc_info) + return cls(None) + + +class UninstallMissingRecord(DiagnosticPipError): + reference = "uninstall-no-record-file" + + def __init__(self, *, distribution: "BaseDistribution") -> None: + installer = distribution.installer + if not installer or installer == "pip": + dep = f"{distribution.raw_name}=={distribution.version}" + hint = Text.assemble( + "You might be able to recover from this via: ", + (f"pip install --force-reinstall --no-deps {dep}", "green"), + ) + else: + hint = Text( + f"The package was installed by {installer}. " + "You should check if it can uninstall the package." + ) + + super().__init__( + message=Text(f"Cannot uninstall {distribution}"), + context=( + "The package's contents are unknown: " + f"no RECORD file was found for {distribution.raw_name}." + ), + hint_stmt=hint, + ) + + +class LegacyDistutilsInstall(DiagnosticPipError): + reference = "uninstall-distutils-installed-package" + + def __init__(self, *, distribution: "BaseDistribution") -> None: + super().__init__( + message=Text(f"Cannot uninstall {distribution}"), + context=( + "It is a distutils installed project and thus we cannot accurately " + "determine which files belong to it which would lead to only a partial " + "uninstall." + ), + hint_stmt=None, + ) + + +class InvalidInstalledPackage(DiagnosticPipError): + reference = "invalid-installed-package" + + def __init__( + self, + *, + dist: "BaseDistribution", + invalid_exc: Union[InvalidRequirement, InvalidVersion], + ) -> None: + installed_location = dist.installed_location + + if isinstance(invalid_exc, InvalidRequirement): + invalid_type = "requirement" + else: + invalid_type = "version" + + super().__init__( + message=Text( + f"Cannot process installed package {dist} " + + (f"in {installed_location!r} " if installed_location else "") + + f"because it has an invalid {invalid_type}:\n{invalid_exc.args[0]}" + ), + context=( + "Starting with pip 24.1, packages with invalid " + f"{invalid_type}s can not be processed." + ), + hint_stmt="To proceed this package must be uninstalled.", + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a17b7b3b6ad49157ee41f3da304fec3d32342d3 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__init__.py @@ -0,0 +1,2 @@ +"""Index interaction code +""" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b0d3b4f2ad700649b9634f87c6489af113f6770 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/collector.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/collector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39f3a9ca3e5dd544916acf8432693225c0d1374b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/collector.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..380467bba1a60dfd296b806ac9281644460c52dc Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/sources.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/sources.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a28c711a38c48b48e2554954793d6567baaed42 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/__pycache__/sources.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/collector.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/collector.py new file mode 100644 index 0000000000000000000000000000000000000000..5f8fdee3d46271652d498cbfc865a25c50f2cab0 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/collector.py @@ -0,0 +1,494 @@ +""" +The main purpose of this module is to expose LinkCollector.collect_sources(). +""" + +import collections +import email.message +import functools +import itertools +import json +import logging +import os +import urllib.parse +import urllib.request +from dataclasses import dataclass +from html.parser import HTMLParser +from optparse import Values +from typing import ( + Callable, + Dict, + Iterable, + List, + MutableMapping, + NamedTuple, + Optional, + Protocol, + Sequence, + Tuple, + Union, +) + +from pip._vendor import requests +from pip._vendor.requests import Response +from pip._vendor.requests.exceptions import RetryError, SSLError + +from pip._internal.exceptions import NetworkConnectionError +from pip._internal.models.link import Link +from pip._internal.models.search_scope import SearchScope +from pip._internal.network.session import PipSession +from pip._internal.network.utils import raise_for_status +from pip._internal.utils.filetypes import is_archive_file +from pip._internal.utils.misc import redact_auth_from_url +from pip._internal.vcs import vcs + +from .sources import CandidatesFromPage, LinkSource, build_source + +logger = logging.getLogger(__name__) + +ResponseHeaders = MutableMapping[str, str] + + +def _match_vcs_scheme(url: str) -> Optional[str]: + """Look for VCS schemes in the URL. + + Returns the matched VCS scheme, or None if there's no match. + """ + for scheme in vcs.schemes: + if url.lower().startswith(scheme) and url[len(scheme)] in "+:": + return scheme + return None + + +class _NotAPIContent(Exception): + def __init__(self, content_type: str, request_desc: str) -> None: + super().__init__(content_type, request_desc) + self.content_type = content_type + self.request_desc = request_desc + + +def _ensure_api_header(response: Response) -> None: + """ + Check the Content-Type header to ensure the response contains a Simple + API Response. + + Raises `_NotAPIContent` if the content type is not a valid content-type. + """ + content_type = response.headers.get("Content-Type", "Unknown") + + content_type_l = content_type.lower() + if content_type_l.startswith( + ( + "text/html", + "application/vnd.pypi.simple.v1+html", + "application/vnd.pypi.simple.v1+json", + ) + ): + return + + raise _NotAPIContent(content_type, response.request.method) + + +class _NotHTTP(Exception): + pass + + +def _ensure_api_response(url: str, session: PipSession) -> None: + """ + Send a HEAD request to the URL, and ensure the response contains a simple + API Response. + + Raises `_NotHTTP` if the URL is not available for a HEAD request, or + `_NotAPIContent` if the content type is not a valid content type. + """ + scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url) + if scheme not in {"http", "https"}: + raise _NotHTTP() + + resp = session.head(url, allow_redirects=True) + raise_for_status(resp) + + _ensure_api_header(resp) + + +def _get_simple_response(url: str, session: PipSession) -> Response: + """Access an Simple API response with GET, and return the response. + + This consists of three parts: + + 1. If the URL looks suspiciously like an archive, send a HEAD first to + check the Content-Type is HTML or Simple API, to avoid downloading a + large file. Raise `_NotHTTP` if the content type cannot be determined, or + `_NotAPIContent` if it is not HTML or a Simple API. + 2. Actually perform the request. Raise HTTP exceptions on network failures. + 3. Check the Content-Type header to make sure we got a Simple API response, + and raise `_NotAPIContent` otherwise. + """ + if is_archive_file(Link(url).filename): + _ensure_api_response(url, session=session) + + logger.debug("Getting page %s", redact_auth_from_url(url)) + + resp = session.get( + url, + headers={ + "Accept": ", ".join( + [ + "application/vnd.pypi.simple.v1+json", + "application/vnd.pypi.simple.v1+html; q=0.1", + "text/html; q=0.01", + ] + ), + # We don't want to blindly returned cached data for + # /simple/, because authors generally expecting that + # twine upload && pip install will function, but if + # they've done a pip install in the last ~10 minutes + # it won't. Thus by setting this to zero we will not + # blindly use any cached data, however the benefit of + # using max-age=0 instead of no-cache, is that we will + # still support conditional requests, so we will still + # minimize traffic sent in cases where the page hasn't + # changed at all, we will just always incur the round + # trip for the conditional GET now instead of only + # once per 10 minutes. + # For more information, please see pypa/pip#5670. + "Cache-Control": "max-age=0", + }, + ) + raise_for_status(resp) + + # The check for archives above only works if the url ends with + # something that looks like an archive. However that is not a + # requirement of an url. Unless we issue a HEAD request on every + # url we cannot know ahead of time for sure if something is a + # Simple API response or not. However we can check after we've + # downloaded it. + _ensure_api_header(resp) + + logger.debug( + "Fetched page %s as %s", + redact_auth_from_url(url), + resp.headers.get("Content-Type", "Unknown"), + ) + + return resp + + +def _get_encoding_from_headers(headers: ResponseHeaders) -> Optional[str]: + """Determine if we have any encoding information in our headers.""" + if headers and "Content-Type" in headers: + m = email.message.Message() + m["content-type"] = headers["Content-Type"] + charset = m.get_param("charset") + if charset: + return str(charset) + return None + + +class CacheablePageContent: + def __init__(self, page: "IndexContent") -> None: + assert page.cache_link_parsing + self.page = page + + def __eq__(self, other: object) -> bool: + return isinstance(other, type(self)) and self.page.url == other.page.url + + def __hash__(self) -> int: + return hash(self.page.url) + + +class ParseLinks(Protocol): + def __call__(self, page: "IndexContent") -> Iterable[Link]: ... + + +def with_cached_index_content(fn: ParseLinks) -> ParseLinks: + """ + Given a function that parses an Iterable[Link] from an IndexContent, cache the + function's result (keyed by CacheablePageContent), unless the IndexContent + `page` has `page.cache_link_parsing == False`. + """ + + @functools.lru_cache(maxsize=None) + def wrapper(cacheable_page: CacheablePageContent) -> List[Link]: + return list(fn(cacheable_page.page)) + + @functools.wraps(fn) + def wrapper_wrapper(page: "IndexContent") -> List[Link]: + if page.cache_link_parsing: + return wrapper(CacheablePageContent(page)) + return list(fn(page)) + + return wrapper_wrapper + + +@with_cached_index_content +def parse_links(page: "IndexContent") -> Iterable[Link]: + """ + Parse a Simple API's Index Content, and yield its anchor elements as Link objects. + """ + + content_type_l = page.content_type.lower() + if content_type_l.startswith("application/vnd.pypi.simple.v1+json"): + data = json.loads(page.content) + for file in data.get("files", []): + link = Link.from_json(file, page.url) + if link is None: + continue + yield link + return + + parser = HTMLLinkParser(page.url) + encoding = page.encoding or "utf-8" + parser.feed(page.content.decode(encoding)) + + url = page.url + base_url = parser.base_url or url + for anchor in parser.anchors: + link = Link.from_element(anchor, page_url=url, base_url=base_url) + if link is None: + continue + yield link + + +@dataclass(frozen=True) +class IndexContent: + """Represents one response (or page), along with its URL. + + :param encoding: the encoding to decode the given content. + :param url: the URL from which the HTML was downloaded. + :param cache_link_parsing: whether links parsed from this page's url + should be cached. PyPI index urls should + have this set to False, for example. + """ + + content: bytes + content_type: str + encoding: Optional[str] + url: str + cache_link_parsing: bool = True + + def __str__(self) -> str: + return redact_auth_from_url(self.url) + + +class HTMLLinkParser(HTMLParser): + """ + HTMLParser that keeps the first base HREF and a list of all anchor + elements' attributes. + """ + + def __init__(self, url: str) -> None: + super().__init__(convert_charrefs=True) + + self.url: str = url + self.base_url: Optional[str] = None + self.anchors: List[Dict[str, Optional[str]]] = [] + + def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None: + if tag == "base" and self.base_url is None: + href = self.get_href(attrs) + if href is not None: + self.base_url = href + elif tag == "a": + self.anchors.append(dict(attrs)) + + def get_href(self, attrs: List[Tuple[str, Optional[str]]]) -> Optional[str]: + for name, value in attrs: + if name == "href": + return value + return None + + +def _handle_get_simple_fail( + link: Link, + reason: Union[str, Exception], + meth: Optional[Callable[..., None]] = None, +) -> None: + if meth is None: + meth = logger.debug + meth("Could not fetch URL %s: %s - skipping", link, reason) + + +def _make_index_content( + response: Response, cache_link_parsing: bool = True +) -> IndexContent: + encoding = _get_encoding_from_headers(response.headers) + return IndexContent( + response.content, + response.headers["Content-Type"], + encoding=encoding, + url=response.url, + cache_link_parsing=cache_link_parsing, + ) + + +def _get_index_content(link: Link, *, session: PipSession) -> Optional["IndexContent"]: + url = link.url.split("#", 1)[0] + + # Check for VCS schemes that do not support lookup as web pages. + vcs_scheme = _match_vcs_scheme(url) + if vcs_scheme: + logger.warning( + "Cannot look at %s URL %s because it does not support lookup as web pages.", + vcs_scheme, + link, + ) + return None + + # Tack index.html onto file:// URLs that point to directories + scheme, _, path, _, _, _ = urllib.parse.urlparse(url) + if scheme == "file" and os.path.isdir(urllib.request.url2pathname(path)): + # add trailing slash if not present so urljoin doesn't trim + # final segment + if not url.endswith("/"): + url += "/" + # TODO: In the future, it would be nice if pip supported PEP 691 + # style responses in the file:// URLs, however there's no + # standard file extension for application/vnd.pypi.simple.v1+json + # so we'll need to come up with something on our own. + url = urllib.parse.urljoin(url, "index.html") + logger.debug(" file: URL is directory, getting %s", url) + + try: + resp = _get_simple_response(url, session=session) + except _NotHTTP: + logger.warning( + "Skipping page %s because it looks like an archive, and cannot " + "be checked by a HTTP HEAD request.", + link, + ) + except _NotAPIContent as exc: + logger.warning( + "Skipping page %s because the %s request got Content-Type: %s. " + "The only supported Content-Types are application/vnd.pypi.simple.v1+json, " + "application/vnd.pypi.simple.v1+html, and text/html", + link, + exc.request_desc, + exc.content_type, + ) + except NetworkConnectionError as exc: + _handle_get_simple_fail(link, exc) + except RetryError as exc: + _handle_get_simple_fail(link, exc) + except SSLError as exc: + reason = "There was a problem confirming the ssl certificate: " + reason += str(exc) + _handle_get_simple_fail(link, reason, meth=logger.info) + except requests.ConnectionError as exc: + _handle_get_simple_fail(link, f"connection error: {exc}") + except requests.Timeout: + _handle_get_simple_fail(link, "timed out") + else: + return _make_index_content(resp, cache_link_parsing=link.cache_link_parsing) + return None + + +class CollectedSources(NamedTuple): + find_links: Sequence[Optional[LinkSource]] + index_urls: Sequence[Optional[LinkSource]] + + +class LinkCollector: + """ + Responsible for collecting Link objects from all configured locations, + making network requests as needed. + + The class's main method is its collect_sources() method. + """ + + def __init__( + self, + session: PipSession, + search_scope: SearchScope, + ) -> None: + self.search_scope = search_scope + self.session = session + + @classmethod + def create( + cls, + session: PipSession, + options: Values, + suppress_no_index: bool = False, + ) -> "LinkCollector": + """ + :param session: The Session to use to make requests. + :param suppress_no_index: Whether to ignore the --no-index option + when constructing the SearchScope object. + """ + index_urls = [options.index_url] + options.extra_index_urls + if options.no_index and not suppress_no_index: + logger.debug( + "Ignoring indexes: %s", + ",".join(redact_auth_from_url(url) for url in index_urls), + ) + index_urls = [] + + # Make sure find_links is a list before passing to create(). + find_links = options.find_links or [] + + search_scope = SearchScope.create( + find_links=find_links, + index_urls=index_urls, + no_index=options.no_index, + ) + link_collector = LinkCollector( + session=session, + search_scope=search_scope, + ) + return link_collector + + @property + def find_links(self) -> List[str]: + return self.search_scope.find_links + + def fetch_response(self, location: Link) -> Optional[IndexContent]: + """ + Fetch an HTML page containing package links. + """ + return _get_index_content(location, session=self.session) + + def collect_sources( + self, + project_name: str, + candidates_from_page: CandidatesFromPage, + ) -> CollectedSources: + # The OrderedDict calls deduplicate sources by URL. + index_url_sources = collections.OrderedDict( + build_source( + loc, + candidates_from_page=candidates_from_page, + page_validator=self.session.is_secure_origin, + expand_dir=False, + cache_link_parsing=False, + project_name=project_name, + ) + for loc in self.search_scope.get_index_urls_locations(project_name) + ).values() + find_links_sources = collections.OrderedDict( + build_source( + loc, + candidates_from_page=candidates_from_page, + page_validator=self.session.is_secure_origin, + expand_dir=True, + cache_link_parsing=True, + project_name=project_name, + ) + for loc in self.find_links + ).values() + + if logger.isEnabledFor(logging.DEBUG): + lines = [ + f"* {s.link}" + for s in itertools.chain(find_links_sources, index_url_sources) + if s is not None and s.link is not None + ] + lines = [ + f"{len(lines)} location(s) to search " + f"for versions of {project_name}:" + ] + lines + logger.debug("\n".join(lines)) + + return CollectedSources( + find_links=list(find_links_sources), + index_urls=list(index_url_sources), + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/package_finder.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/package_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..85628ee5d7a791b4fc9e3a59cd0d8b7659c8ef89 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/package_finder.py @@ -0,0 +1,1029 @@ +"""Routines related to PyPI, indexes""" + +import enum +import functools +import itertools +import logging +import re +from dataclasses import dataclass +from typing import TYPE_CHECKING, FrozenSet, Iterable, List, Optional, Set, Tuple, Union + +from pip._vendor.packaging import specifiers +from pip._vendor.packaging.tags import Tag +from pip._vendor.packaging.utils import canonicalize_name +from pip._vendor.packaging.version import InvalidVersion, _BaseVersion +from pip._vendor.packaging.version import parse as parse_version + +from pip._internal.exceptions import ( + BestVersionAlreadyInstalled, + DistributionNotFound, + InvalidWheelFilename, + UnsupportedWheel, +) +from pip._internal.index.collector import LinkCollector, parse_links +from pip._internal.models.candidate import InstallationCandidate +from pip._internal.models.format_control import FormatControl +from pip._internal.models.link import Link +from pip._internal.models.search_scope import SearchScope +from pip._internal.models.selection_prefs import SelectionPreferences +from pip._internal.models.target_python import TargetPython +from pip._internal.models.wheel import Wheel +from pip._internal.req import InstallRequirement +from pip._internal.utils._log import getLogger +from pip._internal.utils.filetypes import WHEEL_EXTENSION +from pip._internal.utils.hashes import Hashes +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import build_netloc +from pip._internal.utils.packaging import check_requires_python +from pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS + +if TYPE_CHECKING: + from pip._vendor.typing_extensions import TypeGuard + +__all__ = ["FormatControl", "BestCandidateResult", "PackageFinder"] + + +logger = getLogger(__name__) + +BuildTag = Union[Tuple[()], Tuple[int, str]] +CandidateSortingKey = Tuple[int, int, int, _BaseVersion, Optional[int], BuildTag] + + +def _check_link_requires_python( + link: Link, + version_info: Tuple[int, int, int], + ignore_requires_python: bool = False, +) -> bool: + """ + Return whether the given Python version is compatible with a link's + "Requires-Python" value. + + :param version_info: A 3-tuple of ints representing the Python + major-minor-micro version to check. + :param ignore_requires_python: Whether to ignore the "Requires-Python" + value if the given Python version isn't compatible. + """ + try: + is_compatible = check_requires_python( + link.requires_python, + version_info=version_info, + ) + except specifiers.InvalidSpecifier: + logger.debug( + "Ignoring invalid Requires-Python (%r) for link: %s", + link.requires_python, + link, + ) + else: + if not is_compatible: + version = ".".join(map(str, version_info)) + if not ignore_requires_python: + logger.verbose( + "Link requires a different Python (%s not in: %r): %s", + version, + link.requires_python, + link, + ) + return False + + logger.debug( + "Ignoring failed Requires-Python check (%s not in: %r) for link: %s", + version, + link.requires_python, + link, + ) + + return True + + +class LinkType(enum.Enum): + candidate = enum.auto() + different_project = enum.auto() + yanked = enum.auto() + format_unsupported = enum.auto() + format_invalid = enum.auto() + platform_mismatch = enum.auto() + requires_python_mismatch = enum.auto() + + +class LinkEvaluator: + """ + Responsible for evaluating links for a particular project. + """ + + _py_version_re = re.compile(r"-py([123]\.?[0-9]?)$") + + # Don't include an allow_yanked default value to make sure each call + # site considers whether yanked releases are allowed. This also causes + # that decision to be made explicit in the calling code, which helps + # people when reading the code. + def __init__( + self, + project_name: str, + canonical_name: str, + formats: FrozenSet[str], + target_python: TargetPython, + allow_yanked: bool, + ignore_requires_python: Optional[bool] = None, + ) -> None: + """ + :param project_name: The user supplied package name. + :param canonical_name: The canonical package name. + :param formats: The formats allowed for this package. Should be a set + with 'binary' or 'source' or both in it. + :param target_python: The target Python interpreter to use when + evaluating link compatibility. This is used, for example, to + check wheel compatibility, as well as when checking the Python + version, e.g. the Python version embedded in a link filename + (or egg fragment) and against an HTML link's optional PEP 503 + "data-requires-python" attribute. + :param allow_yanked: Whether files marked as yanked (in the sense + of PEP 592) are permitted to be candidates for install. + :param ignore_requires_python: Whether to ignore incompatible + PEP 503 "data-requires-python" values in HTML links. Defaults + to False. + """ + if ignore_requires_python is None: + ignore_requires_python = False + + self._allow_yanked = allow_yanked + self._canonical_name = canonical_name + self._ignore_requires_python = ignore_requires_python + self._formats = formats + self._target_python = target_python + + self.project_name = project_name + + def evaluate_link(self, link: Link) -> Tuple[LinkType, str]: + """ + Determine whether a link is a candidate for installation. + + :return: A tuple (result, detail), where *result* is an enum + representing whether the evaluation found a candidate, or the reason + why one is not found. If a candidate is found, *detail* will be the + candidate's version string; if one is not found, it contains the + reason the link fails to qualify. + """ + version = None + if link.is_yanked and not self._allow_yanked: + reason = link.yanked_reason or "" + return (LinkType.yanked, f"yanked for reason: {reason}") + + if link.egg_fragment: + egg_info = link.egg_fragment + ext = link.ext + else: + egg_info, ext = link.splitext() + if not ext: + return (LinkType.format_unsupported, "not a file") + if ext not in SUPPORTED_EXTENSIONS: + return ( + LinkType.format_unsupported, + f"unsupported archive format: {ext}", + ) + if "binary" not in self._formats and ext == WHEEL_EXTENSION: + reason = f"No binaries permitted for {self.project_name}" + return (LinkType.format_unsupported, reason) + if "macosx10" in link.path and ext == ".zip": + return (LinkType.format_unsupported, "macosx10 one") + if ext == WHEEL_EXTENSION: + try: + wheel = Wheel(link.filename) + except InvalidWheelFilename: + return ( + LinkType.format_invalid, + "invalid wheel filename", + ) + if canonicalize_name(wheel.name) != self._canonical_name: + reason = f"wrong project name (not {self.project_name})" + return (LinkType.different_project, reason) + + supported_tags = self._target_python.get_unsorted_tags() + if not wheel.supported(supported_tags): + # Include the wheel's tags in the reason string to + # simplify troubleshooting compatibility issues. + file_tags = ", ".join(wheel.get_formatted_file_tags()) + reason = ( + f"none of the wheel's tags ({file_tags}) are compatible " + f"(run pip debug --verbose to show compatible tags)" + ) + return (LinkType.platform_mismatch, reason) + + version = wheel.version + + # This should be up by the self.ok_binary check, but see issue 2700. + if "source" not in self._formats and ext != WHEEL_EXTENSION: + reason = f"No sources permitted for {self.project_name}" + return (LinkType.format_unsupported, reason) + + if not version: + version = _extract_version_from_fragment( + egg_info, + self._canonical_name, + ) + if not version: + reason = f"Missing project version for {self.project_name}" + return (LinkType.format_invalid, reason) + + match = self._py_version_re.search(version) + if match: + version = version[: match.start()] + py_version = match.group(1) + if py_version != self._target_python.py_version: + return ( + LinkType.platform_mismatch, + "Python version is incorrect", + ) + + supports_python = _check_link_requires_python( + link, + version_info=self._target_python.py_version_info, + ignore_requires_python=self._ignore_requires_python, + ) + if not supports_python: + reason = f"{version} Requires-Python {link.requires_python}" + return (LinkType.requires_python_mismatch, reason) + + logger.debug("Found link %s, version: %s", link, version) + + return (LinkType.candidate, version) + + +def filter_unallowed_hashes( + candidates: List[InstallationCandidate], + hashes: Optional[Hashes], + project_name: str, +) -> List[InstallationCandidate]: + """ + Filter out candidates whose hashes aren't allowed, and return a new + list of candidates. + + If at least one candidate has an allowed hash, then all candidates with + either an allowed hash or no hash specified are returned. Otherwise, + the given candidates are returned. + + Including the candidates with no hash specified when there is a match + allows a warning to be logged if there is a more preferred candidate + with no hash specified. Returning all candidates in the case of no + matches lets pip report the hash of the candidate that would otherwise + have been installed (e.g. permitting the user to more easily update + their requirements file with the desired hash). + """ + if not hashes: + logger.debug( + "Given no hashes to check %s links for project %r: " + "discarding no candidates", + len(candidates), + project_name, + ) + # Make sure we're not returning back the given value. + return list(candidates) + + matches_or_no_digest = [] + # Collect the non-matches for logging purposes. + non_matches = [] + match_count = 0 + for candidate in candidates: + link = candidate.link + if not link.has_hash: + pass + elif link.is_hash_allowed(hashes=hashes): + match_count += 1 + else: + non_matches.append(candidate) + continue + + matches_or_no_digest.append(candidate) + + if match_count: + filtered = matches_or_no_digest + else: + # Make sure we're not returning back the given value. + filtered = list(candidates) + + if len(filtered) == len(candidates): + discard_message = "discarding no candidates" + else: + discard_message = "discarding {} non-matches:\n {}".format( + len(non_matches), + "\n ".join(str(candidate.link) for candidate in non_matches), + ) + + logger.debug( + "Checked %s links for project %r against %s hashes " + "(%s matches, %s no digest): %s", + len(candidates), + project_name, + hashes.digest_count, + match_count, + len(matches_or_no_digest) - match_count, + discard_message, + ) + + return filtered + + +@dataclass +class CandidatePreferences: + """ + Encapsulates some of the preferences for filtering and sorting + InstallationCandidate objects. + """ + + prefer_binary: bool = False + allow_all_prereleases: bool = False + + +@dataclass(frozen=True) +class BestCandidateResult: + """A collection of candidates, returned by `PackageFinder.find_best_candidate`. + + This class is only intended to be instantiated by CandidateEvaluator's + `compute_best_candidate()` method. + + :param all_candidates: A sequence of all available candidates found. + :param applicable_candidates: The applicable candidates. + :param best_candidate: The most preferred candidate found, or None + if no applicable candidates were found. + """ + + all_candidates: List[InstallationCandidate] + applicable_candidates: List[InstallationCandidate] + best_candidate: Optional[InstallationCandidate] + + def __post_init__(self) -> None: + assert set(self.applicable_candidates) <= set(self.all_candidates) + + if self.best_candidate is None: + assert not self.applicable_candidates + else: + assert self.best_candidate in self.applicable_candidates + + +class CandidateEvaluator: + """ + Responsible for filtering and sorting candidates for installation based + on what tags are valid. + """ + + @classmethod + def create( + cls, + project_name: str, + target_python: Optional[TargetPython] = None, + prefer_binary: bool = False, + allow_all_prereleases: bool = False, + specifier: Optional[specifiers.BaseSpecifier] = None, + hashes: Optional[Hashes] = None, + ) -> "CandidateEvaluator": + """Create a CandidateEvaluator object. + + :param target_python: The target Python interpreter to use when + checking compatibility. If None (the default), a TargetPython + object will be constructed from the running Python. + :param specifier: An optional object implementing `filter` + (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable + versions. + :param hashes: An optional collection of allowed hashes. + """ + if target_python is None: + target_python = TargetPython() + if specifier is None: + specifier = specifiers.SpecifierSet() + + supported_tags = target_python.get_sorted_tags() + + return cls( + project_name=project_name, + supported_tags=supported_tags, + specifier=specifier, + prefer_binary=prefer_binary, + allow_all_prereleases=allow_all_prereleases, + hashes=hashes, + ) + + def __init__( + self, + project_name: str, + supported_tags: List[Tag], + specifier: specifiers.BaseSpecifier, + prefer_binary: bool = False, + allow_all_prereleases: bool = False, + hashes: Optional[Hashes] = None, + ) -> None: + """ + :param supported_tags: The PEP 425 tags supported by the target + Python in order of preference (most preferred first). + """ + self._allow_all_prereleases = allow_all_prereleases + self._hashes = hashes + self._prefer_binary = prefer_binary + self._project_name = project_name + self._specifier = specifier + self._supported_tags = supported_tags + # Since the index of the tag in the _supported_tags list is used + # as a priority, precompute a map from tag to index/priority to be + # used in wheel.find_most_preferred_tag. + self._wheel_tag_preferences = { + tag: idx for idx, tag in enumerate(supported_tags) + } + + def get_applicable_candidates( + self, + candidates: List[InstallationCandidate], + ) -> List[InstallationCandidate]: + """ + Return the applicable candidates from a list of candidates. + """ + # Using None infers from the specifier instead. + allow_prereleases = self._allow_all_prereleases or None + specifier = self._specifier + + # We turn the version object into a str here because otherwise + # when we're debundled but setuptools isn't, Python will see + # packaging.version.Version and + # pkg_resources._vendor.packaging.version.Version as different + # types. This way we'll use a str as a common data interchange + # format. If we stop using the pkg_resources provided specifier + # and start using our own, we can drop the cast to str(). + candidates_and_versions = [(c, str(c.version)) for c in candidates] + versions = set( + specifier.filter( + (v for _, v in candidates_and_versions), + prereleases=allow_prereleases, + ) + ) + + applicable_candidates = [c for c, v in candidates_and_versions if v in versions] + filtered_applicable_candidates = filter_unallowed_hashes( + candidates=applicable_candidates, + hashes=self._hashes, + project_name=self._project_name, + ) + + return sorted(filtered_applicable_candidates, key=self._sort_key) + + def _sort_key(self, candidate: InstallationCandidate) -> CandidateSortingKey: + """ + Function to pass as the `key` argument to a call to sorted() to sort + InstallationCandidates by preference. + + Returns a tuple such that tuples sorting as greater using Python's + default comparison operator are more preferred. + + The preference is as follows: + + First and foremost, candidates with allowed (matching) hashes are + always preferred over candidates without matching hashes. This is + because e.g. if the only candidate with an allowed hash is yanked, + we still want to use that candidate. + + Second, excepting hash considerations, candidates that have been + yanked (in the sense of PEP 592) are always less preferred than + candidates that haven't been yanked. Then: + + If not finding wheels, they are sorted by version only. + If finding wheels, then the sort order is by version, then: + 1. existing installs + 2. wheels ordered via Wheel.support_index_min(self._supported_tags) + 3. source archives + If prefer_binary was set, then all wheels are sorted above sources. + + Note: it was considered to embed this logic into the Link + comparison operators, but then different sdist links + with the same version, would have to be considered equal + """ + valid_tags = self._supported_tags + support_num = len(valid_tags) + build_tag: BuildTag = () + binary_preference = 0 + link = candidate.link + if link.is_wheel: + # can raise InvalidWheelFilename + wheel = Wheel(link.filename) + try: + pri = -( + wheel.find_most_preferred_tag( + valid_tags, self._wheel_tag_preferences + ) + ) + except ValueError: + raise UnsupportedWheel( + f"{wheel.filename} is not a supported wheel for this platform. It " + "can't be sorted." + ) + if self._prefer_binary: + binary_preference = 1 + if wheel.build_tag is not None: + match = re.match(r"^(\d+)(.*)$", wheel.build_tag) + assert match is not None, "guaranteed by filename validation" + build_tag_groups = match.groups() + build_tag = (int(build_tag_groups[0]), build_tag_groups[1]) + else: # sdist + pri = -(support_num) + has_allowed_hash = int(link.is_hash_allowed(self._hashes)) + yank_value = -1 * int(link.is_yanked) # -1 for yanked. + return ( + has_allowed_hash, + yank_value, + binary_preference, + candidate.version, + pri, + build_tag, + ) + + def sort_best_candidate( + self, + candidates: List[InstallationCandidate], + ) -> Optional[InstallationCandidate]: + """ + Return the best candidate per the instance's sort order, or None if + no candidate is acceptable. + """ + if not candidates: + return None + best_candidate = max(candidates, key=self._sort_key) + return best_candidate + + def compute_best_candidate( + self, + candidates: List[InstallationCandidate], + ) -> BestCandidateResult: + """ + Compute and return a `BestCandidateResult` instance. + """ + applicable_candidates = self.get_applicable_candidates(candidates) + + best_candidate = self.sort_best_candidate(applicable_candidates) + + return BestCandidateResult( + candidates, + applicable_candidates=applicable_candidates, + best_candidate=best_candidate, + ) + + +class PackageFinder: + """This finds packages. + + This is meant to match easy_install's technique for looking for + packages, by reading pages and looking for appropriate links. + """ + + def __init__( + self, + link_collector: LinkCollector, + target_python: TargetPython, + allow_yanked: bool, + format_control: Optional[FormatControl] = None, + candidate_prefs: Optional[CandidatePreferences] = None, + ignore_requires_python: Optional[bool] = None, + ) -> None: + """ + This constructor is primarily meant to be used by the create() class + method and from tests. + + :param format_control: A FormatControl object, used to control + the selection of source packages / binary packages when consulting + the index and links. + :param candidate_prefs: Options to use when creating a + CandidateEvaluator object. + """ + if candidate_prefs is None: + candidate_prefs = CandidatePreferences() + + format_control = format_control or FormatControl(set(), set()) + + self._allow_yanked = allow_yanked + self._candidate_prefs = candidate_prefs + self._ignore_requires_python = ignore_requires_python + self._link_collector = link_collector + self._target_python = target_python + + self.format_control = format_control + + # These are boring links that have already been logged somehow. + self._logged_links: Set[Tuple[Link, LinkType, str]] = set() + + # Don't include an allow_yanked default value to make sure each call + # site considers whether yanked releases are allowed. This also causes + # that decision to be made explicit in the calling code, which helps + # people when reading the code. + @classmethod + def create( + cls, + link_collector: LinkCollector, + selection_prefs: SelectionPreferences, + target_python: Optional[TargetPython] = None, + ) -> "PackageFinder": + """Create a PackageFinder. + + :param selection_prefs: The candidate selection preferences, as a + SelectionPreferences object. + :param target_python: The target Python interpreter to use when + checking compatibility. If None (the default), a TargetPython + object will be constructed from the running Python. + """ + if target_python is None: + target_python = TargetPython() + + candidate_prefs = CandidatePreferences( + prefer_binary=selection_prefs.prefer_binary, + allow_all_prereleases=selection_prefs.allow_all_prereleases, + ) + + return cls( + candidate_prefs=candidate_prefs, + link_collector=link_collector, + target_python=target_python, + allow_yanked=selection_prefs.allow_yanked, + format_control=selection_prefs.format_control, + ignore_requires_python=selection_prefs.ignore_requires_python, + ) + + @property + def target_python(self) -> TargetPython: + return self._target_python + + @property + def search_scope(self) -> SearchScope: + return self._link_collector.search_scope + + @search_scope.setter + def search_scope(self, search_scope: SearchScope) -> None: + self._link_collector.search_scope = search_scope + + @property + def find_links(self) -> List[str]: + return self._link_collector.find_links + + @property + def index_urls(self) -> List[str]: + return self.search_scope.index_urls + + @property + def proxy(self) -> Optional[str]: + return self._link_collector.session.pip_proxy + + @property + def trusted_hosts(self) -> Iterable[str]: + for host_port in self._link_collector.session.pip_trusted_origins: + yield build_netloc(*host_port) + + @property + def custom_cert(self) -> Optional[str]: + # session.verify is either a boolean (use default bundle/no SSL + # verification) or a string path to a custom CA bundle to use. We only + # care about the latter. + verify = self._link_collector.session.verify + return verify if isinstance(verify, str) else None + + @property + def client_cert(self) -> Optional[str]: + cert = self._link_collector.session.cert + assert not isinstance(cert, tuple), "pip only supports PEM client certs" + return cert + + @property + def allow_all_prereleases(self) -> bool: + return self._candidate_prefs.allow_all_prereleases + + def set_allow_all_prereleases(self) -> None: + self._candidate_prefs.allow_all_prereleases = True + + @property + def prefer_binary(self) -> bool: + return self._candidate_prefs.prefer_binary + + def set_prefer_binary(self) -> None: + self._candidate_prefs.prefer_binary = True + + def requires_python_skipped_reasons(self) -> List[str]: + reasons = { + detail + for _, result, detail in self._logged_links + if result == LinkType.requires_python_mismatch + } + return sorted(reasons) + + def make_link_evaluator(self, project_name: str) -> LinkEvaluator: + canonical_name = canonicalize_name(project_name) + formats = self.format_control.get_allowed_formats(canonical_name) + + return LinkEvaluator( + project_name=project_name, + canonical_name=canonical_name, + formats=formats, + target_python=self._target_python, + allow_yanked=self._allow_yanked, + ignore_requires_python=self._ignore_requires_python, + ) + + def _sort_links(self, links: Iterable[Link]) -> List[Link]: + """ + Returns elements of links in order, non-egg links first, egg links + second, while eliminating duplicates + """ + eggs, no_eggs = [], [] + seen: Set[Link] = set() + for link in links: + if link not in seen: + seen.add(link) + if link.egg_fragment: + eggs.append(link) + else: + no_eggs.append(link) + return no_eggs + eggs + + def _log_skipped_link(self, link: Link, result: LinkType, detail: str) -> None: + # This is a hot method so don't waste time hashing links unless we're + # actually going to log 'em. + if not logger.isEnabledFor(logging.DEBUG): + return + + entry = (link, result, detail) + if entry not in self._logged_links: + # Put the link at the end so the reason is more visible and because + # the link string is usually very long. + logger.debug("Skipping link: %s: %s", detail, link) + self._logged_links.add(entry) + + def get_install_candidate( + self, link_evaluator: LinkEvaluator, link: Link + ) -> Optional[InstallationCandidate]: + """ + If the link is a candidate for install, convert it to an + InstallationCandidate and return it. Otherwise, return None. + """ + result, detail = link_evaluator.evaluate_link(link) + if result != LinkType.candidate: + self._log_skipped_link(link, result, detail) + return None + + try: + return InstallationCandidate( + name=link_evaluator.project_name, + link=link, + version=detail, + ) + except InvalidVersion: + return None + + def evaluate_links( + self, link_evaluator: LinkEvaluator, links: Iterable[Link] + ) -> List[InstallationCandidate]: + """ + Convert links that are candidates to InstallationCandidate objects. + """ + candidates = [] + for link in self._sort_links(links): + candidate = self.get_install_candidate(link_evaluator, link) + if candidate is not None: + candidates.append(candidate) + + return candidates + + def process_project_url( + self, project_url: Link, link_evaluator: LinkEvaluator + ) -> List[InstallationCandidate]: + logger.debug( + "Fetching project page and analyzing links: %s", + project_url, + ) + index_response = self._link_collector.fetch_response(project_url) + if index_response is None: + return [] + + page_links = list(parse_links(index_response)) + + with indent_log(): + package_links = self.evaluate_links( + link_evaluator, + links=page_links, + ) + + return package_links + + @functools.lru_cache(maxsize=None) + def find_all_candidates(self, project_name: str) -> List[InstallationCandidate]: + """Find all available InstallationCandidate for project_name + + This checks index_urls and find_links. + All versions found are returned as an InstallationCandidate list. + + See LinkEvaluator.evaluate_link() for details on which files + are accepted. + """ + link_evaluator = self.make_link_evaluator(project_name) + + collected_sources = self._link_collector.collect_sources( + project_name=project_name, + candidates_from_page=functools.partial( + self.process_project_url, + link_evaluator=link_evaluator, + ), + ) + + page_candidates_it = itertools.chain.from_iterable( + source.page_candidates() + for sources in collected_sources + for source in sources + if source is not None + ) + page_candidates = list(page_candidates_it) + + file_links_it = itertools.chain.from_iterable( + source.file_links() + for sources in collected_sources + for source in sources + if source is not None + ) + file_candidates = self.evaluate_links( + link_evaluator, + sorted(file_links_it, reverse=True), + ) + + if logger.isEnabledFor(logging.DEBUG) and file_candidates: + paths = [] + for candidate in file_candidates: + assert candidate.link.url # we need to have a URL + try: + paths.append(candidate.link.file_path) + except Exception: + paths.append(candidate.link.url) # it's not a local file + + logger.debug("Local files found: %s", ", ".join(paths)) + + # This is an intentional priority ordering + return file_candidates + page_candidates + + def make_candidate_evaluator( + self, + project_name: str, + specifier: Optional[specifiers.BaseSpecifier] = None, + hashes: Optional[Hashes] = None, + ) -> CandidateEvaluator: + """Create a CandidateEvaluator object to use.""" + candidate_prefs = self._candidate_prefs + return CandidateEvaluator.create( + project_name=project_name, + target_python=self._target_python, + prefer_binary=candidate_prefs.prefer_binary, + allow_all_prereleases=candidate_prefs.allow_all_prereleases, + specifier=specifier, + hashes=hashes, + ) + + @functools.lru_cache(maxsize=None) + def find_best_candidate( + self, + project_name: str, + specifier: Optional[specifiers.BaseSpecifier] = None, + hashes: Optional[Hashes] = None, + ) -> BestCandidateResult: + """Find matches for the given project and specifier. + + :param specifier: An optional object implementing `filter` + (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable + versions. + + :return: A `BestCandidateResult` instance. + """ + candidates = self.find_all_candidates(project_name) + candidate_evaluator = self.make_candidate_evaluator( + project_name=project_name, + specifier=specifier, + hashes=hashes, + ) + return candidate_evaluator.compute_best_candidate(candidates) + + def find_requirement( + self, req: InstallRequirement, upgrade: bool + ) -> Optional[InstallationCandidate]: + """Try to find a Link matching req + + Expects req, an InstallRequirement and upgrade, a boolean + Returns a InstallationCandidate if found, + Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise + """ + hashes = req.hashes(trust_internet=False) + best_candidate_result = self.find_best_candidate( + req.name, + specifier=req.specifier, + hashes=hashes, + ) + best_candidate = best_candidate_result.best_candidate + + installed_version: Optional[_BaseVersion] = None + if req.satisfied_by is not None: + installed_version = req.satisfied_by.version + + def _format_versions(cand_iter: Iterable[InstallationCandidate]) -> str: + # This repeated parse_version and str() conversion is needed to + # handle different vendoring sources from pip and pkg_resources. + # If we stop using the pkg_resources provided specifier and start + # using our own, we can drop the cast to str(). + return ( + ", ".join( + sorted( + {str(c.version) for c in cand_iter}, + key=parse_version, + ) + ) + or "none" + ) + + if installed_version is None and best_candidate is None: + logger.critical( + "Could not find a version that satisfies the requirement %s " + "(from versions: %s)", + req, + _format_versions(best_candidate_result.all_candidates), + ) + + raise DistributionNotFound(f"No matching distribution found for {req}") + + def _should_install_candidate( + candidate: Optional[InstallationCandidate], + ) -> "TypeGuard[InstallationCandidate]": + if installed_version is None: + return True + if best_candidate is None: + return False + return best_candidate.version > installed_version + + if not upgrade and installed_version is not None: + if _should_install_candidate(best_candidate): + logger.debug( + "Existing installed version (%s) satisfies requirement " + "(most up-to-date version is %s)", + installed_version, + best_candidate.version, + ) + else: + logger.debug( + "Existing installed version (%s) is most up-to-date and " + "satisfies requirement", + installed_version, + ) + return None + + if _should_install_candidate(best_candidate): + logger.debug( + "Using version %s (newest of versions: %s)", + best_candidate.version, + _format_versions(best_candidate_result.applicable_candidates), + ) + return best_candidate + + # We have an existing version, and its the best version + logger.debug( + "Installed version (%s) is most up-to-date (past versions: %s)", + installed_version, + _format_versions(best_candidate_result.applicable_candidates), + ) + raise BestVersionAlreadyInstalled + + +def _find_name_version_sep(fragment: str, canonical_name: str) -> int: + """Find the separator's index based on the package's canonical name. + + :param fragment: A + filename "fragment" (stem) or + egg fragment. + :param canonical_name: The package's canonical name. + + This function is needed since the canonicalized name does not necessarily + have the same length as the egg info's name part. An example:: + + >>> fragment = 'foo__bar-1.0' + >>> canonical_name = 'foo-bar' + >>> _find_name_version_sep(fragment, canonical_name) + 8 + """ + # Project name and version must be separated by one single dash. Find all + # occurrences of dashes; if the string in front of it matches the canonical + # name, this is the one separating the name and version parts. + for i, c in enumerate(fragment): + if c != "-": + continue + if canonicalize_name(fragment[:i]) == canonical_name: + return i + raise ValueError(f"{fragment} does not match {canonical_name}") + + +def _extract_version_from_fragment(fragment: str, canonical_name: str) -> Optional[str]: + """Parse the version string from a + filename + "fragment" (stem) or egg fragment. + + :param fragment: The string to parse. E.g. foo-2.1 + :param canonical_name: The canonicalized name of the package this + belongs to. + """ + try: + version_start = _find_name_version_sep(fragment, canonical_name) + 1 + except ValueError: + return None + version = fragment[version_start:] + if not version: + return None + return version diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/sources.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/sources.py new file mode 100644 index 0000000000000000000000000000000000000000..3dafb30e6eb843ac56315dd5d0ab223bf4f740b8 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/index/sources.py @@ -0,0 +1,284 @@ +import logging +import mimetypes +import os +from collections import defaultdict +from typing import Callable, Dict, Iterable, List, Optional, Tuple + +from pip._vendor.packaging.utils import ( + InvalidSdistFilename, + InvalidWheelFilename, + canonicalize_name, + parse_sdist_filename, + parse_wheel_filename, +) + +from pip._internal.models.candidate import InstallationCandidate +from pip._internal.models.link import Link +from pip._internal.utils.urls import path_to_url, url_to_path +from pip._internal.vcs import is_url + +logger = logging.getLogger(__name__) + +FoundCandidates = Iterable[InstallationCandidate] +FoundLinks = Iterable[Link] +CandidatesFromPage = Callable[[Link], Iterable[InstallationCandidate]] +PageValidator = Callable[[Link], bool] + + +class LinkSource: + @property + def link(self) -> Optional[Link]: + """Returns the underlying link, if there's one.""" + raise NotImplementedError() + + def page_candidates(self) -> FoundCandidates: + """Candidates found by parsing an archive listing HTML file.""" + raise NotImplementedError() + + def file_links(self) -> FoundLinks: + """Links found by specifying archives directly.""" + raise NotImplementedError() + + +def _is_html_file(file_url: str) -> bool: + return mimetypes.guess_type(file_url, strict=False)[0] == "text/html" + + +class _FlatDirectoryToUrls: + """Scans directory and caches results""" + + def __init__(self, path: str) -> None: + self._path = path + self._page_candidates: List[str] = [] + self._project_name_to_urls: Dict[str, List[str]] = defaultdict(list) + self._scanned_directory = False + + def _scan_directory(self) -> None: + """Scans directory once and populates both page_candidates + and project_name_to_urls at the same time + """ + for entry in os.scandir(self._path): + url = path_to_url(entry.path) + if _is_html_file(url): + self._page_candidates.append(url) + continue + + # File must have a valid wheel or sdist name, + # otherwise not worth considering as a package + try: + project_filename = parse_wheel_filename(entry.name)[0] + except InvalidWheelFilename: + try: + project_filename = parse_sdist_filename(entry.name)[0] + except InvalidSdistFilename: + continue + + self._project_name_to_urls[project_filename].append(url) + self._scanned_directory = True + + @property + def page_candidates(self) -> List[str]: + if not self._scanned_directory: + self._scan_directory() + + return self._page_candidates + + @property + def project_name_to_urls(self) -> Dict[str, List[str]]: + if not self._scanned_directory: + self._scan_directory() + + return self._project_name_to_urls + + +class _FlatDirectorySource(LinkSource): + """Link source specified by ``--find-links=``. + + This looks the content of the directory, and returns: + + * ``page_candidates``: Links listed on each HTML file in the directory. + * ``file_candidates``: Archives in the directory. + """ + + _paths_to_urls: Dict[str, _FlatDirectoryToUrls] = {} + + def __init__( + self, + candidates_from_page: CandidatesFromPage, + path: str, + project_name: str, + ) -> None: + self._candidates_from_page = candidates_from_page + self._project_name = canonicalize_name(project_name) + + # Get existing instance of _FlatDirectoryToUrls if it exists + if path in self._paths_to_urls: + self._path_to_urls = self._paths_to_urls[path] + else: + self._path_to_urls = _FlatDirectoryToUrls(path=path) + self._paths_to_urls[path] = self._path_to_urls + + @property + def link(self) -> Optional[Link]: + return None + + def page_candidates(self) -> FoundCandidates: + for url in self._path_to_urls.page_candidates: + yield from self._candidates_from_page(Link(url)) + + def file_links(self) -> FoundLinks: + for url in self._path_to_urls.project_name_to_urls[self._project_name]: + yield Link(url) + + +class _LocalFileSource(LinkSource): + """``--find-links=`` or ``--[extra-]index-url=``. + + If a URL is supplied, it must be a ``file:`` URL. If a path is supplied to + the option, it is converted to a URL first. This returns: + + * ``page_candidates``: Links listed on an HTML file. + * ``file_candidates``: The non-HTML file. + """ + + def __init__( + self, + candidates_from_page: CandidatesFromPage, + link: Link, + ) -> None: + self._candidates_from_page = candidates_from_page + self._link = link + + @property + def link(self) -> Optional[Link]: + return self._link + + def page_candidates(self) -> FoundCandidates: + if not _is_html_file(self._link.url): + return + yield from self._candidates_from_page(self._link) + + def file_links(self) -> FoundLinks: + if _is_html_file(self._link.url): + return + yield self._link + + +class _RemoteFileSource(LinkSource): + """``--find-links=`` or ``--[extra-]index-url=``. + + This returns: + + * ``page_candidates``: Links listed on an HTML file. + * ``file_candidates``: The non-HTML file. + """ + + def __init__( + self, + candidates_from_page: CandidatesFromPage, + page_validator: PageValidator, + link: Link, + ) -> None: + self._candidates_from_page = candidates_from_page + self._page_validator = page_validator + self._link = link + + @property + def link(self) -> Optional[Link]: + return self._link + + def page_candidates(self) -> FoundCandidates: + if not self._page_validator(self._link): + return + yield from self._candidates_from_page(self._link) + + def file_links(self) -> FoundLinks: + yield self._link + + +class _IndexDirectorySource(LinkSource): + """``--[extra-]index-url=``. + + This is treated like a remote URL; ``candidates_from_page`` contains logic + for this by appending ``index.html`` to the link. + """ + + def __init__( + self, + candidates_from_page: CandidatesFromPage, + link: Link, + ) -> None: + self._candidates_from_page = candidates_from_page + self._link = link + + @property + def link(self) -> Optional[Link]: + return self._link + + def page_candidates(self) -> FoundCandidates: + yield from self._candidates_from_page(self._link) + + def file_links(self) -> FoundLinks: + return () + + +def build_source( + location: str, + *, + candidates_from_page: CandidatesFromPage, + page_validator: PageValidator, + expand_dir: bool, + cache_link_parsing: bool, + project_name: str, +) -> Tuple[Optional[str], Optional[LinkSource]]: + path: Optional[str] = None + url: Optional[str] = None + if os.path.exists(location): # Is a local path. + url = path_to_url(location) + path = location + elif location.startswith("file:"): # A file: URL. + url = location + path = url_to_path(location) + elif is_url(location): + url = location + + if url is None: + msg = ( + "Location '%s' is ignored: " + "it is either a non-existing path or lacks a specific scheme." + ) + logger.warning(msg, location) + return (None, None) + + if path is None: + source: LinkSource = _RemoteFileSource( + candidates_from_page=candidates_from_page, + page_validator=page_validator, + link=Link(url, cache_link_parsing=cache_link_parsing), + ) + return (url, source) + + if os.path.isdir(path): + if expand_dir: + source = _FlatDirectorySource( + candidates_from_page=candidates_from_page, + path=path, + project_name=project_name, + ) + else: + source = _IndexDirectorySource( + candidates_from_page=candidates_from_page, + link=Link(url, cache_link_parsing=cache_link_parsing), + ) + return (url, source) + elif os.path.isfile(path): + source = _LocalFileSource( + candidates_from_page=candidates_from_page, + link=Link(url, cache_link_parsing=cache_link_parsing), + ) + return (url, source) + logger.warning( + "Location '%s' is ignored: it is neither a file nor a directory.", + location, + ) + return (url, None) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..32382be7fe5f6781047e9774679aa8bcf5bbce8a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__init__.py @@ -0,0 +1,456 @@ +import functools +import logging +import os +import pathlib +import sys +import sysconfig +from typing import Any, Dict, Generator, Optional, Tuple + +from pip._internal.models.scheme import SCHEME_KEYS, Scheme +from pip._internal.utils.compat import WINDOWS +from pip._internal.utils.deprecation import deprecated +from pip._internal.utils.virtualenv import running_under_virtualenv + +from . import _sysconfig +from .base import ( + USER_CACHE_DIR, + get_major_minor_version, + get_src_prefix, + is_osx_framework, + site_packages, + user_site, +) + +__all__ = [ + "USER_CACHE_DIR", + "get_bin_prefix", + "get_bin_user", + "get_major_minor_version", + "get_platlib", + "get_purelib", + "get_scheme", + "get_src_prefix", + "site_packages", + "user_site", +] + + +logger = logging.getLogger(__name__) + + +_PLATLIBDIR: str = getattr(sys, "platlibdir", "lib") + +_USE_SYSCONFIG_DEFAULT = sys.version_info >= (3, 10) + + +def _should_use_sysconfig() -> bool: + """This function determines the value of _USE_SYSCONFIG. + + By default, pip uses sysconfig on Python 3.10+. + But Python distributors can override this decision by setting: + sysconfig._PIP_USE_SYSCONFIG = True / False + Rationale in https://github.com/pypa/pip/issues/10647 + + This is a function for testability, but should be constant during any one + run. + """ + return bool(getattr(sysconfig, "_PIP_USE_SYSCONFIG", _USE_SYSCONFIG_DEFAULT)) + + +_USE_SYSCONFIG = _should_use_sysconfig() + +if not _USE_SYSCONFIG: + # Import distutils lazily to avoid deprecation warnings, + # but import it soon enough that it is in memory and available during + # a pip reinstall. + from . import _distutils + +# Be noisy about incompatibilities if this platforms "should" be using +# sysconfig, but is explicitly opting out and using distutils instead. +if _USE_SYSCONFIG_DEFAULT and not _USE_SYSCONFIG: + _MISMATCH_LEVEL = logging.WARNING +else: + _MISMATCH_LEVEL = logging.DEBUG + + +def _looks_like_bpo_44860() -> bool: + """The resolution to bpo-44860 will change this incorrect platlib. + + See . + """ + from distutils.command.install import INSTALL_SCHEMES + + try: + unix_user_platlib = INSTALL_SCHEMES["unix_user"]["platlib"] + except KeyError: + return False + return unix_user_platlib == "$usersite" + + +def _looks_like_red_hat_patched_platlib_purelib(scheme: Dict[str, str]) -> bool: + platlib = scheme["platlib"] + if "/$platlibdir/" in platlib: + platlib = platlib.replace("/$platlibdir/", f"/{_PLATLIBDIR}/") + if "/lib64/" not in platlib: + return False + unpatched = platlib.replace("/lib64/", "/lib/") + return unpatched.replace("$platbase/", "$base/") == scheme["purelib"] + + +@functools.lru_cache(maxsize=None) +def _looks_like_red_hat_lib() -> bool: + """Red Hat patches platlib in unix_prefix and unix_home, but not purelib. + + This is the only way I can see to tell a Red Hat-patched Python. + """ + from distutils.command.install import INSTALL_SCHEMES + + return all( + k in INSTALL_SCHEMES + and _looks_like_red_hat_patched_platlib_purelib(INSTALL_SCHEMES[k]) + for k in ("unix_prefix", "unix_home") + ) + + +@functools.lru_cache(maxsize=None) +def _looks_like_debian_scheme() -> bool: + """Debian adds two additional schemes.""" + from distutils.command.install import INSTALL_SCHEMES + + return "deb_system" in INSTALL_SCHEMES and "unix_local" in INSTALL_SCHEMES + + +@functools.lru_cache(maxsize=None) +def _looks_like_red_hat_scheme() -> bool: + """Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``. + + Red Hat's ``00251-change-user-install-location.patch`` changes the install + command's ``prefix`` and ``exec_prefix`` to append ``"/local"``. This is + (fortunately?) done quite unconditionally, so we create a default command + object without any configuration to detect this. + """ + from distutils.command.install import install + from distutils.dist import Distribution + + cmd: Any = install(Distribution()) + cmd.finalize_options() + return ( + cmd.exec_prefix == f"{os.path.normpath(sys.exec_prefix)}/local" + and cmd.prefix == f"{os.path.normpath(sys.prefix)}/local" + ) + + +@functools.lru_cache(maxsize=None) +def _looks_like_slackware_scheme() -> bool: + """Slackware patches sysconfig but fails to patch distutils and site. + + Slackware changes sysconfig's user scheme to use ``"lib64"`` for the lib + path, but does not do the same to the site module. + """ + if user_site is None: # User-site not available. + return False + try: + paths = sysconfig.get_paths(scheme="posix_user", expand=False) + except KeyError: # User-site not available. + return False + return "/lib64/" in paths["purelib"] and "/lib64/" not in user_site + + +@functools.lru_cache(maxsize=None) +def _looks_like_msys2_mingw_scheme() -> bool: + """MSYS2 patches distutils and sysconfig to use a UNIX-like scheme. + + However, MSYS2 incorrectly patches sysconfig ``nt`` scheme. The fix is + likely going to be included in their 3.10 release, so we ignore the warning. + See msys2/MINGW-packages#9319. + + MSYS2 MINGW's patch uses lowercase ``"lib"`` instead of the usual uppercase, + and is missing the final ``"site-packages"``. + """ + paths = sysconfig.get_paths("nt", expand=False) + return all( + "Lib" not in p and "lib" in p and not p.endswith("site-packages") + for p in (paths[key] for key in ("platlib", "purelib")) + ) + + +def _fix_abiflags(parts: Tuple[str]) -> Generator[str, None, None]: + ldversion = sysconfig.get_config_var("LDVERSION") + abiflags = getattr(sys, "abiflags", None) + + # LDVERSION does not end with sys.abiflags. Just return the path unchanged. + if not ldversion or not abiflags or not ldversion.endswith(abiflags): + yield from parts + return + + # Strip sys.abiflags from LDVERSION-based path components. + for part in parts: + if part.endswith(ldversion): + part = part[: (0 - len(abiflags))] + yield part + + +@functools.lru_cache(maxsize=None) +def _warn_mismatched(old: pathlib.Path, new: pathlib.Path, *, key: str) -> None: + issue_url = "https://github.com/pypa/pip/issues/10151" + message = ( + "Value for %s does not match. Please report this to <%s>" + "\ndistutils: %s" + "\nsysconfig: %s" + ) + logger.log(_MISMATCH_LEVEL, message, key, issue_url, old, new) + + +def _warn_if_mismatch(old: pathlib.Path, new: pathlib.Path, *, key: str) -> bool: + if old == new: + return False + _warn_mismatched(old, new, key=key) + return True + + +@functools.lru_cache(maxsize=None) +def _log_context( + *, + user: bool = False, + home: Optional[str] = None, + root: Optional[str] = None, + prefix: Optional[str] = None, +) -> None: + parts = [ + "Additional context:", + "user = %r", + "home = %r", + "root = %r", + "prefix = %r", + ] + + logger.log(_MISMATCH_LEVEL, "\n".join(parts), user, home, root, prefix) + + +def get_scheme( + dist_name: str, + user: bool = False, + home: Optional[str] = None, + root: Optional[str] = None, + isolated: bool = False, + prefix: Optional[str] = None, +) -> Scheme: + new = _sysconfig.get_scheme( + dist_name, + user=user, + home=home, + root=root, + isolated=isolated, + prefix=prefix, + ) + if _USE_SYSCONFIG: + return new + + old = _distutils.get_scheme( + dist_name, + user=user, + home=home, + root=root, + isolated=isolated, + prefix=prefix, + ) + + warning_contexts = [] + for k in SCHEME_KEYS: + old_v = pathlib.Path(getattr(old, k)) + new_v = pathlib.Path(getattr(new, k)) + + if old_v == new_v: + continue + + # distutils incorrectly put PyPy packages under ``site-packages/python`` + # in the ``posix_home`` scheme, but PyPy devs said they expect the + # directory name to be ``pypy`` instead. So we treat this as a bug fix + # and not warn about it. See bpo-43307 and python/cpython#24628. + skip_pypy_special_case = ( + sys.implementation.name == "pypy" + and home is not None + and k in ("platlib", "purelib") + and old_v.parent == new_v.parent + and old_v.name.startswith("python") + and new_v.name.startswith("pypy") + ) + if skip_pypy_special_case: + continue + + # sysconfig's ``osx_framework_user`` does not include ``pythonX.Y`` in + # the ``include`` value, but distutils's ``headers`` does. We'll let + # CPython decide whether this is a bug or feature. See bpo-43948. + skip_osx_framework_user_special_case = ( + user + and is_osx_framework() + and k == "headers" + and old_v.parent.parent == new_v.parent + and old_v.parent.name.startswith("python") + ) + if skip_osx_framework_user_special_case: + continue + + # On Red Hat and derived Linux distributions, distutils is patched to + # use "lib64" instead of "lib" for platlib. + if k == "platlib" and _looks_like_red_hat_lib(): + continue + + # On Python 3.9+, sysconfig's posix_user scheme sets platlib against + # sys.platlibdir, but distutils's unix_user incorrectly coninutes + # using the same $usersite for both platlib and purelib. This creates a + # mismatch when sys.platlibdir is not "lib". + skip_bpo_44860 = ( + user + and k == "platlib" + and not WINDOWS + and sys.version_info >= (3, 9) + and _PLATLIBDIR != "lib" + and _looks_like_bpo_44860() + ) + if skip_bpo_44860: + continue + + # Slackware incorrectly patches posix_user to use lib64 instead of lib, + # but not usersite to match the location. + skip_slackware_user_scheme = ( + user + and k in ("platlib", "purelib") + and not WINDOWS + and _looks_like_slackware_scheme() + ) + if skip_slackware_user_scheme: + continue + + # Both Debian and Red Hat patch Python to place the system site under + # /usr/local instead of /usr. Debian also places lib in dist-packages + # instead of site-packages, but the /usr/local check should cover it. + skip_linux_system_special_case = ( + not (user or home or prefix or running_under_virtualenv()) + and old_v.parts[1:3] == ("usr", "local") + and len(new_v.parts) > 1 + and new_v.parts[1] == "usr" + and (len(new_v.parts) < 3 or new_v.parts[2] != "local") + and (_looks_like_red_hat_scheme() or _looks_like_debian_scheme()) + ) + if skip_linux_system_special_case: + continue + + # MSYS2 MINGW's sysconfig patch does not include the "site-packages" + # part of the path. This is incorrect and will be fixed in MSYS. + skip_msys2_mingw_bug = ( + WINDOWS and k in ("platlib", "purelib") and _looks_like_msys2_mingw_scheme() + ) + if skip_msys2_mingw_bug: + continue + + # CPython's POSIX install script invokes pip (via ensurepip) against the + # interpreter located in the source tree, not the install site. This + # triggers special logic in sysconfig that's not present in distutils. + # https://github.com/python/cpython/blob/8c21941ddaf/Lib/sysconfig.py#L178-L194 + skip_cpython_build = ( + sysconfig.is_python_build(check_home=True) + and not WINDOWS + and k in ("headers", "include", "platinclude") + ) + if skip_cpython_build: + continue + + warning_contexts.append((old_v, new_v, f"scheme.{k}")) + + if not warning_contexts: + return old + + # Check if this path mismatch is caused by distutils config files. Those + # files will no longer work once we switch to sysconfig, so this raises a + # deprecation message for them. + default_old = _distutils.distutils_scheme( + dist_name, + user, + home, + root, + isolated, + prefix, + ignore_config_files=True, + ) + if any(default_old[k] != getattr(old, k) for k in SCHEME_KEYS): + deprecated( + reason=( + "Configuring installation scheme with distutils config files " + "is deprecated and will no longer work in the near future. If you " + "are using a Homebrew or Linuxbrew Python, please see discussion " + "at https://github.com/Homebrew/homebrew-core/issues/76621" + ), + replacement=None, + gone_in=None, + ) + return old + + # Post warnings about this mismatch so user can report them back. + for old_v, new_v, key in warning_contexts: + _warn_mismatched(old_v, new_v, key=key) + _log_context(user=user, home=home, root=root, prefix=prefix) + + return old + + +def get_bin_prefix() -> str: + new = _sysconfig.get_bin_prefix() + if _USE_SYSCONFIG: + return new + + old = _distutils.get_bin_prefix() + if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="bin_prefix"): + _log_context() + return old + + +def get_bin_user() -> str: + return _sysconfig.get_scheme("", user=True).scripts + + +def _looks_like_deb_system_dist_packages(value: str) -> bool: + """Check if the value is Debian's APT-controlled dist-packages. + + Debian's ``distutils.sysconfig.get_python_lib()`` implementation returns the + default package path controlled by APT, but does not patch ``sysconfig`` to + do the same. This is similar to the bug worked around in ``get_scheme()``, + but here the default is ``deb_system`` instead of ``unix_local``. Ultimately + we can't do anything about this Debian bug, and this detection allows us to + skip the warning when needed. + """ + if not _looks_like_debian_scheme(): + return False + if value == "/usr/lib/python3/dist-packages": + return True + return False + + +def get_purelib() -> str: + """Return the default pure-Python lib location.""" + new = _sysconfig.get_purelib() + if _USE_SYSCONFIG: + return new + + old = _distutils.get_purelib() + if _looks_like_deb_system_dist_packages(old): + return old + if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="purelib"): + _log_context() + return old + + +def get_platlib() -> str: + """Return the default platform-shared lib location.""" + new = _sysconfig.get_platlib() + if _USE_SYSCONFIG: + return new + + from . import _distutils + + old = _distutils.get_platlib() + if _looks_like_deb_system_dist_packages(old): + return old + if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="platlib"): + _log_context() + return old diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ef6dbbc577d722405e760a07e959437022e0bcc Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/_distutils.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/_distutils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ff98a35ff782613521ba1f257cab7c9b4df516 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/_distutils.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/_sysconfig.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/_sysconfig.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63ff8bbbe4a882a3cf3b27cbdc3744a249d2060c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/_sysconfig.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/base.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdeccdd40f01858b0c53ce5d9d379c446f7ae6ee Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/__pycache__/base.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py new file mode 100644 index 0000000000000000000000000000000000000000..3d856256986f68b1bc38d012cfc96f8075268493 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/_distutils.py @@ -0,0 +1,172 @@ +"""Locations where we look for configs, install stuff, etc""" + +# The following comment should be removed at some point in the future. +# mypy: strict-optional=False + +# If pip's going to use distutils, it should not be using the copy that setuptools +# might have injected into the environment. This is done by removing the injected +# shim, if it's injected. +# +# See https://github.com/pypa/pip/issues/8761 for the original discussion and +# rationale for why this is done within pip. +try: + __import__("_distutils_hack").remove_shim() +except (ImportError, AttributeError): + pass + +import logging +import os +import sys +from distutils.cmd import Command as DistutilsCommand +from distutils.command.install import SCHEME_KEYS +from distutils.command.install import install as distutils_install_command +from distutils.sysconfig import get_python_lib +from typing import Dict, List, Optional, Union + +from pip._internal.models.scheme import Scheme +from pip._internal.utils.compat import WINDOWS +from pip._internal.utils.virtualenv import running_under_virtualenv + +from .base import get_major_minor_version + +logger = logging.getLogger(__name__) + + +def distutils_scheme( + dist_name: str, + user: bool = False, + home: Optional[str] = None, + root: Optional[str] = None, + isolated: bool = False, + prefix: Optional[str] = None, + *, + ignore_config_files: bool = False, +) -> Dict[str, str]: + """ + Return a distutils install scheme + """ + from distutils.dist import Distribution + + dist_args: Dict[str, Union[str, List[str]]] = {"name": dist_name} + if isolated: + dist_args["script_args"] = ["--no-user-cfg"] + + d = Distribution(dist_args) + if not ignore_config_files: + try: + d.parse_config_files() + except UnicodeDecodeError: + paths = d.find_config_files() + logger.warning( + "Ignore distutils configs in %s due to encoding errors.", + ", ".join(os.path.basename(p) for p in paths), + ) + obj: Optional[DistutilsCommand] = None + obj = d.get_command_obj("install", create=True) + assert obj is not None + i: distutils_install_command = obj + # NOTE: setting user or home has the side-effect of creating the home dir + # or user base for installations during finalize_options() + # ideally, we'd prefer a scheme class that has no side-effects. + assert not (user and prefix), f"user={user} prefix={prefix}" + assert not (home and prefix), f"home={home} prefix={prefix}" + i.user = user or i.user + if user or home: + i.prefix = "" + i.prefix = prefix or i.prefix + i.home = home or i.home + i.root = root or i.root + i.finalize_options() + + scheme: Dict[str, str] = {} + for key in SCHEME_KEYS: + scheme[key] = getattr(i, "install_" + key) + + # install_lib specified in setup.cfg should install *everything* + # into there (i.e. it takes precedence over both purelib and + # platlib). Note, i.install_lib is *always* set after + # finalize_options(); we only want to override here if the user + # has explicitly requested it hence going back to the config + if "install_lib" in d.get_option_dict("install"): + scheme.update({"purelib": i.install_lib, "platlib": i.install_lib}) + + if running_under_virtualenv(): + if home: + prefix = home + elif user: + prefix = i.install_userbase + else: + prefix = i.prefix + scheme["headers"] = os.path.join( + prefix, + "include", + "site", + f"python{get_major_minor_version()}", + dist_name, + ) + + if root is not None: + path_no_drive = os.path.splitdrive(os.path.abspath(scheme["headers"]))[1] + scheme["headers"] = os.path.join(root, path_no_drive[1:]) + + return scheme + + +def get_scheme( + dist_name: str, + user: bool = False, + home: Optional[str] = None, + root: Optional[str] = None, + isolated: bool = False, + prefix: Optional[str] = None, +) -> Scheme: + """ + Get the "scheme" corresponding to the input parameters. The distutils + documentation provides the context for the available schemes: + https://docs.python.org/3/install/index.html#alternate-installation + + :param dist_name: the name of the package to retrieve the scheme for, used + in the headers scheme path + :param user: indicates to use the "user" scheme + :param home: indicates to use the "home" scheme and provides the base + directory for the same + :param root: root under which other directories are re-based + :param isolated: equivalent to --no-user-cfg, i.e. do not consider + ~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for + scheme paths + :param prefix: indicates to use the "prefix" scheme and provides the + base directory for the same + """ + scheme = distutils_scheme(dist_name, user, home, root, isolated, prefix) + return Scheme( + platlib=scheme["platlib"], + purelib=scheme["purelib"], + headers=scheme["headers"], + scripts=scheme["scripts"], + data=scheme["data"], + ) + + +def get_bin_prefix() -> str: + # XXX: In old virtualenv versions, sys.prefix can contain '..' components, + # so we need to call normpath to eliminate them. + prefix = os.path.normpath(sys.prefix) + if WINDOWS: + bin_py = os.path.join(prefix, "Scripts") + # buildout uses 'bin' on Windows too? + if not os.path.exists(bin_py): + bin_py = os.path.join(prefix, "bin") + return bin_py + # Forcing to use /usr/local/bin for standard macOS framework installs + # Also log to ~/Library/Logs/ for use with the Console.app log viewer + if sys.platform[:6] == "darwin" and prefix[:16] == "/System/Library/": + return "/usr/local/bin" + return os.path.join(prefix, "bin") + + +def get_purelib() -> str: + return get_python_lib(plat_specific=False) + + +def get_platlib() -> str: + return get_python_lib(plat_specific=True) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/_sysconfig.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/_sysconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..ca860ea562c2c0c30982ba6cff654355e9f21c8a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/_sysconfig.py @@ -0,0 +1,214 @@ +import logging +import os +import sys +import sysconfig +import typing + +from pip._internal.exceptions import InvalidSchemeCombination, UserInstallationInvalid +from pip._internal.models.scheme import SCHEME_KEYS, Scheme +from pip._internal.utils.virtualenv import running_under_virtualenv + +from .base import change_root, get_major_minor_version, is_osx_framework + +logger = logging.getLogger(__name__) + + +# Notes on _infer_* functions. +# Unfortunately ``get_default_scheme()`` didn't exist before 3.10, so there's no +# way to ask things like "what is the '_prefix' scheme on this platform". These +# functions try to answer that with some heuristics while accounting for ad-hoc +# platforms not covered by CPython's default sysconfig implementation. If the +# ad-hoc implementation does not fully implement sysconfig, we'll fall back to +# a POSIX scheme. + +_AVAILABLE_SCHEMES = set(sysconfig.get_scheme_names()) + +_PREFERRED_SCHEME_API = getattr(sysconfig, "get_preferred_scheme", None) + + +def _should_use_osx_framework_prefix() -> bool: + """Check for Apple's ``osx_framework_library`` scheme. + + Python distributed by Apple's Command Line Tools has this special scheme + that's used when: + + * This is a framework build. + * We are installing into the system prefix. + + This does not account for ``pip install --prefix`` (also means we're not + installing to the system prefix), which should use ``posix_prefix``, but + logic here means ``_infer_prefix()`` outputs ``osx_framework_library``. But + since ``prefix`` is not available for ``sysconfig.get_default_scheme()``, + which is the stdlib replacement for ``_infer_prefix()``, presumably Apple + wouldn't be able to magically switch between ``osx_framework_library`` and + ``posix_prefix``. ``_infer_prefix()`` returning ``osx_framework_library`` + means its behavior is consistent whether we use the stdlib implementation + or our own, and we deal with this special case in ``get_scheme()`` instead. + """ + return ( + "osx_framework_library" in _AVAILABLE_SCHEMES + and not running_under_virtualenv() + and is_osx_framework() + ) + + +def _infer_prefix() -> str: + """Try to find a prefix scheme for the current platform. + + This tries: + + * A special ``osx_framework_library`` for Python distributed by Apple's + Command Line Tools, when not running in a virtual environment. + * Implementation + OS, used by PyPy on Windows (``pypy_nt``). + * Implementation without OS, used by PyPy on POSIX (``pypy``). + * OS + "prefix", used by CPython on POSIX (``posix_prefix``). + * Just the OS name, used by CPython on Windows (``nt``). + + If none of the above works, fall back to ``posix_prefix``. + """ + if _PREFERRED_SCHEME_API: + return _PREFERRED_SCHEME_API("prefix") + if _should_use_osx_framework_prefix(): + return "osx_framework_library" + implementation_suffixed = f"{sys.implementation.name}_{os.name}" + if implementation_suffixed in _AVAILABLE_SCHEMES: + return implementation_suffixed + if sys.implementation.name in _AVAILABLE_SCHEMES: + return sys.implementation.name + suffixed = f"{os.name}_prefix" + if suffixed in _AVAILABLE_SCHEMES: + return suffixed + if os.name in _AVAILABLE_SCHEMES: # On Windows, prefx is just called "nt". + return os.name + return "posix_prefix" + + +def _infer_user() -> str: + """Try to find a user scheme for the current platform.""" + if _PREFERRED_SCHEME_API: + return _PREFERRED_SCHEME_API("user") + if is_osx_framework() and not running_under_virtualenv(): + suffixed = "osx_framework_user" + else: + suffixed = f"{os.name}_user" + if suffixed in _AVAILABLE_SCHEMES: + return suffixed + if "posix_user" not in _AVAILABLE_SCHEMES: # User scheme unavailable. + raise UserInstallationInvalid() + return "posix_user" + + +def _infer_home() -> str: + """Try to find a home for the current platform.""" + if _PREFERRED_SCHEME_API: + return _PREFERRED_SCHEME_API("home") + suffixed = f"{os.name}_home" + if suffixed in _AVAILABLE_SCHEMES: + return suffixed + return "posix_home" + + +# Update these keys if the user sets a custom home. +_HOME_KEYS = [ + "installed_base", + "base", + "installed_platbase", + "platbase", + "prefix", + "exec_prefix", +] +if sysconfig.get_config_var("userbase") is not None: + _HOME_KEYS.append("userbase") + + +def get_scheme( + dist_name: str, + user: bool = False, + home: typing.Optional[str] = None, + root: typing.Optional[str] = None, + isolated: bool = False, + prefix: typing.Optional[str] = None, +) -> Scheme: + """ + Get the "scheme" corresponding to the input parameters. + + :param dist_name: the name of the package to retrieve the scheme for, used + in the headers scheme path + :param user: indicates to use the "user" scheme + :param home: indicates to use the "home" scheme + :param root: root under which other directories are re-based + :param isolated: ignored, but kept for distutils compatibility (where + this controls whether the user-site pydistutils.cfg is honored) + :param prefix: indicates to use the "prefix" scheme and provides the + base directory for the same + """ + if user and prefix: + raise InvalidSchemeCombination("--user", "--prefix") + if home and prefix: + raise InvalidSchemeCombination("--home", "--prefix") + + if home is not None: + scheme_name = _infer_home() + elif user: + scheme_name = _infer_user() + else: + scheme_name = _infer_prefix() + + # Special case: When installing into a custom prefix, use posix_prefix + # instead of osx_framework_library. See _should_use_osx_framework_prefix() + # docstring for details. + if prefix is not None and scheme_name == "osx_framework_library": + scheme_name = "posix_prefix" + + if home is not None: + variables = {k: home for k in _HOME_KEYS} + elif prefix is not None: + variables = {k: prefix for k in _HOME_KEYS} + else: + variables = {} + + paths = sysconfig.get_paths(scheme=scheme_name, vars=variables) + + # Logic here is very arbitrary, we're doing it for compatibility, don't ask. + # 1. Pip historically uses a special header path in virtual environments. + # 2. If the distribution name is not known, distutils uses 'UNKNOWN'. We + # only do the same when not running in a virtual environment because + # pip's historical header path logic (see point 1) did not do this. + if running_under_virtualenv(): + if user: + base = variables.get("userbase", sys.prefix) + else: + base = variables.get("base", sys.prefix) + python_xy = f"python{get_major_minor_version()}" + paths["include"] = os.path.join(base, "include", "site", python_xy) + elif not dist_name: + dist_name = "UNKNOWN" + + scheme = Scheme( + platlib=paths["platlib"], + purelib=paths["purelib"], + headers=os.path.join(paths["include"], dist_name), + scripts=paths["scripts"], + data=paths["data"], + ) + if root is not None: + converted_keys = {} + for key in SCHEME_KEYS: + converted_keys[key] = change_root(root, getattr(scheme, key)) + scheme = Scheme(**converted_keys) + return scheme + + +def get_bin_prefix() -> str: + # Forcing to use /usr/local/bin for standard macOS framework installs. + if sys.platform[:6] == "darwin" and sys.prefix[:16] == "/System/Library/": + return "/usr/local/bin" + return sysconfig.get_paths()["scripts"] + + +def get_purelib() -> str: + return sysconfig.get_paths()["purelib"] + + +def get_platlib() -> str: + return sysconfig.get_paths()["platlib"] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/base.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/base.py new file mode 100644 index 0000000000000000000000000000000000000000..3f9f896e632e929a63e9724ab80ecdfc9761b795 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/locations/base.py @@ -0,0 +1,81 @@ +import functools +import os +import site +import sys +import sysconfig +import typing + +from pip._internal.exceptions import InstallationError +from pip._internal.utils import appdirs +from pip._internal.utils.virtualenv import running_under_virtualenv + +# Application Directories +USER_CACHE_DIR = appdirs.user_cache_dir("pip") + +# FIXME doesn't account for venv linked to global site-packages +site_packages: str = sysconfig.get_path("purelib") + + +def get_major_minor_version() -> str: + """ + Return the major-minor version of the current Python as a string, e.g. + "3.7" or "3.10". + """ + return "{}.{}".format(*sys.version_info) + + +def change_root(new_root: str, pathname: str) -> str: + """Return 'pathname' with 'new_root' prepended. + + If 'pathname' is relative, this is equivalent to os.path.join(new_root, pathname). + Otherwise, it requires making 'pathname' relative and then joining the + two, which is tricky on DOS/Windows and Mac OS. + + This is borrowed from Python's standard library's distutils module. + """ + if os.name == "posix": + if not os.path.isabs(pathname): + return os.path.join(new_root, pathname) + else: + return os.path.join(new_root, pathname[1:]) + + elif os.name == "nt": + (drive, path) = os.path.splitdrive(pathname) + if path[0] == "\\": + path = path[1:] + return os.path.join(new_root, path) + + else: + raise InstallationError( + f"Unknown platform: {os.name}\n" + "Can not change root path prefix on unknown platform." + ) + + +def get_src_prefix() -> str: + if running_under_virtualenv(): + src_prefix = os.path.join(sys.prefix, "src") + else: + # FIXME: keep src in cwd for now (it is not a temporary folder) + try: + src_prefix = os.path.join(os.getcwd(), "src") + except OSError: + # In case the current working directory has been renamed or deleted + sys.exit("The folder you are executing pip from can no longer be found.") + + # under macOS + virtualenv sys.prefix is not properly resolved + # it is something like /path/to/python/bin/.. + return os.path.abspath(src_prefix) + + +try: + # Use getusersitepackages if this is present, as it ensures that the + # value is initialised properly. + user_site: typing.Optional[str] = site.getusersitepackages() +except AttributeError: + user_site = site.USER_SITE + + +@functools.lru_cache(maxsize=None) +def is_osx_framework() -> bool: + return bool(sysconfig.get_config_var("PYTHONFRAMEWORK")) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/main.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/main.py new file mode 100644 index 0000000000000000000000000000000000000000..33c6d24cd85b55a9fb1b1e6ab784f471e2b135f0 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/main.py @@ -0,0 +1,12 @@ +from typing import List, Optional + + +def main(args: Optional[List[str]] = None) -> int: + """This is preserved for old console scripts that may still be referencing + it. + + For additional details, see https://github.com/pypa/pip/issues/7498. + """ + from pip._internal.utils.entrypoints import _wrapper + + return _wrapper(args) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea1e7fd2e5c4908bec25d08b4ad32be05834985 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__init__.py @@ -0,0 +1,128 @@ +import contextlib +import functools +import os +import sys +from typing import TYPE_CHECKING, List, Optional, Type, cast + +from pip._internal.utils.misc import strtobool + +from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel + +if TYPE_CHECKING: + from typing import Literal, Protocol +else: + Protocol = object + +__all__ = [ + "BaseDistribution", + "BaseEnvironment", + "FilesystemWheel", + "MemoryWheel", + "Wheel", + "get_default_environment", + "get_environment", + "get_wheel_distribution", + "select_backend", +] + + +def _should_use_importlib_metadata() -> bool: + """Whether to use the ``importlib.metadata`` or ``pkg_resources`` backend. + + By default, pip uses ``importlib.metadata`` on Python 3.11+, and + ``pkg_resources`` otherwise. This can be overridden by a couple of ways: + + * If environment variable ``_PIP_USE_IMPORTLIB_METADATA`` is set, it + dictates whether ``importlib.metadata`` is used, regardless of Python + version. + * On Python 3.11+, Python distributors can patch ``importlib.metadata`` + to add a global constant ``_PIP_USE_IMPORTLIB_METADATA = False``. This + makes pip use ``pkg_resources`` (unless the user set the aforementioned + environment variable to *True*). + """ + with contextlib.suppress(KeyError, ValueError): + return bool(strtobool(os.environ["_PIP_USE_IMPORTLIB_METADATA"])) + if sys.version_info < (3, 11): + return False + import importlib.metadata + + return bool(getattr(importlib.metadata, "_PIP_USE_IMPORTLIB_METADATA", True)) + + +class Backend(Protocol): + NAME: 'Literal["importlib", "pkg_resources"]' + Distribution: Type[BaseDistribution] + Environment: Type[BaseEnvironment] + + +@functools.lru_cache(maxsize=None) +def select_backend() -> Backend: + if _should_use_importlib_metadata(): + from . import importlib + + return cast(Backend, importlib) + from . import pkg_resources + + return cast(Backend, pkg_resources) + + +def get_default_environment() -> BaseEnvironment: + """Get the default representation for the current environment. + + This returns an Environment instance from the chosen backend. The default + Environment instance should be built from ``sys.path`` and may use caching + to share instance state across calls. + """ + return select_backend().Environment.default() + + +def get_environment(paths: Optional[List[str]]) -> BaseEnvironment: + """Get a representation of the environment specified by ``paths``. + + This returns an Environment instance from the chosen backend based on the + given import paths. The backend must build a fresh instance representing + the state of installed distributions when this function is called. + """ + return select_backend().Environment.from_paths(paths) + + +def get_directory_distribution(directory: str) -> BaseDistribution: + """Get the distribution metadata representation in the specified directory. + + This returns a Distribution instance from the chosen backend based on + the given on-disk ``.dist-info`` directory. + """ + return select_backend().Distribution.from_directory(directory) + + +def get_wheel_distribution(wheel: Wheel, canonical_name: str) -> BaseDistribution: + """Get the representation of the specified wheel's distribution metadata. + + This returns a Distribution instance from the chosen backend based on + the given wheel's ``.dist-info`` directory. + + :param canonical_name: Normalized project name of the given wheel. + """ + return select_backend().Distribution.from_wheel(wheel, canonical_name) + + +def get_metadata_distribution( + metadata_contents: bytes, + filename: str, + canonical_name: str, +) -> BaseDistribution: + """Get the dist representation of the specified METADATA file contents. + + This returns a Distribution instance from the chosen backend sourced from the data + in `metadata_contents`. + + :param metadata_contents: Contents of a METADATA file within a dist, or one served + via PEP 658. + :param filename: Filename for the dist this metadata represents. + :param canonical_name: Normalized project name of the given dist. + """ + return select_backend().Distribution.from_metadata_file_contents( + metadata_contents, + filename, + canonical_name, + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..847c3052652cbb8db6b057695f40ed00bcb628ec Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/_json.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/_json.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..004118d9dead59bac0f2a5f499ab3a02f7a5c7a8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/_json.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/base.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24d794e0b32dede839a9b08b27c761f867ac73bd Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/base.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c55c17c1103054654f085da16b2b28db95e8de74 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/_json.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/_json.py new file mode 100644 index 0000000000000000000000000000000000000000..f3aeab3225ffc8f6a63f5f40d351e04be4e3c647 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/_json.py @@ -0,0 +1,86 @@ +# Extracted from https://github.com/pfmoore/pkg_metadata + +from email.header import Header, decode_header, make_header +from email.message import Message +from typing import Any, Dict, List, Union, cast + +METADATA_FIELDS = [ + # Name, Multiple-Use + ("Metadata-Version", False), + ("Name", False), + ("Version", False), + ("Dynamic", True), + ("Platform", True), + ("Supported-Platform", True), + ("Summary", False), + ("Description", False), + ("Description-Content-Type", False), + ("Keywords", False), + ("Home-page", False), + ("Download-URL", False), + ("Author", False), + ("Author-email", False), + ("Maintainer", False), + ("Maintainer-email", False), + ("License", False), + ("License-Expression", False), + ("License-File", True), + ("Classifier", True), + ("Requires-Dist", True), + ("Requires-Python", False), + ("Requires-External", True), + ("Project-URL", True), + ("Provides-Extra", True), + ("Provides-Dist", True), + ("Obsoletes-Dist", True), +] + + +def json_name(field: str) -> str: + return field.lower().replace("-", "_") + + +def msg_to_json(msg: Message) -> Dict[str, Any]: + """Convert a Message object into a JSON-compatible dictionary.""" + + def sanitise_header(h: Union[Header, str]) -> str: + if isinstance(h, Header): + chunks = [] + for bytes, encoding in decode_header(h): + if encoding == "unknown-8bit": + try: + # See if UTF-8 works + bytes.decode("utf-8") + encoding = "utf-8" + except UnicodeDecodeError: + # If not, latin1 at least won't fail + encoding = "latin1" + chunks.append((bytes, encoding)) + return str(make_header(chunks)) + return str(h) + + result = {} + for field, multi in METADATA_FIELDS: + if field not in msg: + continue + key = json_name(field) + if multi: + value: Union[str, List[str]] = [ + sanitise_header(v) for v in msg.get_all(field) # type: ignore + ] + else: + value = sanitise_header(msg.get(field)) # type: ignore + if key == "keywords": + # Accept both comma-separated and space-separated + # forms, for better compatibility with old data. + if "," in value: + value = [v.strip() for v in value.split(",")] + else: + value = value.split() + result[key] = value + + payload = cast(str, msg.get_payload()) + if payload: + result["description"] = payload + + return result diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/base.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/base.py new file mode 100644 index 0000000000000000000000000000000000000000..9eabcdb278bd53959f489a8a0fb5ee13a8512f5b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/base.py @@ -0,0 +1,688 @@ +import csv +import email.message +import functools +import json +import logging +import pathlib +import re +import zipfile +from typing import ( + IO, + Any, + Collection, + Container, + Dict, + Iterable, + Iterator, + List, + NamedTuple, + Optional, + Protocol, + Tuple, + Union, +) + +from pip._vendor.packaging.requirements import Requirement +from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet +from pip._vendor.packaging.utils import NormalizedName, canonicalize_name +from pip._vendor.packaging.version import Version + +from pip._internal.exceptions import NoneMetadataError +from pip._internal.locations import site_packages, user_site +from pip._internal.models.direct_url import ( + DIRECT_URL_METADATA_NAME, + DirectUrl, + DirectUrlValidationError, +) +from pip._internal.utils.compat import stdlib_pkgs # TODO: Move definition here. +from pip._internal.utils.egg_link import egg_link_path_from_sys_path +from pip._internal.utils.misc import is_local, normalize_path +from pip._internal.utils.urls import url_to_path + +from ._json import msg_to_json + +InfoPath = Union[str, pathlib.PurePath] + +logger = logging.getLogger(__name__) + + +class BaseEntryPoint(Protocol): + @property + def name(self) -> str: + raise NotImplementedError() + + @property + def value(self) -> str: + raise NotImplementedError() + + @property + def group(self) -> str: + raise NotImplementedError() + + +def _convert_installed_files_path( + entry: Tuple[str, ...], + info: Tuple[str, ...], +) -> str: + """Convert a legacy installed-files.txt path into modern RECORD path. + + The legacy format stores paths relative to the info directory, while the + modern format stores paths relative to the package root, e.g. the + site-packages directory. + + :param entry: Path parts of the installed-files.txt entry. + :param info: Path parts of the egg-info directory relative to package root. + :returns: The converted entry. + + For best compatibility with symlinks, this does not use ``abspath()`` or + ``Path.resolve()``, but tries to work with path parts: + + 1. While ``entry`` starts with ``..``, remove the equal amounts of parts + from ``info``; if ``info`` is empty, start appending ``..`` instead. + 2. Join the two directly. + """ + while entry and entry[0] == "..": + if not info or info[-1] == "..": + info += ("..",) + else: + info = info[:-1] + entry = entry[1:] + return str(pathlib.Path(*info, *entry)) + + +class RequiresEntry(NamedTuple): + requirement: str + extra: str + marker: str + + +class BaseDistribution(Protocol): + @classmethod + def from_directory(cls, directory: str) -> "BaseDistribution": + """Load the distribution from a metadata directory. + + :param directory: Path to a metadata directory, e.g. ``.dist-info``. + """ + raise NotImplementedError() + + @classmethod + def from_metadata_file_contents( + cls, + metadata_contents: bytes, + filename: str, + project_name: str, + ) -> "BaseDistribution": + """Load the distribution from the contents of a METADATA file. + + This is used to implement PEP 658 by generating a "shallow" dist object that can + be used for resolution without downloading or building the actual dist yet. + + :param metadata_contents: The contents of a METADATA file. + :param filename: File name for the dist with this metadata. + :param project_name: Name of the project this dist represents. + """ + raise NotImplementedError() + + @classmethod + def from_wheel(cls, wheel: "Wheel", name: str) -> "BaseDistribution": + """Load the distribution from a given wheel. + + :param wheel: A concrete wheel definition. + :param name: File name of the wheel. + + :raises InvalidWheel: Whenever loading of the wheel causes a + :py:exc:`zipfile.BadZipFile` exception to be thrown. + :raises UnsupportedWheel: If the wheel is a valid zip, but malformed + internally. + """ + raise NotImplementedError() + + def __repr__(self) -> str: + return f"{self.raw_name} {self.raw_version} ({self.location})" + + def __str__(self) -> str: + return f"{self.raw_name} {self.raw_version}" + + @property + def location(self) -> Optional[str]: + """Where the distribution is loaded from. + + A string value is not necessarily a filesystem path, since distributions + can be loaded from other sources, e.g. arbitrary zip archives. ``None`` + means the distribution is created in-memory. + + Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If + this is a symbolic link, we want to preserve the relative path between + it and files in the distribution. + """ + raise NotImplementedError() + + @property + def editable_project_location(self) -> Optional[str]: + """The project location for editable distributions. + + This is the directory where pyproject.toml or setup.py is located. + None if the distribution is not installed in editable mode. + """ + # TODO: this property is relatively costly to compute, memoize it ? + direct_url = self.direct_url + if direct_url: + if direct_url.is_local_editable(): + return url_to_path(direct_url.url) + else: + # Search for an .egg-link file by walking sys.path, as it was + # done before by dist_is_editable(). + egg_link_path = egg_link_path_from_sys_path(self.raw_name) + if egg_link_path: + # TODO: get project location from second line of egg_link file + # (https://github.com/pypa/pip/issues/10243) + return self.location + return None + + @property + def installed_location(self) -> Optional[str]: + """The distribution's "installed" location. + + This should generally be a ``site-packages`` directory. This is + usually ``dist.location``, except for legacy develop-installed packages, + where ``dist.location`` is the source code location, and this is where + the ``.egg-link`` file is. + + The returned location is normalized (in particular, with symlinks removed). + """ + raise NotImplementedError() + + @property + def info_location(self) -> Optional[str]: + """Location of the .[egg|dist]-info directory or file. + + Similarly to ``location``, a string value is not necessarily a + filesystem path. ``None`` means the distribution is created in-memory. + + For a modern .dist-info installation on disk, this should be something + like ``{location}/{raw_name}-{version}.dist-info``. + + Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If + this is a symbolic link, we want to preserve the relative path between + it and other files in the distribution. + """ + raise NotImplementedError() + + @property + def installed_by_distutils(self) -> bool: + """Whether this distribution is installed with legacy distutils format. + + A distribution installed with "raw" distutils not patched by setuptools + uses one single file at ``info_location`` to store metadata. We need to + treat this specially on uninstallation. + """ + info_location = self.info_location + if not info_location: + return False + return pathlib.Path(info_location).is_file() + + @property + def installed_as_egg(self) -> bool: + """Whether this distribution is installed as an egg. + + This usually indicates the distribution was installed by (older versions + of) easy_install. + """ + location = self.location + if not location: + return False + return location.endswith(".egg") + + @property + def installed_with_setuptools_egg_info(self) -> bool: + """Whether this distribution is installed with the ``.egg-info`` format. + + This usually indicates the distribution was installed with setuptools + with an old pip version or with ``single-version-externally-managed``. + + Note that this ensure the metadata store is a directory. distutils can + also installs an ``.egg-info``, but as a file, not a directory. This + property is *False* for that case. Also see ``installed_by_distutils``. + """ + info_location = self.info_location + if not info_location: + return False + if not info_location.endswith(".egg-info"): + return False + return pathlib.Path(info_location).is_dir() + + @property + def installed_with_dist_info(self) -> bool: + """Whether this distribution is installed with the "modern format". + + This indicates a "modern" installation, e.g. storing metadata in the + ``.dist-info`` directory. This applies to installations made by + setuptools (but through pip, not directly), or anything using the + standardized build backend interface (PEP 517). + """ + info_location = self.info_location + if not info_location: + return False + if not info_location.endswith(".dist-info"): + return False + return pathlib.Path(info_location).is_dir() + + @property + def canonical_name(self) -> NormalizedName: + raise NotImplementedError() + + @property + def version(self) -> Version: + raise NotImplementedError() + + @property + def raw_version(self) -> str: + raise NotImplementedError() + + @property + def setuptools_filename(self) -> str: + """Convert a project name to its setuptools-compatible filename. + + This is a copy of ``pkg_resources.to_filename()`` for compatibility. + """ + return self.raw_name.replace("-", "_") + + @property + def direct_url(self) -> Optional[DirectUrl]: + """Obtain a DirectUrl from this distribution. + + Returns None if the distribution has no `direct_url.json` metadata, + or if `direct_url.json` is invalid. + """ + try: + content = self.read_text(DIRECT_URL_METADATA_NAME) + except FileNotFoundError: + return None + try: + return DirectUrl.from_json(content) + except ( + UnicodeDecodeError, + json.JSONDecodeError, + DirectUrlValidationError, + ) as e: + logger.warning( + "Error parsing %s for %s: %s", + DIRECT_URL_METADATA_NAME, + self.canonical_name, + e, + ) + return None + + @property + def installer(self) -> str: + try: + installer_text = self.read_text("INSTALLER") + except (OSError, ValueError, NoneMetadataError): + return "" # Fail silently if the installer file cannot be read. + for line in installer_text.splitlines(): + cleaned_line = line.strip() + if cleaned_line: + return cleaned_line + return "" + + @property + def requested(self) -> bool: + return self.is_file("REQUESTED") + + @property + def editable(self) -> bool: + return bool(self.editable_project_location) + + @property + def local(self) -> bool: + """If distribution is installed in the current virtual environment. + + Always True if we're not in a virtualenv. + """ + if self.installed_location is None: + return False + return is_local(self.installed_location) + + @property + def in_usersite(self) -> bool: + if self.installed_location is None or user_site is None: + return False + return self.installed_location.startswith(normalize_path(user_site)) + + @property + def in_site_packages(self) -> bool: + if self.installed_location is None or site_packages is None: + return False + return self.installed_location.startswith(normalize_path(site_packages)) + + def is_file(self, path: InfoPath) -> bool: + """Check whether an entry in the info directory is a file.""" + raise NotImplementedError() + + def iter_distutils_script_names(self) -> Iterator[str]: + """Find distutils 'scripts' entries metadata. + + If 'scripts' is supplied in ``setup.py``, distutils records those in the + installed distribution's ``scripts`` directory, a file for each script. + """ + raise NotImplementedError() + + def read_text(self, path: InfoPath) -> str: + """Read a file in the info directory. + + :raise FileNotFoundError: If ``path`` does not exist in the directory. + :raise NoneMetadataError: If ``path`` exists in the info directory, but + cannot be read. + """ + raise NotImplementedError() + + def iter_entry_points(self) -> Iterable[BaseEntryPoint]: + raise NotImplementedError() + + def _metadata_impl(self) -> email.message.Message: + raise NotImplementedError() + + @functools.cached_property + def metadata(self) -> email.message.Message: + """Metadata of distribution parsed from e.g. METADATA or PKG-INFO. + + This should return an empty message if the metadata file is unavailable. + + :raises NoneMetadataError: If the metadata file is available, but does + not contain valid metadata. + """ + metadata = self._metadata_impl() + self._add_egg_info_requires(metadata) + return metadata + + @property + def metadata_dict(self) -> Dict[str, Any]: + """PEP 566 compliant JSON-serializable representation of METADATA or PKG-INFO. + + This should return an empty dict if the metadata file is unavailable. + + :raises NoneMetadataError: If the metadata file is available, but does + not contain valid metadata. + """ + return msg_to_json(self.metadata) + + @property + def metadata_version(self) -> Optional[str]: + """Value of "Metadata-Version:" in distribution metadata, if available.""" + return self.metadata.get("Metadata-Version") + + @property + def raw_name(self) -> str: + """Value of "Name:" in distribution metadata.""" + # The metadata should NEVER be missing the Name: key, but if it somehow + # does, fall back to the known canonical name. + return self.metadata.get("Name", self.canonical_name) + + @property + def requires_python(self) -> SpecifierSet: + """Value of "Requires-Python:" in distribution metadata. + + If the key does not exist or contains an invalid value, an empty + SpecifierSet should be returned. + """ + value = self.metadata.get("Requires-Python") + if value is None: + return SpecifierSet() + try: + # Convert to str to satisfy the type checker; this can be a Header object. + spec = SpecifierSet(str(value)) + except InvalidSpecifier as e: + message = "Package %r has an invalid Requires-Python: %s" + logger.warning(message, self.raw_name, e) + return SpecifierSet() + return spec + + def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]: + """Dependencies of this distribution. + + For modern .dist-info distributions, this is the collection of + "Requires-Dist:" entries in distribution metadata. + """ + raise NotImplementedError() + + def iter_raw_dependencies(self) -> Iterable[str]: + """Raw Requires-Dist metadata.""" + return self.metadata.get_all("Requires-Dist", []) + + def iter_provided_extras(self) -> Iterable[NormalizedName]: + """Extras provided by this distribution. + + For modern .dist-info distributions, this is the collection of + "Provides-Extra:" entries in distribution metadata. + + The return value of this function is expected to be normalised names, + per PEP 685, with the returned value being handled appropriately by + `iter_dependencies`. + """ + raise NotImplementedError() + + def _iter_declared_entries_from_record(self) -> Optional[Iterator[str]]: + try: + text = self.read_text("RECORD") + except FileNotFoundError: + return None + # This extra Path-str cast normalizes entries. + return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines())) + + def _iter_declared_entries_from_legacy(self) -> Optional[Iterator[str]]: + try: + text = self.read_text("installed-files.txt") + except FileNotFoundError: + return None + paths = (p for p in text.splitlines(keepends=False) if p) + root = self.location + info = self.info_location + if root is None or info is None: + return paths + try: + info_rel = pathlib.Path(info).relative_to(root) + except ValueError: # info is not relative to root. + return paths + if not info_rel.parts: # info *is* root. + return paths + return ( + _convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts) + for p in paths + ) + + def iter_declared_entries(self) -> Optional[Iterator[str]]: + """Iterate through file entries declared in this distribution. + + For modern .dist-info distributions, this is the files listed in the + ``RECORD`` metadata file. For legacy setuptools distributions, this + comes from ``installed-files.txt``, with entries normalized to be + compatible with the format used by ``RECORD``. + + :return: An iterator for listed entries, or None if the distribution + contains neither ``RECORD`` nor ``installed-files.txt``. + """ + return ( + self._iter_declared_entries_from_record() + or self._iter_declared_entries_from_legacy() + ) + + def _iter_requires_txt_entries(self) -> Iterator[RequiresEntry]: + """Parse a ``requires.txt`` in an egg-info directory. + + This is an INI-ish format where an egg-info stores dependencies. A + section name describes extra other environment markers, while each entry + is an arbitrary string (not a key-value pair) representing a dependency + as a requirement string (no markers). + + There is a construct in ``importlib.metadata`` called ``Sectioned`` that + does mostly the same, but the format is currently considered private. + """ + try: + content = self.read_text("requires.txt") + except FileNotFoundError: + return + extra = marker = "" # Section-less entries don't have markers. + for line in content.splitlines(): + line = line.strip() + if not line or line.startswith("#"): # Comment; ignored. + continue + if line.startswith("[") and line.endswith("]"): # A section header. + extra, _, marker = line.strip("[]").partition(":") + continue + yield RequiresEntry(requirement=line, extra=extra, marker=marker) + + def _iter_egg_info_extras(self) -> Iterable[str]: + """Get extras from the egg-info directory.""" + known_extras = {""} + for entry in self._iter_requires_txt_entries(): + extra = canonicalize_name(entry.extra) + if extra in known_extras: + continue + known_extras.add(extra) + yield extra + + def _iter_egg_info_dependencies(self) -> Iterable[str]: + """Get distribution dependencies from the egg-info directory. + + To ease parsing, this converts a legacy dependency entry into a PEP 508 + requirement string. Like ``_iter_requires_txt_entries()``, there is code + in ``importlib.metadata`` that does mostly the same, but not do exactly + what we need. + + Namely, ``importlib.metadata`` does not normalize the extra name before + putting it into the requirement string, which causes marker comparison + to fail because the dist-info format do normalize. This is consistent in + all currently available PEP 517 backends, although not standardized. + """ + for entry in self._iter_requires_txt_entries(): + extra = canonicalize_name(entry.extra) + if extra and entry.marker: + marker = f'({entry.marker}) and extra == "{extra}"' + elif extra: + marker = f'extra == "{extra}"' + elif entry.marker: + marker = entry.marker + else: + marker = "" + if marker: + yield f"{entry.requirement} ; {marker}" + else: + yield entry.requirement + + def _add_egg_info_requires(self, metadata: email.message.Message) -> None: + """Add egg-info requires.txt information to the metadata.""" + if not metadata.get_all("Requires-Dist"): + for dep in self._iter_egg_info_dependencies(): + metadata["Requires-Dist"] = dep + if not metadata.get_all("Provides-Extra"): + for extra in self._iter_egg_info_extras(): + metadata["Provides-Extra"] = extra + + +class BaseEnvironment: + """An environment containing distributions to introspect.""" + + @classmethod + def default(cls) -> "BaseEnvironment": + raise NotImplementedError() + + @classmethod + def from_paths(cls, paths: Optional[List[str]]) -> "BaseEnvironment": + raise NotImplementedError() + + def get_distribution(self, name: str) -> Optional["BaseDistribution"]: + """Given a requirement name, return the installed distributions. + + The name may not be normalized. The implementation must canonicalize + it for lookup. + """ + raise NotImplementedError() + + def _iter_distributions(self) -> Iterator["BaseDistribution"]: + """Iterate through installed distributions. + + This function should be implemented by subclass, but never called + directly. Use the public ``iter_distribution()`` instead, which + implements additional logic to make sure the distributions are valid. + """ + raise NotImplementedError() + + def iter_all_distributions(self) -> Iterator[BaseDistribution]: + """Iterate through all installed distributions without any filtering.""" + for dist in self._iter_distributions(): + # Make sure the distribution actually comes from a valid Python + # packaging distribution. Pip's AdjacentTempDirectory leaves folders + # e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The + # valid project name pattern is taken from PEP 508. + project_name_valid = re.match( + r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", + dist.canonical_name, + flags=re.IGNORECASE, + ) + if not project_name_valid: + logger.warning( + "Ignoring invalid distribution %s (%s)", + dist.canonical_name, + dist.location, + ) + continue + yield dist + + def iter_installed_distributions( + self, + local_only: bool = True, + skip: Container[str] = stdlib_pkgs, + include_editables: bool = True, + editables_only: bool = False, + user_only: bool = False, + ) -> Iterator[BaseDistribution]: + """Return a list of installed distributions. + + This is based on ``iter_all_distributions()`` with additional filtering + options. Note that ``iter_installed_distributions()`` without arguments + is *not* equal to ``iter_all_distributions()``, since some of the + configurations exclude packages by default. + + :param local_only: If True (default), only return installations + local to the current virtualenv, if in a virtualenv. + :param skip: An iterable of canonicalized project names to ignore; + defaults to ``stdlib_pkgs``. + :param include_editables: If False, don't report editables. + :param editables_only: If True, only report editables. + :param user_only: If True, only report installations in the user + site directory. + """ + it = self.iter_all_distributions() + if local_only: + it = (d for d in it if d.local) + if not include_editables: + it = (d for d in it if not d.editable) + if editables_only: + it = (d for d in it if d.editable) + if user_only: + it = (d for d in it if d.in_usersite) + return (d for d in it if d.canonical_name not in skip) + + +class Wheel(Protocol): + location: str + + def as_zipfile(self) -> zipfile.ZipFile: + raise NotImplementedError() + + +class FilesystemWheel(Wheel): + def __init__(self, location: str) -> None: + self.location = location + + def as_zipfile(self) -> zipfile.ZipFile: + return zipfile.ZipFile(self.location, allowZip64=True) + + +class MemoryWheel(Wheel): + def __init__(self, location: str, stream: IO[bytes]) -> None: + self.location = location + self.stream = stream + + def as_zipfile(self) -> zipfile.ZipFile: + return zipfile.ZipFile(self.stream, allowZip64=True) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a779138db1040d3903c2bb66ecb2f52a46879dae --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__init__.py @@ -0,0 +1,6 @@ +from ._dists import Distribution +from ._envs import Environment + +__all__ = ["NAME", "Distribution", "Environment"] + +NAME = "importlib" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bd2d867ca7febcf982dca081c2a231bc79d8466 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/_compat.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f1bdfe3edbc4fcc8137a1267d11ad5cbd4ed9ba Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/_compat.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/_dists.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/_dists.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e29e67a78bcd45b49d374ff52765b8dcdf0b9423 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/_dists.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/_envs.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/_envs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..934e10435bb3fc10d61bdd8356e3f0db5dac09d9 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/__pycache__/_envs.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/_compat.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1e815cdbdf517ec8b3565d7dafb7e67ce1705c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/_compat.py @@ -0,0 +1,85 @@ +import importlib.metadata +import os +from typing import Any, Optional, Protocol, Tuple, cast + +from pip._vendor.packaging.utils import NormalizedName, canonicalize_name + + +class BadMetadata(ValueError): + def __init__(self, dist: importlib.metadata.Distribution, *, reason: str) -> None: + self.dist = dist + self.reason = reason + + def __str__(self) -> str: + return f"Bad metadata in {self.dist} ({self.reason})" + + +class BasePath(Protocol): + """A protocol that various path objects conform. + + This exists because importlib.metadata uses both ``pathlib.Path`` and + ``zipfile.Path``, and we need a common base for type hints (Union does not + work well since ``zipfile.Path`` is too new for our linter setup). + + This does not mean to be exhaustive, but only contains things that present + in both classes *that we need*. + """ + + @property + def name(self) -> str: + raise NotImplementedError() + + @property + def parent(self) -> "BasePath": + raise NotImplementedError() + + +def get_info_location(d: importlib.metadata.Distribution) -> Optional[BasePath]: + """Find the path to the distribution's metadata directory. + + HACK: This relies on importlib.metadata's private ``_path`` attribute. Not + all distributions exist on disk, so importlib.metadata is correct to not + expose the attribute as public. But pip's code base is old and not as clean, + so we do this to avoid having to rewrite too many things. Hopefully we can + eliminate this some day. + """ + return getattr(d, "_path", None) + + +def parse_name_and_version_from_info_directory( + dist: importlib.metadata.Distribution, +) -> Tuple[Optional[str], Optional[str]]: + """Get a name and version from the metadata directory name. + + This is much faster than reading distribution metadata. + """ + info_location = get_info_location(dist) + if info_location is None: + return None, None + + stem, suffix = os.path.splitext(info_location.name) + if suffix == ".dist-info": + name, sep, version = stem.partition("-") + if sep: + return name, version + + if suffix == ".egg-info": + name = stem.split("-", 1)[0] + return name, None + + return None, None + + +def get_dist_canonical_name(dist: importlib.metadata.Distribution) -> NormalizedName: + """Get the distribution's normalized name. + + The ``name`` attribute is only available in Python 3.10 or later. We are + targeting exactly that, but Mypy does not know this. + """ + if name := parse_name_and_version_from_info_directory(dist)[0]: + return canonicalize_name(name) + + name = cast(Any, dist).name + if not isinstance(name, str): + raise BadMetadata(dist, reason="invalid metadata entry 'name'") + return canonicalize_name(name) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/_dists.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/_dists.py new file mode 100644 index 0000000000000000000000000000000000000000..d220b616e2860407336cfaed32c6d5972e7688dd --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/_dists.py @@ -0,0 +1,228 @@ +import email.message +import importlib.metadata +import pathlib +import zipfile +from os import PathLike +from typing import ( + Collection, + Dict, + Iterable, + Iterator, + Mapping, + Optional, + Sequence, + Union, + cast, +) + +from pip._vendor.packaging.requirements import Requirement +from pip._vendor.packaging.utils import NormalizedName, canonicalize_name +from pip._vendor.packaging.version import Version +from pip._vendor.packaging.version import parse as parse_version + +from pip._internal.exceptions import InvalidWheel, UnsupportedWheel +from pip._internal.metadata.base import ( + BaseDistribution, + BaseEntryPoint, + InfoPath, + Wheel, +) +from pip._internal.utils.misc import normalize_path +from pip._internal.utils.packaging import get_requirement +from pip._internal.utils.temp_dir import TempDirectory +from pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file + +from ._compat import ( + BasePath, + get_dist_canonical_name, + parse_name_and_version_from_info_directory, +) + + +class WheelDistribution(importlib.metadata.Distribution): + """An ``importlib.metadata.Distribution`` read from a wheel. + + Although ``importlib.metadata.PathDistribution`` accepts ``zipfile.Path``, + its implementation is too "lazy" for pip's needs (we can't keep the ZipFile + handle open for the entire lifetime of the distribution object). + + This implementation eagerly reads the entire metadata directory into the + memory instead, and operates from that. + """ + + def __init__( + self, + files: Mapping[pathlib.PurePosixPath, bytes], + info_location: pathlib.PurePosixPath, + ) -> None: + self._files = files + self.info_location = info_location + + @classmethod + def from_zipfile( + cls, + zf: zipfile.ZipFile, + name: str, + location: str, + ) -> "WheelDistribution": + info_dir, _ = parse_wheel(zf, name) + paths = ( + (name, pathlib.PurePosixPath(name.split("/", 1)[-1])) + for name in zf.namelist() + if name.startswith(f"{info_dir}/") + ) + files = { + relpath: read_wheel_metadata_file(zf, fullpath) + for fullpath, relpath in paths + } + info_location = pathlib.PurePosixPath(location, info_dir) + return cls(files, info_location) + + def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]: + # Only allow iterating through the metadata directory. + if pathlib.PurePosixPath(str(path)) in self._files: + return iter(self._files) + raise FileNotFoundError(path) + + def read_text(self, filename: str) -> Optional[str]: + try: + data = self._files[pathlib.PurePosixPath(filename)] + except KeyError: + return None + try: + text = data.decode("utf-8") + except UnicodeDecodeError as e: + wheel = self.info_location.parent + error = f"Error decoding metadata for {wheel}: {e} in {filename} file" + raise UnsupportedWheel(error) + return text + + def locate_file(self, path: Union[str, "PathLike[str]"]) -> pathlib.Path: + # This method doesn't make sense for our in-memory wheel, but the API + # requires us to define it. + raise NotImplementedError + + +class Distribution(BaseDistribution): + def __init__( + self, + dist: importlib.metadata.Distribution, + info_location: Optional[BasePath], + installed_location: Optional[BasePath], + ) -> None: + self._dist = dist + self._info_location = info_location + self._installed_location = installed_location + + @classmethod + def from_directory(cls, directory: str) -> BaseDistribution: + info_location = pathlib.Path(directory) + dist = importlib.metadata.Distribution.at(info_location) + return cls(dist, info_location, info_location.parent) + + @classmethod + def from_metadata_file_contents( + cls, + metadata_contents: bytes, + filename: str, + project_name: str, + ) -> BaseDistribution: + # Generate temp dir to contain the metadata file, and write the file contents. + temp_dir = pathlib.Path( + TempDirectory(kind="metadata", globally_managed=True).path + ) + metadata_path = temp_dir / "METADATA" + metadata_path.write_bytes(metadata_contents) + # Construct dist pointing to the newly created directory. + dist = importlib.metadata.Distribution.at(metadata_path.parent) + return cls(dist, metadata_path.parent, None) + + @classmethod + def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution: + try: + with wheel.as_zipfile() as zf: + dist = WheelDistribution.from_zipfile(zf, name, wheel.location) + except zipfile.BadZipFile as e: + raise InvalidWheel(wheel.location, name) from e + return cls(dist, dist.info_location, pathlib.PurePosixPath(wheel.location)) + + @property + def location(self) -> Optional[str]: + if self._info_location is None: + return None + return str(self._info_location.parent) + + @property + def info_location(self) -> Optional[str]: + if self._info_location is None: + return None + return str(self._info_location) + + @property + def installed_location(self) -> Optional[str]: + if self._installed_location is None: + return None + return normalize_path(str(self._installed_location)) + + @property + def canonical_name(self) -> NormalizedName: + return get_dist_canonical_name(self._dist) + + @property + def version(self) -> Version: + if version := parse_name_and_version_from_info_directory(self._dist)[1]: + return parse_version(version) + return parse_version(self._dist.version) + + @property + def raw_version(self) -> str: + return self._dist.version + + def is_file(self, path: InfoPath) -> bool: + return self._dist.read_text(str(path)) is not None + + def iter_distutils_script_names(self) -> Iterator[str]: + # A distutils installation is always "flat" (not in e.g. egg form), so + # if this distribution's info location is NOT a pathlib.Path (but e.g. + # zipfile.Path), it can never contain any distutils scripts. + if not isinstance(self._info_location, pathlib.Path): + return + for child in self._info_location.joinpath("scripts").iterdir(): + yield child.name + + def read_text(self, path: InfoPath) -> str: + content = self._dist.read_text(str(path)) + if content is None: + raise FileNotFoundError(path) + return content + + def iter_entry_points(self) -> Iterable[BaseEntryPoint]: + # importlib.metadata's EntryPoint structure satisfies BaseEntryPoint. + return self._dist.entry_points + + def _metadata_impl(self) -> email.message.Message: + # From Python 3.10+, importlib.metadata declares PackageMetadata as the + # return type. This protocol is unfortunately a disaster now and misses + # a ton of fields that we need, including get() and get_payload(). We + # rely on the implementation that the object is actually a Message now, + # until upstream can improve the protocol. (python/cpython#94952) + return cast(email.message.Message, self._dist.metadata) + + def iter_provided_extras(self) -> Iterable[NormalizedName]: + return [ + canonicalize_name(extra) + for extra in self.metadata.get_all("Provides-Extra", []) + ] + + def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]: + contexts: Sequence[Dict[str, str]] = [{"extra": e} for e in extras] + for req_string in self.metadata.get_all("Requires-Dist", []): + # strip() because email.message.Message.get_all() may return a leading \n + # in case a long header was wrapped. + req = get_requirement(req_string.strip()) + if not req.marker: + yield req + elif not extras and req.marker.evaluate({"extra": ""}): + yield req + elif any(req.marker.evaluate(context) for context in contexts): + yield req diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/_envs.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/_envs.py new file mode 100644 index 0000000000000000000000000000000000000000..4d906fd3149f1242db2efa6ed095d5857d61116c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/importlib/_envs.py @@ -0,0 +1,189 @@ +import functools +import importlib.metadata +import logging +import os +import pathlib +import sys +import zipfile +import zipimport +from typing import Iterator, List, Optional, Sequence, Set, Tuple + +from pip._vendor.packaging.utils import NormalizedName, canonicalize_name + +from pip._internal.metadata.base import BaseDistribution, BaseEnvironment +from pip._internal.models.wheel import Wheel +from pip._internal.utils.deprecation import deprecated +from pip._internal.utils.filetypes import WHEEL_EXTENSION + +from ._compat import BadMetadata, BasePath, get_dist_canonical_name, get_info_location +from ._dists import Distribution + +logger = logging.getLogger(__name__) + + +def _looks_like_wheel(location: str) -> bool: + if not location.endswith(WHEEL_EXTENSION): + return False + if not os.path.isfile(location): + return False + if not Wheel.wheel_file_re.match(os.path.basename(location)): + return False + return zipfile.is_zipfile(location) + + +class _DistributionFinder: + """Finder to locate distributions. + + The main purpose of this class is to memoize found distributions' names, so + only one distribution is returned for each package name. At lot of pip code + assumes this (because it is setuptools's behavior), and not doing the same + can potentially cause a distribution in lower precedence path to override a + higher precedence one if the caller is not careful. + + Eventually we probably want to make it possible to see lower precedence + installations as well. It's useful feature, after all. + """ + + FoundResult = Tuple[importlib.metadata.Distribution, Optional[BasePath]] + + def __init__(self) -> None: + self._found_names: Set[NormalizedName] = set() + + def _find_impl(self, location: str) -> Iterator[FoundResult]: + """Find distributions in a location.""" + # Skip looking inside a wheel. Since a package inside a wheel is not + # always valid (due to .data directories etc.), its .dist-info entry + # should not be considered an installed distribution. + if _looks_like_wheel(location): + return + # To know exactly where we find a distribution, we have to feed in the + # paths one by one, instead of dumping the list to importlib.metadata. + for dist in importlib.metadata.distributions(path=[location]): + info_location = get_info_location(dist) + try: + name = get_dist_canonical_name(dist) + except BadMetadata as e: + logger.warning("Skipping %s due to %s", info_location, e.reason) + continue + if name in self._found_names: + continue + self._found_names.add(name) + yield dist, info_location + + def find(self, location: str) -> Iterator[BaseDistribution]: + """Find distributions in a location. + + The path can be either a directory, or a ZIP archive. + """ + for dist, info_location in self._find_impl(location): + if info_location is None: + installed_location: Optional[BasePath] = None + else: + installed_location = info_location.parent + yield Distribution(dist, info_location, installed_location) + + def find_linked(self, location: str) -> Iterator[BaseDistribution]: + """Read location in egg-link files and return distributions in there. + + The path should be a directory; otherwise this returns nothing. This + follows how setuptools does this for compatibility. The first non-empty + line in the egg-link is read as a path (resolved against the egg-link's + containing directory if relative). Distributions found at that linked + location are returned. + """ + path = pathlib.Path(location) + if not path.is_dir(): + return + for child in path.iterdir(): + if child.suffix != ".egg-link": + continue + with child.open() as f: + lines = (line.strip() for line in f) + target_rel = next((line for line in lines if line), "") + if not target_rel: + continue + target_location = str(path.joinpath(target_rel)) + for dist, info_location in self._find_impl(target_location): + yield Distribution(dist, info_location, path) + + def _find_eggs_in_dir(self, location: str) -> Iterator[BaseDistribution]: + from pip._vendor.pkg_resources import find_distributions + + from pip._internal.metadata import pkg_resources as legacy + + with os.scandir(location) as it: + for entry in it: + if not entry.name.endswith(".egg"): + continue + for dist in find_distributions(entry.path): + yield legacy.Distribution(dist) + + def _find_eggs_in_zip(self, location: str) -> Iterator[BaseDistribution]: + from pip._vendor.pkg_resources import find_eggs_in_zip + + from pip._internal.metadata import pkg_resources as legacy + + try: + importer = zipimport.zipimporter(location) + except zipimport.ZipImportError: + return + for dist in find_eggs_in_zip(importer, location): + yield legacy.Distribution(dist) + + def find_eggs(self, location: str) -> Iterator[BaseDistribution]: + """Find eggs in a location. + + This actually uses the old *pkg_resources* backend. We likely want to + deprecate this so we can eventually remove the *pkg_resources* + dependency entirely. Before that, this should first emit a deprecation + warning for some versions when using the fallback since importing + *pkg_resources* is slow for those who don't need it. + """ + if os.path.isdir(location): + yield from self._find_eggs_in_dir(location) + if zipfile.is_zipfile(location): + yield from self._find_eggs_in_zip(location) + + +@functools.lru_cache(maxsize=None) # Warn a distribution exactly once. +def _emit_egg_deprecation(location: Optional[str]) -> None: + deprecated( + reason=f"Loading egg at {location} is deprecated.", + replacement="to use pip for package installation", + gone_in="25.1", + issue=12330, + ) + + +class Environment(BaseEnvironment): + def __init__(self, paths: Sequence[str]) -> None: + self._paths = paths + + @classmethod + def default(cls) -> BaseEnvironment: + return cls(sys.path) + + @classmethod + def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment: + if paths is None: + return cls(sys.path) + return cls(paths) + + def _iter_distributions(self) -> Iterator[BaseDistribution]: + finder = _DistributionFinder() + for location in self._paths: + yield from finder.find(location) + for dist in finder.find_eggs(location): + _emit_egg_deprecation(dist.location) + yield dist + # This must go last because that's how pkg_resources tie-breaks. + yield from finder.find_linked(location) + + def get_distribution(self, name: str) -> Optional[BaseDistribution]: + canonical_name = canonicalize_name(name) + matches = ( + distribution + for distribution in self.iter_all_distributions() + if distribution.canonical_name == canonical_name + ) + return next(matches, None) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/pkg_resources.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/pkg_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..4ea84f93a6fb8f2d04230d70491eac7809672031 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/metadata/pkg_resources.py @@ -0,0 +1,301 @@ +import email.message +import email.parser +import logging +import os +import zipfile +from typing import ( + Collection, + Iterable, + Iterator, + List, + Mapping, + NamedTuple, + Optional, +) + +from pip._vendor import pkg_resources +from pip._vendor.packaging.requirements import Requirement +from pip._vendor.packaging.utils import NormalizedName, canonicalize_name +from pip._vendor.packaging.version import Version +from pip._vendor.packaging.version import parse as parse_version + +from pip._internal.exceptions import InvalidWheel, NoneMetadataError, UnsupportedWheel +from pip._internal.utils.egg_link import egg_link_path_from_location +from pip._internal.utils.misc import display_path, normalize_path +from pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file + +from .base import ( + BaseDistribution, + BaseEntryPoint, + BaseEnvironment, + InfoPath, + Wheel, +) + +__all__ = ["NAME", "Distribution", "Environment"] + +logger = logging.getLogger(__name__) + +NAME = "pkg_resources" + + +class EntryPoint(NamedTuple): + name: str + value: str + group: str + + +class InMemoryMetadata: + """IMetadataProvider that reads metadata files from a dictionary. + + This also maps metadata decoding exceptions to our internal exception type. + """ + + def __init__(self, metadata: Mapping[str, bytes], wheel_name: str) -> None: + self._metadata = metadata + self._wheel_name = wheel_name + + def has_metadata(self, name: str) -> bool: + return name in self._metadata + + def get_metadata(self, name: str) -> str: + try: + return self._metadata[name].decode() + except UnicodeDecodeError as e: + # Augment the default error with the origin of the file. + raise UnsupportedWheel( + f"Error decoding metadata for {self._wheel_name}: {e} in {name} file" + ) + + def get_metadata_lines(self, name: str) -> Iterable[str]: + return pkg_resources.yield_lines(self.get_metadata(name)) + + def metadata_isdir(self, name: str) -> bool: + return False + + def metadata_listdir(self, name: str) -> List[str]: + return [] + + def run_script(self, script_name: str, namespace: str) -> None: + pass + + +class Distribution(BaseDistribution): + def __init__(self, dist: pkg_resources.Distribution) -> None: + self._dist = dist + # This is populated lazily, to avoid loading metadata for all possible + # distributions eagerly. + self.__extra_mapping: Optional[Mapping[NormalizedName, str]] = None + + @property + def _extra_mapping(self) -> Mapping[NormalizedName, str]: + if self.__extra_mapping is None: + self.__extra_mapping = { + canonicalize_name(extra): extra for extra in self._dist.extras + } + + return self.__extra_mapping + + @classmethod + def from_directory(cls, directory: str) -> BaseDistribution: + dist_dir = directory.rstrip(os.sep) + + # Build a PathMetadata object, from path to metadata. :wink: + base_dir, dist_dir_name = os.path.split(dist_dir) + metadata = pkg_resources.PathMetadata(base_dir, dist_dir) + + # Determine the correct Distribution object type. + if dist_dir.endswith(".egg-info"): + dist_cls = pkg_resources.Distribution + dist_name = os.path.splitext(dist_dir_name)[0] + else: + assert dist_dir.endswith(".dist-info") + dist_cls = pkg_resources.DistInfoDistribution + dist_name = os.path.splitext(dist_dir_name)[0].split("-")[0] + + dist = dist_cls(base_dir, project_name=dist_name, metadata=metadata) + return cls(dist) + + @classmethod + def from_metadata_file_contents( + cls, + metadata_contents: bytes, + filename: str, + project_name: str, + ) -> BaseDistribution: + metadata_dict = { + "METADATA": metadata_contents, + } + dist = pkg_resources.DistInfoDistribution( + location=filename, + metadata=InMemoryMetadata(metadata_dict, filename), + project_name=project_name, + ) + return cls(dist) + + @classmethod + def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution: + try: + with wheel.as_zipfile() as zf: + info_dir, _ = parse_wheel(zf, name) + metadata_dict = { + path.split("/", 1)[-1]: read_wheel_metadata_file(zf, path) + for path in zf.namelist() + if path.startswith(f"{info_dir}/") + } + except zipfile.BadZipFile as e: + raise InvalidWheel(wheel.location, name) from e + except UnsupportedWheel as e: + raise UnsupportedWheel(f"{name} has an invalid wheel, {e}") + dist = pkg_resources.DistInfoDistribution( + location=wheel.location, + metadata=InMemoryMetadata(metadata_dict, wheel.location), + project_name=name, + ) + return cls(dist) + + @property + def location(self) -> Optional[str]: + return self._dist.location + + @property + def installed_location(self) -> Optional[str]: + egg_link = egg_link_path_from_location(self.raw_name) + if egg_link: + location = egg_link + elif self.location: + location = self.location + else: + return None + return normalize_path(location) + + @property + def info_location(self) -> Optional[str]: + return self._dist.egg_info + + @property + def installed_by_distutils(self) -> bool: + # A distutils-installed distribution is provided by FileMetadata. This + # provider has a "path" attribute not present anywhere else. Not the + # best introspection logic, but pip has been doing this for a long time. + try: + return bool(self._dist._provider.path) + except AttributeError: + return False + + @property + def canonical_name(self) -> NormalizedName: + return canonicalize_name(self._dist.project_name) + + @property + def version(self) -> Version: + return parse_version(self._dist.version) + + @property + def raw_version(self) -> str: + return self._dist.version + + def is_file(self, path: InfoPath) -> bool: + return self._dist.has_metadata(str(path)) + + def iter_distutils_script_names(self) -> Iterator[str]: + yield from self._dist.metadata_listdir("scripts") + + def read_text(self, path: InfoPath) -> str: + name = str(path) + if not self._dist.has_metadata(name): + raise FileNotFoundError(name) + content = self._dist.get_metadata(name) + if content is None: + raise NoneMetadataError(self, name) + return content + + def iter_entry_points(self) -> Iterable[BaseEntryPoint]: + for group, entries in self._dist.get_entry_map().items(): + for name, entry_point in entries.items(): + name, _, value = str(entry_point).partition("=") + yield EntryPoint(name=name.strip(), value=value.strip(), group=group) + + def _metadata_impl(self) -> email.message.Message: + """ + :raises NoneMetadataError: if the distribution reports `has_metadata()` + True but `get_metadata()` returns None. + """ + if isinstance(self._dist, pkg_resources.DistInfoDistribution): + metadata_name = "METADATA" + else: + metadata_name = "PKG-INFO" + try: + metadata = self.read_text(metadata_name) + except FileNotFoundError: + if self.location: + displaying_path = display_path(self.location) + else: + displaying_path = repr(self.location) + logger.warning("No metadata found in %s", displaying_path) + metadata = "" + feed_parser = email.parser.FeedParser() + feed_parser.feed(metadata) + return feed_parser.close() + + def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]: + if extras: + relevant_extras = set(self._extra_mapping) & set( + map(canonicalize_name, extras) + ) + extras = [self._extra_mapping[extra] for extra in relevant_extras] + return self._dist.requires(extras) + + def iter_provided_extras(self) -> Iterable[NormalizedName]: + return self._extra_mapping.keys() + + +class Environment(BaseEnvironment): + def __init__(self, ws: pkg_resources.WorkingSet) -> None: + self._ws = ws + + @classmethod + def default(cls) -> BaseEnvironment: + return cls(pkg_resources.working_set) + + @classmethod + def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment: + return cls(pkg_resources.WorkingSet(paths)) + + def _iter_distributions(self) -> Iterator[BaseDistribution]: + for dist in self._ws: + yield Distribution(dist) + + def _search_distribution(self, name: str) -> Optional[BaseDistribution]: + """Find a distribution matching the ``name`` in the environment. + + This searches from *all* distributions available in the environment, to + match the behavior of ``pkg_resources.get_distribution()``. + """ + canonical_name = canonicalize_name(name) + for dist in self.iter_all_distributions(): + if dist.canonical_name == canonical_name: + return dist + return None + + def get_distribution(self, name: str) -> Optional[BaseDistribution]: + # Search the distribution by looking through the working set. + dist = self._search_distribution(name) + if dist: + return dist + + # If distribution could not be found, call working_set.require to + # update the working set, and try to find the distribution again. + # This might happen for e.g. when you install a package twice, once + # using setup.py develop and again using setup.py install. Now when + # running pip uninstall twice, the package gets removed from the + # working set in the first uninstall, so we have to populate the + # working set again so that pip knows about it and the packages gets + # picked up and is successfully uninstalled the second time too. + try: + # We didn't pass in any version specifiers, so this can never + # raise pkg_resources.VersionConflict. + self._ws.require(name) + except pkg_resources.DistributionNotFound: + return None + return self._search_distribution(name) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7855226e4b500142deef8fb247cd33a9a991d122 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__init__.py @@ -0,0 +1,2 @@ +"""A package that contains models that represent entities. +""" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5774c16331dd7bbb233bdf4bd8439cd444da2357 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/candidate.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/candidate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9011a8860af2e024cea2f29c9abd4f475d954843 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/candidate.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/direct_url.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/direct_url.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c55c418aa8be0a3aded713a62121d8bdb5aa2b6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/direct_url.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/format_control.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/format_control.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5eb41645e076c9f3fae6de652584e7e199054ae Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/format_control.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/index.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/index.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..331e063979e0ce68993f1b7dcfcd2d8a7daa4f2c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/index.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/installation_report.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/installation_report.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72d2255f7ef10d5cd656c5ee77ea91003208bfe6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/installation_report.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/link.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/link.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b277a2a568106792dfd80f3570a22bb9b8339588 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/link.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/scheme.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/scheme.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbc6cf4cf4ac8bc81cddc427b03a13b91db4b4d8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/scheme.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/search_scope.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/search_scope.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdb5db698f539d60e495e1be96127c88eb9e660d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/search_scope.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/selection_prefs.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/selection_prefs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d2486d105613b948d8d1d96ba4dcd16eb020ab1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/selection_prefs.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/target_python.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/target_python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d36397d79a19b0f88f201398a5610eae2d1832fd Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/target_python.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/wheel.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/wheel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6196c78f1cccf0d5fbc8f238ccb9cf38413cda1e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/__pycache__/wheel.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/candidate.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/candidate.py new file mode 100644 index 0000000000000000000000000000000000000000..f27f283154ac5aa55d52ccac754138b36341ff6b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/candidate.py @@ -0,0 +1,25 @@ +from dataclasses import dataclass + +from pip._vendor.packaging.version import Version +from pip._vendor.packaging.version import parse as parse_version + +from pip._internal.models.link import Link + + +@dataclass(frozen=True) +class InstallationCandidate: + """Represents a potential "candidate" for installation.""" + + __slots__ = ["name", "version", "link"] + + name: str + version: Version + link: Link + + def __init__(self, name: str, version: str, link: Link) -> None: + object.__setattr__(self, "name", name) + object.__setattr__(self, "version", parse_version(version)) + object.__setattr__(self, "link", link) + + def __str__(self) -> str: + return f"{self.name!r} candidate (version {self.version} at {self.link})" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/direct_url.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/direct_url.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5ec8d4aa9b02b7264f7a5a0222e7e1fe215ad0 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/direct_url.py @@ -0,0 +1,224 @@ +""" PEP 610 """ + +import json +import re +import urllib.parse +from dataclasses import dataclass +from typing import Any, ClassVar, Dict, Iterable, Optional, Type, TypeVar, Union + +__all__ = [ + "DirectUrl", + "DirectUrlValidationError", + "DirInfo", + "ArchiveInfo", + "VcsInfo", +] + +T = TypeVar("T") + +DIRECT_URL_METADATA_NAME = "direct_url.json" +ENV_VAR_RE = re.compile(r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$") + + +class DirectUrlValidationError(Exception): + pass + + +def _get( + d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None +) -> Optional[T]: + """Get value from dictionary and verify expected type.""" + if key not in d: + return default + value = d[key] + if not isinstance(value, expected_type): + raise DirectUrlValidationError( + f"{value!r} has unexpected type for {key} (expected {expected_type})" + ) + return value + + +def _get_required( + d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None +) -> T: + value = _get(d, expected_type, key, default) + if value is None: + raise DirectUrlValidationError(f"{key} must have a value") + return value + + +def _exactly_one_of(infos: Iterable[Optional["InfoType"]]) -> "InfoType": + infos = [info for info in infos if info is not None] + if not infos: + raise DirectUrlValidationError( + "missing one of archive_info, dir_info, vcs_info" + ) + if len(infos) > 1: + raise DirectUrlValidationError( + "more than one of archive_info, dir_info, vcs_info" + ) + assert infos[0] is not None + return infos[0] + + +def _filter_none(**kwargs: Any) -> Dict[str, Any]: + """Make dict excluding None values.""" + return {k: v for k, v in kwargs.items() if v is not None} + + +@dataclass +class VcsInfo: + name: ClassVar = "vcs_info" + + vcs: str + commit_id: str + requested_revision: Optional[str] = None + + @classmethod + def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional["VcsInfo"]: + if d is None: + return None + return cls( + vcs=_get_required(d, str, "vcs"), + commit_id=_get_required(d, str, "commit_id"), + requested_revision=_get(d, str, "requested_revision"), + ) + + def _to_dict(self) -> Dict[str, Any]: + return _filter_none( + vcs=self.vcs, + requested_revision=self.requested_revision, + commit_id=self.commit_id, + ) + + +class ArchiveInfo: + name = "archive_info" + + def __init__( + self, + hash: Optional[str] = None, + hashes: Optional[Dict[str, str]] = None, + ) -> None: + # set hashes before hash, since the hash setter will further populate hashes + self.hashes = hashes + self.hash = hash + + @property + def hash(self) -> Optional[str]: + return self._hash + + @hash.setter + def hash(self, value: Optional[str]) -> None: + if value is not None: + # Auto-populate the hashes key to upgrade to the new format automatically. + # We don't back-populate the legacy hash key from hashes. + try: + hash_name, hash_value = value.split("=", 1) + except ValueError: + raise DirectUrlValidationError( + f"invalid archive_info.hash format: {value!r}" + ) + if self.hashes is None: + self.hashes = {hash_name: hash_value} + elif hash_name not in self.hashes: + self.hashes = self.hashes.copy() + self.hashes[hash_name] = hash_value + self._hash = value + + @classmethod + def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional["ArchiveInfo"]: + if d is None: + return None + return cls(hash=_get(d, str, "hash"), hashes=_get(d, dict, "hashes")) + + def _to_dict(self) -> Dict[str, Any]: + return _filter_none(hash=self.hash, hashes=self.hashes) + + +@dataclass +class DirInfo: + name: ClassVar = "dir_info" + + editable: bool = False + + @classmethod + def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional["DirInfo"]: + if d is None: + return None + return cls(editable=_get_required(d, bool, "editable", default=False)) + + def _to_dict(self) -> Dict[str, Any]: + return _filter_none(editable=self.editable or None) + + +InfoType = Union[ArchiveInfo, DirInfo, VcsInfo] + + +@dataclass +class DirectUrl: + url: str + info: InfoType + subdirectory: Optional[str] = None + + def _remove_auth_from_netloc(self, netloc: str) -> str: + if "@" not in netloc: + return netloc + user_pass, netloc_no_user_pass = netloc.split("@", 1) + if ( + isinstance(self.info, VcsInfo) + and self.info.vcs == "git" + and user_pass == "git" + ): + return netloc + if ENV_VAR_RE.match(user_pass): + return netloc + return netloc_no_user_pass + + @property + def redacted_url(self) -> str: + """url with user:password part removed unless it is formed with + environment variables as specified in PEP 610, or it is ``git`` + in the case of a git URL. + """ + purl = urllib.parse.urlsplit(self.url) + netloc = self._remove_auth_from_netloc(purl.netloc) + surl = urllib.parse.urlunsplit( + (purl.scheme, netloc, purl.path, purl.query, purl.fragment) + ) + return surl + + def validate(self) -> None: + self.from_dict(self.to_dict()) + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "DirectUrl": + return DirectUrl( + url=_get_required(d, str, "url"), + subdirectory=_get(d, str, "subdirectory"), + info=_exactly_one_of( + [ + ArchiveInfo._from_dict(_get(d, dict, "archive_info")), + DirInfo._from_dict(_get(d, dict, "dir_info")), + VcsInfo._from_dict(_get(d, dict, "vcs_info")), + ] + ), + ) + + def to_dict(self) -> Dict[str, Any]: + res = _filter_none( + url=self.redacted_url, + subdirectory=self.subdirectory, + ) + res[self.info.name] = self.info._to_dict() + return res + + @classmethod + def from_json(cls, s: str) -> "DirectUrl": + return cls.from_dict(json.loads(s)) + + def to_json(self) -> str: + return json.dumps(self.to_dict(), sort_keys=True) + + def is_local_editable(self) -> bool: + return isinstance(self.info, DirInfo) and self.info.editable diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/format_control.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/format_control.py new file mode 100644 index 0000000000000000000000000000000000000000..ccd11272c030c2d067e1bb6d90fc744c7379a923 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/format_control.py @@ -0,0 +1,78 @@ +from typing import FrozenSet, Optional, Set + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.exceptions import CommandError + + +class FormatControl: + """Helper for managing formats from which a package can be installed.""" + + __slots__ = ["no_binary", "only_binary"] + + def __init__( + self, + no_binary: Optional[Set[str]] = None, + only_binary: Optional[Set[str]] = None, + ) -> None: + if no_binary is None: + no_binary = set() + if only_binary is None: + only_binary = set() + + self.no_binary = no_binary + self.only_binary = only_binary + + def __eq__(self, other: object) -> bool: + if not isinstance(other, self.__class__): + return NotImplemented + + if self.__slots__ != other.__slots__: + return False + + return all(getattr(self, k) == getattr(other, k) for k in self.__slots__) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.no_binary}, {self.only_binary})" + + @staticmethod + def handle_mutual_excludes(value: str, target: Set[str], other: Set[str]) -> None: + if value.startswith("-"): + raise CommandError( + "--no-binary / --only-binary option requires 1 argument." + ) + new = value.split(",") + while ":all:" in new: + other.clear() + target.clear() + target.add(":all:") + del new[: new.index(":all:") + 1] + # Without a none, we want to discard everything as :all: covers it + if ":none:" not in new: + return + for name in new: + if name == ":none:": + target.clear() + continue + name = canonicalize_name(name) + other.discard(name) + target.add(name) + + def get_allowed_formats(self, canonical_name: str) -> FrozenSet[str]: + result = {"binary", "source"} + if canonical_name in self.only_binary: + result.discard("source") + elif canonical_name in self.no_binary: + result.discard("binary") + elif ":all:" in self.only_binary: + result.discard("source") + elif ":all:" in self.no_binary: + result.discard("binary") + return frozenset(result) + + def disallow_binaries(self) -> None: + self.handle_mutual_excludes( + ":all:", + self.no_binary, + self.only_binary, + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/index.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/index.py new file mode 100644 index 0000000000000000000000000000000000000000..b94c32511f0cda2363bfc4f29c9c8bfcc7101f9b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/index.py @@ -0,0 +1,28 @@ +import urllib.parse + + +class PackageIndex: + """Represents a Package Index and provides easier access to endpoints""" + + __slots__ = ["url", "netloc", "simple_url", "pypi_url", "file_storage_domain"] + + def __init__(self, url: str, file_storage_domain: str) -> None: + super().__init__() + self.url = url + self.netloc = urllib.parse.urlsplit(url).netloc + self.simple_url = self._url_for_path("simple") + self.pypi_url = self._url_for_path("pypi") + + # This is part of a temporary hack used to block installs of PyPI + # packages which depend on external urls only necessary until PyPI can + # block such packages themselves + self.file_storage_domain = file_storage_domain + + def _url_for_path(self, path: str) -> str: + return urllib.parse.urljoin(self.url, path) + + +PyPI = PackageIndex("https://pypi.org/", file_storage_domain="files.pythonhosted.org") +TestPyPI = PackageIndex( + "https://test.pypi.org/", file_storage_domain="test-files.pythonhosted.org" +) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/installation_report.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/installation_report.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c6330df32bd2b57c885156cb7f8c0c8c3e3741 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/installation_report.py @@ -0,0 +1,56 @@ +from typing import Any, Dict, Sequence + +from pip._vendor.packaging.markers import default_environment + +from pip import __version__ +from pip._internal.req.req_install import InstallRequirement + + +class InstallationReport: + def __init__(self, install_requirements: Sequence[InstallRequirement]): + self._install_requirements = install_requirements + + @classmethod + def _install_req_to_dict(cls, ireq: InstallRequirement) -> Dict[str, Any]: + assert ireq.download_info, f"No download_info for {ireq}" + res = { + # PEP 610 json for the download URL. download_info.archive_info.hashes may + # be absent when the requirement was installed from the wheel cache + # and the cache entry was populated by an older pip version that did not + # record origin.json. + "download_info": ireq.download_info.to_dict(), + # is_direct is true if the requirement was a direct URL reference (which + # includes editable requirements), and false if the requirement was + # downloaded from a PEP 503 index or --find-links. + "is_direct": ireq.is_direct, + # is_yanked is true if the requirement was yanked from the index, but + # was still selected by pip to conform to PEP 592. + "is_yanked": ireq.link.is_yanked if ireq.link else False, + # requested is true if the requirement was specified by the user (aka + # top level requirement), and false if it was installed as a dependency of a + # requirement. https://peps.python.org/pep-0376/#requested + "requested": ireq.user_supplied, + # PEP 566 json encoding for metadata + # https://www.python.org/dev/peps/pep-0566/#json-compatible-metadata + "metadata": ireq.get_dist().metadata_dict, + } + if ireq.user_supplied and ireq.extras: + # For top level requirements, the list of requested extras, if any. + res["requested_extras"] = sorted(ireq.extras) + return res + + def to_dict(self) -> Dict[str, Any]: + return { + "version": "1", + "pip_version": __version__, + "install": [ + self._install_req_to_dict(ireq) for ireq in self._install_requirements + ], + # https://peps.python.org/pep-0508/#environment-markers + # TODO: currently, the resolver uses the default environment to evaluate + # environment markers, so that is what we report here. In the future, it + # should also take into account options such as --python-version or + # --platform, perhaps under the form of an environment_override field? + # https://github.com/pypa/pip/issues/11198 + "environment": default_environment(), + } diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/link.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/link.py new file mode 100644 index 0000000000000000000000000000000000000000..27ad016090c565af4375d9a236d363c2be62532c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/link.py @@ -0,0 +1,604 @@ +import functools +import itertools +import logging +import os +import posixpath +import re +import urllib.parse +from dataclasses import dataclass +from typing import ( + TYPE_CHECKING, + Any, + Dict, + List, + Mapping, + NamedTuple, + Optional, + Tuple, + Union, +) + +from pip._internal.utils.deprecation import deprecated +from pip._internal.utils.filetypes import WHEEL_EXTENSION +from pip._internal.utils.hashes import Hashes +from pip._internal.utils.misc import ( + pairwise, + redact_auth_from_url, + split_auth_from_netloc, + splitext, +) +from pip._internal.utils.urls import path_to_url, url_to_path + +if TYPE_CHECKING: + from pip._internal.index.collector import IndexContent + +logger = logging.getLogger(__name__) + + +# Order matters, earlier hashes have a precedence over later hashes for what +# we will pick to use. +_SUPPORTED_HASHES = ("sha512", "sha384", "sha256", "sha224", "sha1", "md5") + + +@dataclass(frozen=True) +class LinkHash: + """Links to content may have embedded hash values. This class parses those. + + `name` must be any member of `_SUPPORTED_HASHES`. + + This class can be converted to and from `ArchiveInfo`. While ArchiveInfo intends to + be JSON-serializable to conform to PEP 610, this class contains the logic for + parsing a hash name and value for correctness, and then checking whether that hash + conforms to a schema with `.is_hash_allowed()`.""" + + name: str + value: str + + _hash_url_fragment_re = re.compile( + # NB: we do not validate that the second group (.*) is a valid hex + # digest. Instead, we simply keep that string in this class, and then check it + # against Hashes when hash-checking is needed. This is easier to debug than + # proactively discarding an invalid hex digest, as we handle incorrect hashes + # and malformed hashes in the same place. + r"[#&]({choices})=([^&]*)".format( + choices="|".join(re.escape(hash_name) for hash_name in _SUPPORTED_HASHES) + ), + ) + + def __post_init__(self) -> None: + assert self.name in _SUPPORTED_HASHES + + @classmethod + @functools.lru_cache(maxsize=None) + def find_hash_url_fragment(cls, url: str) -> Optional["LinkHash"]: + """Search a string for a checksum algorithm name and encoded output value.""" + match = cls._hash_url_fragment_re.search(url) + if match is None: + return None + name, value = match.groups() + return cls(name=name, value=value) + + def as_dict(self) -> Dict[str, str]: + return {self.name: self.value} + + def as_hashes(self) -> Hashes: + """Return a Hashes instance which checks only for the current hash.""" + return Hashes({self.name: [self.value]}) + + def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool: + """ + Return True if the current hash is allowed by `hashes`. + """ + if hashes is None: + return False + return hashes.is_hash_allowed(self.name, hex_digest=self.value) + + +@dataclass(frozen=True) +class MetadataFile: + """Information about a core metadata file associated with a distribution.""" + + hashes: Optional[Dict[str, str]] + + def __post_init__(self) -> None: + if self.hashes is not None: + assert all(name in _SUPPORTED_HASHES for name in self.hashes) + + +def supported_hashes(hashes: Optional[Dict[str, str]]) -> Optional[Dict[str, str]]: + # Remove any unsupported hash types from the mapping. If this leaves no + # supported hashes, return None + if hashes is None: + return None + hashes = {n: v for n, v in hashes.items() if n in _SUPPORTED_HASHES} + if not hashes: + return None + return hashes + + +def _clean_url_path_part(part: str) -> str: + """ + Clean a "part" of a URL path (i.e. after splitting on "@" characters). + """ + # We unquote prior to quoting to make sure nothing is double quoted. + return urllib.parse.quote(urllib.parse.unquote(part)) + + +def _clean_file_url_path(part: str) -> str: + """ + Clean the first part of a URL path that corresponds to a local + filesystem path (i.e. the first part after splitting on "@" characters). + """ + # We unquote prior to quoting to make sure nothing is double quoted. + # Also, on Windows the path part might contain a drive letter which + # should not be quoted. On Linux where drive letters do not + # exist, the colon should be quoted. We rely on urllib.request + # to do the right thing here. + return urllib.request.pathname2url(urllib.request.url2pathname(part)) + + +# percent-encoded: / +_reserved_chars_re = re.compile("(@|%2F)", re.IGNORECASE) + + +def _clean_url_path(path: str, is_local_path: bool) -> str: + """ + Clean the path portion of a URL. + """ + if is_local_path: + clean_func = _clean_file_url_path + else: + clean_func = _clean_url_path_part + + # Split on the reserved characters prior to cleaning so that + # revision strings in VCS URLs are properly preserved. + parts = _reserved_chars_re.split(path) + + cleaned_parts = [] + for to_clean, reserved in pairwise(itertools.chain(parts, [""])): + cleaned_parts.append(clean_func(to_clean)) + # Normalize %xx escapes (e.g. %2f -> %2F) + cleaned_parts.append(reserved.upper()) + + return "".join(cleaned_parts) + + +def _ensure_quoted_url(url: str) -> str: + """ + Make sure a link is fully quoted. + For example, if ' ' occurs in the URL, it will be replaced with "%20", + and without double-quoting other characters. + """ + # Split the URL into parts according to the general structure + # `scheme://netloc/path?query#fragment`. + result = urllib.parse.urlsplit(url) + # If the netloc is empty, then the URL refers to a local filesystem path. + is_local_path = not result.netloc + path = _clean_url_path(result.path, is_local_path=is_local_path) + return urllib.parse.urlunsplit(result._replace(path=path)) + + +def _absolute_link_url(base_url: str, url: str) -> str: + """ + A faster implementation of urllib.parse.urljoin with a shortcut + for absolute http/https URLs. + """ + if url.startswith(("https://", "http://")): + return url + else: + return urllib.parse.urljoin(base_url, url) + + +@functools.total_ordering +class Link: + """Represents a parsed link from a Package Index's simple URL""" + + __slots__ = [ + "_parsed_url", + "_url", + "_path", + "_hashes", + "comes_from", + "requires_python", + "yanked_reason", + "metadata_file_data", + "cache_link_parsing", + "egg_fragment", + ] + + def __init__( + self, + url: str, + comes_from: Optional[Union[str, "IndexContent"]] = None, + requires_python: Optional[str] = None, + yanked_reason: Optional[str] = None, + metadata_file_data: Optional[MetadataFile] = None, + cache_link_parsing: bool = True, + hashes: Optional[Mapping[str, str]] = None, + ) -> None: + """ + :param url: url of the resource pointed to (href of the link) + :param comes_from: instance of IndexContent where the link was found, + or string. + :param requires_python: String containing the `Requires-Python` + metadata field, specified in PEP 345. This may be specified by + a data-requires-python attribute in the HTML link tag, as + described in PEP 503. + :param yanked_reason: the reason the file has been yanked, if the + file has been yanked, or None if the file hasn't been yanked. + This is the value of the "data-yanked" attribute, if present, in + a simple repository HTML link. If the file has been yanked but + no reason was provided, this should be the empty string. See + PEP 592 for more information and the specification. + :param metadata_file_data: the metadata attached to the file, or None if + no such metadata is provided. This argument, if not None, indicates + that a separate metadata file exists, and also optionally supplies + hashes for that file. + :param cache_link_parsing: A flag that is used elsewhere to determine + whether resources retrieved from this link should be cached. PyPI + URLs should generally have this set to False, for example. + :param hashes: A mapping of hash names to digests to allow us to + determine the validity of a download. + """ + + # The comes_from, requires_python, and metadata_file_data arguments are + # only used by classmethods of this class, and are not used in client + # code directly. + + # url can be a UNC windows share + if url.startswith("\\\\"): + url = path_to_url(url) + + self._parsed_url = urllib.parse.urlsplit(url) + # Store the url as a private attribute to prevent accidentally + # trying to set a new value. + self._url = url + # The .path property is hot, so calculate its value ahead of time. + self._path = urllib.parse.unquote(self._parsed_url.path) + + link_hash = LinkHash.find_hash_url_fragment(url) + hashes_from_link = {} if link_hash is None else link_hash.as_dict() + if hashes is None: + self._hashes = hashes_from_link + else: + self._hashes = {**hashes, **hashes_from_link} + + self.comes_from = comes_from + self.requires_python = requires_python if requires_python else None + self.yanked_reason = yanked_reason + self.metadata_file_data = metadata_file_data + + self.cache_link_parsing = cache_link_parsing + self.egg_fragment = self._egg_fragment() + + @classmethod + def from_json( + cls, + file_data: Dict[str, Any], + page_url: str, + ) -> Optional["Link"]: + """ + Convert an pypi json document from a simple repository page into a Link. + """ + file_url = file_data.get("url") + if file_url is None: + return None + + url = _ensure_quoted_url(_absolute_link_url(page_url, file_url)) + pyrequire = file_data.get("requires-python") + yanked_reason = file_data.get("yanked") + hashes = file_data.get("hashes", {}) + + # PEP 714: Indexes must use the name core-metadata, but + # clients should support the old name as a fallback for compatibility. + metadata_info = file_data.get("core-metadata") + if metadata_info is None: + metadata_info = file_data.get("dist-info-metadata") + + # The metadata info value may be a boolean, or a dict of hashes. + if isinstance(metadata_info, dict): + # The file exists, and hashes have been supplied + metadata_file_data = MetadataFile(supported_hashes(metadata_info)) + elif metadata_info: + # The file exists, but there are no hashes + metadata_file_data = MetadataFile(None) + else: + # False or not present: the file does not exist + metadata_file_data = None + + # The Link.yanked_reason expects an empty string instead of a boolean. + if yanked_reason and not isinstance(yanked_reason, str): + yanked_reason = "" + # The Link.yanked_reason expects None instead of False. + elif not yanked_reason: + yanked_reason = None + + return cls( + url, + comes_from=page_url, + requires_python=pyrequire, + yanked_reason=yanked_reason, + hashes=hashes, + metadata_file_data=metadata_file_data, + ) + + @classmethod + def from_element( + cls, + anchor_attribs: Dict[str, Optional[str]], + page_url: str, + base_url: str, + ) -> Optional["Link"]: + """ + Convert an anchor element's attributes in a simple repository page to a Link. + """ + href = anchor_attribs.get("href") + if not href: + return None + + url = _ensure_quoted_url(_absolute_link_url(base_url, href)) + pyrequire = anchor_attribs.get("data-requires-python") + yanked_reason = anchor_attribs.get("data-yanked") + + # PEP 714: Indexes must use the name data-core-metadata, but + # clients should support the old name as a fallback for compatibility. + metadata_info = anchor_attribs.get("data-core-metadata") + if metadata_info is None: + metadata_info = anchor_attribs.get("data-dist-info-metadata") + # The metadata info value may be the string "true", or a string of + # the form "hashname=hashval" + if metadata_info == "true": + # The file exists, but there are no hashes + metadata_file_data = MetadataFile(None) + elif metadata_info is None: + # The file does not exist + metadata_file_data = None + else: + # The file exists, and hashes have been supplied + hashname, sep, hashval = metadata_info.partition("=") + if sep == "=": + metadata_file_data = MetadataFile(supported_hashes({hashname: hashval})) + else: + # Error - data is wrong. Treat as no hashes supplied. + logger.debug( + "Index returned invalid data-dist-info-metadata value: %s", + metadata_info, + ) + metadata_file_data = MetadataFile(None) + + return cls( + url, + comes_from=page_url, + requires_python=pyrequire, + yanked_reason=yanked_reason, + metadata_file_data=metadata_file_data, + ) + + def __str__(self) -> str: + if self.requires_python: + rp = f" (requires-python:{self.requires_python})" + else: + rp = "" + if self.comes_from: + return f"{redact_auth_from_url(self._url)} (from {self.comes_from}){rp}" + else: + return redact_auth_from_url(str(self._url)) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash(self.url) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Link): + return NotImplemented + return self.url == other.url + + def __lt__(self, other: Any) -> bool: + if not isinstance(other, Link): + return NotImplemented + return self.url < other.url + + @property + def url(self) -> str: + return self._url + + @property + def filename(self) -> str: + path = self.path.rstrip("/") + name = posixpath.basename(path) + if not name: + # Make sure we don't leak auth information if the netloc + # includes a username and password. + netloc, user_pass = split_auth_from_netloc(self.netloc) + return netloc + + name = urllib.parse.unquote(name) + assert name, f"URL {self._url!r} produced no filename" + return name + + @property + def file_path(self) -> str: + return url_to_path(self.url) + + @property + def scheme(self) -> str: + return self._parsed_url.scheme + + @property + def netloc(self) -> str: + """ + This can contain auth information. + """ + return self._parsed_url.netloc + + @property + def path(self) -> str: + return self._path + + def splitext(self) -> Tuple[str, str]: + return splitext(posixpath.basename(self.path.rstrip("/"))) + + @property + def ext(self) -> str: + return self.splitext()[1] + + @property + def url_without_fragment(self) -> str: + scheme, netloc, path, query, fragment = self._parsed_url + return urllib.parse.urlunsplit((scheme, netloc, path, query, "")) + + _egg_fragment_re = re.compile(r"[#&]egg=([^&]*)") + + # Per PEP 508. + _project_name_re = re.compile( + r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE + ) + + def _egg_fragment(self) -> Optional[str]: + match = self._egg_fragment_re.search(self._url) + if not match: + return None + + # An egg fragment looks like a PEP 508 project name, along with + # an optional extras specifier. Anything else is invalid. + project_name = match.group(1) + if not self._project_name_re.match(project_name): + deprecated( + reason=f"{self} contains an egg fragment with a non-PEP 508 name.", + replacement="to use the req @ url syntax, and remove the egg fragment", + gone_in="25.1", + issue=13157, + ) + + return project_name + + _subdirectory_fragment_re = re.compile(r"[#&]subdirectory=([^&]*)") + + @property + def subdirectory_fragment(self) -> Optional[str]: + match = self._subdirectory_fragment_re.search(self._url) + if not match: + return None + return match.group(1) + + def metadata_link(self) -> Optional["Link"]: + """Return a link to the associated core metadata file (if any).""" + if self.metadata_file_data is None: + return None + metadata_url = f"{self.url_without_fragment}.metadata" + if self.metadata_file_data.hashes is None: + return Link(metadata_url) + return Link(metadata_url, hashes=self.metadata_file_data.hashes) + + def as_hashes(self) -> Hashes: + return Hashes({k: [v] for k, v in self._hashes.items()}) + + @property + def hash(self) -> Optional[str]: + return next(iter(self._hashes.values()), None) + + @property + def hash_name(self) -> Optional[str]: + return next(iter(self._hashes), None) + + @property + def show_url(self) -> str: + return posixpath.basename(self._url.split("#", 1)[0].split("?", 1)[0]) + + @property + def is_file(self) -> bool: + return self.scheme == "file" + + def is_existing_dir(self) -> bool: + return self.is_file and os.path.isdir(self.file_path) + + @property + def is_wheel(self) -> bool: + return self.ext == WHEEL_EXTENSION + + @property + def is_vcs(self) -> bool: + from pip._internal.vcs import vcs + + return self.scheme in vcs.all_schemes + + @property + def is_yanked(self) -> bool: + return self.yanked_reason is not None + + @property + def has_hash(self) -> bool: + return bool(self._hashes) + + def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool: + """ + Return True if the link has a hash and it is allowed by `hashes`. + """ + if hashes is None: + return False + return any(hashes.is_hash_allowed(k, v) for k, v in self._hashes.items()) + + +class _CleanResult(NamedTuple): + """Convert link for equivalency check. + + This is used in the resolver to check whether two URL-specified requirements + likely point to the same distribution and can be considered equivalent. This + equivalency logic avoids comparing URLs literally, which can be too strict + (e.g. "a=1&b=2" vs "b=2&a=1") and produce conflicts unexpecting to users. + + Currently this does three things: + + 1. Drop the basic auth part. This is technically wrong since a server can + serve different content based on auth, but if it does that, it is even + impossible to guarantee two URLs without auth are equivalent, since + the user can input different auth information when prompted. So the + practical solution is to assume the auth doesn't affect the response. + 2. Parse the query to avoid the ordering issue. Note that ordering under the + same key in the query are NOT cleaned; i.e. "a=1&a=2" and "a=2&a=1" are + still considered different. + 3. Explicitly drop most of the fragment part, except ``subdirectory=`` and + hash values, since it should have no impact the downloaded content. Note + that this drops the "egg=" part historically used to denote the requested + project (and extras), which is wrong in the strictest sense, but too many + people are supplying it inconsistently to cause superfluous resolution + conflicts, so we choose to also ignore them. + """ + + parsed: urllib.parse.SplitResult + query: Dict[str, List[str]] + subdirectory: str + hashes: Dict[str, str] + + +def _clean_link(link: Link) -> _CleanResult: + parsed = link._parsed_url + netloc = parsed.netloc.rsplit("@", 1)[-1] + # According to RFC 8089, an empty host in file: means localhost. + if parsed.scheme == "file" and not netloc: + netloc = "localhost" + fragment = urllib.parse.parse_qs(parsed.fragment) + if "egg" in fragment: + logger.debug("Ignoring egg= fragment in %s", link) + try: + # If there are multiple subdirectory values, use the first one. + # This matches the behavior of Link.subdirectory_fragment. + subdirectory = fragment["subdirectory"][0] + except (IndexError, KeyError): + subdirectory = "" + # If there are multiple hash values under the same algorithm, use the + # first one. This matches the behavior of Link.hash_value. + hashes = {k: fragment[k][0] for k in _SUPPORTED_HASHES if k in fragment} + return _CleanResult( + parsed=parsed._replace(netloc=netloc, query="", fragment=""), + query=urllib.parse.parse_qs(parsed.query), + subdirectory=subdirectory, + hashes=hashes, + ) + + +@functools.lru_cache(maxsize=None) +def links_equivalent(link1: Link, link2: Link) -> bool: + return _clean_link(link1) == _clean_link(link2) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/scheme.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/scheme.py new file mode 100644 index 0000000000000000000000000000000000000000..06a9a550e34389c27ad3ee0bcef73d581cd4b448 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/scheme.py @@ -0,0 +1,25 @@ +""" +For types associated with installation schemes. + +For a general overview of available schemes and their context, see +https://docs.python.org/3/install/index.html#alternate-installation. +""" + +from dataclasses import dataclass + +SCHEME_KEYS = ["platlib", "purelib", "headers", "scripts", "data"] + + +@dataclass(frozen=True) +class Scheme: + """A Scheme holds paths which are used as the base directories for + artifacts associated with a Python package. + """ + + __slots__ = SCHEME_KEYS + + platlib: str + purelib: str + headers: str + scripts: str + data: str diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/search_scope.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/search_scope.py new file mode 100644 index 0000000000000000000000000000000000000000..ee7bc86229acda0378707431e5b4e9f054305d85 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/search_scope.py @@ -0,0 +1,127 @@ +import itertools +import logging +import os +import posixpath +import urllib.parse +from dataclasses import dataclass +from typing import List + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.models.index import PyPI +from pip._internal.utils.compat import has_tls +from pip._internal.utils.misc import normalize_path, redact_auth_from_url + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class SearchScope: + """ + Encapsulates the locations that pip is configured to search. + """ + + __slots__ = ["find_links", "index_urls", "no_index"] + + find_links: List[str] + index_urls: List[str] + no_index: bool + + @classmethod + def create( + cls, + find_links: List[str], + index_urls: List[str], + no_index: bool, + ) -> "SearchScope": + """ + Create a SearchScope object after normalizing the `find_links`. + """ + # Build find_links. If an argument starts with ~, it may be + # a local file relative to a home directory. So try normalizing + # it and if it exists, use the normalized version. + # This is deliberately conservative - it might be fine just to + # blindly normalize anything starting with a ~... + built_find_links: List[str] = [] + for link in find_links: + if link.startswith("~"): + new_link = normalize_path(link) + if os.path.exists(new_link): + link = new_link + built_find_links.append(link) + + # If we don't have TLS enabled, then WARN if anyplace we're looking + # relies on TLS. + if not has_tls(): + for link in itertools.chain(index_urls, built_find_links): + parsed = urllib.parse.urlparse(link) + if parsed.scheme == "https": + logger.warning( + "pip is configured with locations that require " + "TLS/SSL, however the ssl module in Python is not " + "available." + ) + break + + return cls( + find_links=built_find_links, + index_urls=index_urls, + no_index=no_index, + ) + + def get_formatted_locations(self) -> str: + lines = [] + redacted_index_urls = [] + if self.index_urls and self.index_urls != [PyPI.simple_url]: + for url in self.index_urls: + redacted_index_url = redact_auth_from_url(url) + + # Parse the URL + purl = urllib.parse.urlsplit(redacted_index_url) + + # URL is generally invalid if scheme and netloc is missing + # there are issues with Python and URL parsing, so this test + # is a bit crude. See bpo-20271, bpo-23505. Python doesn't + # always parse invalid URLs correctly - it should raise + # exceptions for malformed URLs + if not purl.scheme and not purl.netloc: + logger.warning( + 'The index url "%s" seems invalid, please provide a scheme.', + redacted_index_url, + ) + + redacted_index_urls.append(redacted_index_url) + + lines.append( + "Looking in indexes: {}".format(", ".join(redacted_index_urls)) + ) + + if self.find_links: + lines.append( + "Looking in links: {}".format( + ", ".join(redact_auth_from_url(url) for url in self.find_links) + ) + ) + return "\n".join(lines) + + def get_index_urls_locations(self, project_name: str) -> List[str]: + """Returns the locations found via self.index_urls + + Checks the url_name on the main (first in the list) index and + use this url_name to produce all locations + """ + + def mkurl_pypi_url(url: str) -> str: + loc = posixpath.join( + url, urllib.parse.quote(canonicalize_name(project_name)) + ) + # For maximum compatibility with easy_install, ensure the path + # ends in a trailing slash. Although this isn't in the spec + # (and PyPI can handle it without the slash) some other index + # implementations might break if they relied on easy_install's + # behavior. + if not loc.endswith("/"): + loc = loc + "/" + return loc + + return [mkurl_pypi_url(url) for url in self.index_urls] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/selection_prefs.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/selection_prefs.py new file mode 100644 index 0000000000000000000000000000000000000000..e9b50aa51756719d751ed0338aa7ca0a33d45f5a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/selection_prefs.py @@ -0,0 +1,53 @@ +from typing import Optional + +from pip._internal.models.format_control import FormatControl + + +# TODO: This needs Python 3.10's improved slots support for dataclasses +# to be converted into a dataclass. +class SelectionPreferences: + """ + Encapsulates the candidate selection preferences for downloading + and installing files. + """ + + __slots__ = [ + "allow_yanked", + "allow_all_prereleases", + "format_control", + "prefer_binary", + "ignore_requires_python", + ] + + # Don't include an allow_yanked default value to make sure each call + # site considers whether yanked releases are allowed. This also causes + # that decision to be made explicit in the calling code, which helps + # people when reading the code. + def __init__( + self, + allow_yanked: bool, + allow_all_prereleases: bool = False, + format_control: Optional[FormatControl] = None, + prefer_binary: bool = False, + ignore_requires_python: Optional[bool] = None, + ) -> None: + """Create a SelectionPreferences object. + + :param allow_yanked: Whether files marked as yanked (in the sense + of PEP 592) are permitted to be candidates for install. + :param format_control: A FormatControl object or None. Used to control + the selection of source packages / binary packages when consulting + the index and links. + :param prefer_binary: Whether to prefer an old, but valid, binary + dist over a new source dist. + :param ignore_requires_python: Whether to ignore incompatible + "Requires-Python" values in links. Defaults to False. + """ + if ignore_requires_python is None: + ignore_requires_python = False + + self.allow_yanked = allow_yanked + self.allow_all_prereleases = allow_all_prereleases + self.format_control = format_control + self.prefer_binary = prefer_binary + self.ignore_requires_python = ignore_requires_python diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/target_python.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/target_python.py new file mode 100644 index 0000000000000000000000000000000000000000..88925a9fd01a440e6de970bc234c3503b7f09cc1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/target_python.py @@ -0,0 +1,121 @@ +import sys +from typing import List, Optional, Set, Tuple + +from pip._vendor.packaging.tags import Tag + +from pip._internal.utils.compatibility_tags import get_supported, version_info_to_nodot +from pip._internal.utils.misc import normalize_version_info + + +class TargetPython: + """ + Encapsulates the properties of a Python interpreter one is targeting + for a package install, download, etc. + """ + + __slots__ = [ + "_given_py_version_info", + "abis", + "implementation", + "platforms", + "py_version", + "py_version_info", + "_valid_tags", + "_valid_tags_set", + ] + + def __init__( + self, + platforms: Optional[List[str]] = None, + py_version_info: Optional[Tuple[int, ...]] = None, + abis: Optional[List[str]] = None, + implementation: Optional[str] = None, + ) -> None: + """ + :param platforms: A list of strings or None. If None, searches for + packages that are supported by the current system. Otherwise, will + find packages that can be built on the platforms passed in. These + packages will only be downloaded for distribution: they will + not be built locally. + :param py_version_info: An optional tuple of ints representing the + Python version information to use (e.g. `sys.version_info[:3]`). + This can have length 1, 2, or 3 when provided. + :param abis: A list of strings or None. This is passed to + compatibility_tags.py's get_supported() function as is. + :param implementation: A string or None. This is passed to + compatibility_tags.py's get_supported() function as is. + """ + # Store the given py_version_info for when we call get_supported(). + self._given_py_version_info = py_version_info + + if py_version_info is None: + py_version_info = sys.version_info[:3] + else: + py_version_info = normalize_version_info(py_version_info) + + py_version = ".".join(map(str, py_version_info[:2])) + + self.abis = abis + self.implementation = implementation + self.platforms = platforms + self.py_version = py_version + self.py_version_info = py_version_info + + # This is used to cache the return value of get_(un)sorted_tags. + self._valid_tags: Optional[List[Tag]] = None + self._valid_tags_set: Optional[Set[Tag]] = None + + def format_given(self) -> str: + """ + Format the given, non-None attributes for display. + """ + display_version = None + if self._given_py_version_info is not None: + display_version = ".".join( + str(part) for part in self._given_py_version_info + ) + + key_values = [ + ("platforms", self.platforms), + ("version_info", display_version), + ("abis", self.abis), + ("implementation", self.implementation), + ] + return " ".join( + f"{key}={value!r}" for key, value in key_values if value is not None + ) + + def get_sorted_tags(self) -> List[Tag]: + """ + Return the supported PEP 425 tags to check wheel candidates against. + + The tags are returned in order of preference (most preferred first). + """ + if self._valid_tags is None: + # Pass versions=None if no py_version_info was given since + # versions=None uses special default logic. + py_version_info = self._given_py_version_info + if py_version_info is None: + version = None + else: + version = version_info_to_nodot(py_version_info) + + tags = get_supported( + version=version, + platforms=self.platforms, + abis=self.abis, + impl=self.implementation, + ) + self._valid_tags = tags + + return self._valid_tags + + def get_unsorted_tags(self) -> Set[Tag]: + """Exactly the same as get_sorted_tags, but returns a set. + + This is important for performance. + """ + if self._valid_tags_set is None: + self._valid_tags_set = set(self.get_sorted_tags()) + + return self._valid_tags_set diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/wheel.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..ea8560089d3df41689f41fe2639aa9f61dd1eace --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/models/wheel.py @@ -0,0 +1,118 @@ +"""Represents a wheel file and provides access to the various parts of the +name that have meaning. +""" + +import re +from typing import Dict, Iterable, List + +from pip._vendor.packaging.tags import Tag +from pip._vendor.packaging.utils import ( + InvalidWheelFilename as PackagingInvalidWheelName, +) +from pip._vendor.packaging.utils import parse_wheel_filename + +from pip._internal.exceptions import InvalidWheelFilename +from pip._internal.utils.deprecation import deprecated + + +class Wheel: + """A wheel file""" + + wheel_file_re = re.compile( + r"""^(?P(?P[^\s-]+?)-(?P[^\s-]*?)) + ((-(?P\d[^-]*?))?-(?P[^\s-]+?)-(?P[^\s-]+?)-(?P[^\s-]+?) + \.whl|\.dist-info)$""", + re.VERBOSE, + ) + + def __init__(self, filename: str) -> None: + """ + :raises InvalidWheelFilename: when the filename is invalid for a wheel + """ + wheel_info = self.wheel_file_re.match(filename) + if not wheel_info: + raise InvalidWheelFilename(f"{filename} is not a valid wheel filename.") + self.filename = filename + self.name = wheel_info.group("name").replace("_", "-") + _version = wheel_info.group("ver") + if "_" in _version: + try: + parse_wheel_filename(filename) + except PackagingInvalidWheelName as e: + deprecated( + reason=( + f"Wheel filename {filename!r} is not correctly normalised. " + "Future versions of pip will raise the following error:\n" + f"{e.args[0]}\n\n" + ), + replacement=( + "to rename the wheel to use a correctly normalised " + "name (this may require updating the version in " + "the project metadata)" + ), + gone_in="25.1", + issue=12938, + ) + + _version = _version.replace("_", "-") + + self.version = _version + self.build_tag = wheel_info.group("build") + self.pyversions = wheel_info.group("pyver").split(".") + self.abis = wheel_info.group("abi").split(".") + self.plats = wheel_info.group("plat").split(".") + + # All the tag combinations from this file + self.file_tags = { + Tag(x, y, z) for x in self.pyversions for y in self.abis for z in self.plats + } + + def get_formatted_file_tags(self) -> List[str]: + """Return the wheel's tags as a sorted list of strings.""" + return sorted(str(tag) for tag in self.file_tags) + + def support_index_min(self, tags: List[Tag]) -> int: + """Return the lowest index that one of the wheel's file_tag combinations + achieves in the given list of supported tags. + + For example, if there are 8 supported tags and one of the file tags + is first in the list, then return 0. + + :param tags: the PEP 425 tags to check the wheel against, in order + with most preferred first. + + :raises ValueError: If none of the wheel's file tags match one of + the supported tags. + """ + try: + return next(i for i, t in enumerate(tags) if t in self.file_tags) + except StopIteration: + raise ValueError() + + def find_most_preferred_tag( + self, tags: List[Tag], tag_to_priority: Dict[Tag, int] + ) -> int: + """Return the priority of the most preferred tag that one of the wheel's file + tag combinations achieves in the given list of supported tags using the given + tag_to_priority mapping, where lower priorities are more-preferred. + + This is used in place of support_index_min in some cases in order to avoid + an expensive linear scan of a large list of tags. + + :param tags: the PEP 425 tags to check the wheel against. + :param tag_to_priority: a mapping from tag to priority of that tag, where + lower is more preferred. + + :raises ValueError: If none of the wheel's file tags match one of + the supported tags. + """ + return min( + tag_to_priority[tag] for tag in self.file_tags if tag in tag_to_priority + ) + + def supported(self, tags: Iterable[Tag]) -> bool: + """Return whether the wheel is compatible with one of the given tags. + + :param tags: the PEP 425 tags to check the wheel against. + """ + return not self.file_tags.isdisjoint(tags) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b51bde91b2e5b4e557ed9b70fc113843cc3d49ae --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__init__.py @@ -0,0 +1,2 @@ +"""Contains purely network-related utilities. +""" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5f4765cfdaf22c850573ac97b93022bc637ea34 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/auth.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..123f6c94a86455a80c91ee8fa50a245d15720052 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/auth.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/cache.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca6031c3b5171ff59fc7c5db3f41b6fc34f480f5 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/cache.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/download.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/download.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..411d8219904254aecc7d53fdab7b51ae7044a03b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/download.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e66a215b3093352110b7a26cb91d65059662373 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/session.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/session.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a948f2f2e07b0d0fd309f372745c814fce509cdf Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/session.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/utils.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35787e67451ffa980794b6ecb4a521a87f56d023 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/utils.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/xmlrpc.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/xmlrpc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04b6c0bf0d32b237e43d4148cc028583e55ddad6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/__pycache__/xmlrpc.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/auth.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..1a2606ed080463dc36d34d5a4ff33b8937839823 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/auth.py @@ -0,0 +1,566 @@ +"""Network Authentication Helpers + +Contains interface (MultiDomainBasicAuth) and associated glue code for +providing credentials in the context of network requests. +""" + +import logging +import os +import shutil +import subprocess +import sysconfig +import typing +import urllib.parse +from abc import ABC, abstractmethod +from functools import lru_cache +from os.path import commonprefix +from pathlib import Path +from typing import Any, Dict, List, NamedTuple, Optional, Tuple + +from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth +from pip._vendor.requests.models import Request, Response +from pip._vendor.requests.utils import get_netrc_auth + +from pip._internal.utils.logging import getLogger +from pip._internal.utils.misc import ( + ask, + ask_input, + ask_password, + remove_auth_from_url, + split_auth_netloc_from_url, +) +from pip._internal.vcs.versioncontrol import AuthInfo + +logger = getLogger(__name__) + +KEYRING_DISABLED = False + + +class Credentials(NamedTuple): + url: str + username: str + password: str + + +class KeyRingBaseProvider(ABC): + """Keyring base provider interface""" + + has_keyring: bool + + @abstractmethod + def get_auth_info( + self, url: str, username: Optional[str] + ) -> Optional[AuthInfo]: ... + + @abstractmethod + def save_auth_info(self, url: str, username: str, password: str) -> None: ... + + +class KeyRingNullProvider(KeyRingBaseProvider): + """Keyring null provider""" + + has_keyring = False + + def get_auth_info(self, url: str, username: Optional[str]) -> Optional[AuthInfo]: + return None + + def save_auth_info(self, url: str, username: str, password: str) -> None: + return None + + +class KeyRingPythonProvider(KeyRingBaseProvider): + """Keyring interface which uses locally imported `keyring`""" + + has_keyring = True + + def __init__(self) -> None: + import keyring + + self.keyring = keyring + + def get_auth_info(self, url: str, username: Optional[str]) -> Optional[AuthInfo]: + # Support keyring's get_credential interface which supports getting + # credentials without a username. This is only available for + # keyring>=15.2.0. + if hasattr(self.keyring, "get_credential"): + logger.debug("Getting credentials from keyring for %s", url) + cred = self.keyring.get_credential(url, username) + if cred is not None: + return cred.username, cred.password + return None + + if username is not None: + logger.debug("Getting password from keyring for %s", url) + password = self.keyring.get_password(url, username) + if password: + return username, password + return None + + def save_auth_info(self, url: str, username: str, password: str) -> None: + self.keyring.set_password(url, username, password) + + +class KeyRingCliProvider(KeyRingBaseProvider): + """Provider which uses `keyring` cli + + Instead of calling the keyring package installed alongside pip + we call keyring on the command line which will enable pip to + use which ever installation of keyring is available first in + PATH. + """ + + has_keyring = True + + def __init__(self, cmd: str) -> None: + self.keyring = cmd + + def get_auth_info(self, url: str, username: Optional[str]) -> Optional[AuthInfo]: + # This is the default implementation of keyring.get_credential + # https://github.com/jaraco/keyring/blob/97689324abcf01bd1793d49063e7ca01e03d7d07/keyring/backend.py#L134-L139 + if username is not None: + password = self._get_password(url, username) + if password is not None: + return username, password + return None + + def save_auth_info(self, url: str, username: str, password: str) -> None: + return self._set_password(url, username, password) + + def _get_password(self, service_name: str, username: str) -> Optional[str]: + """Mirror the implementation of keyring.get_password using cli""" + if self.keyring is None: + return None + + cmd = [self.keyring, "get", service_name, username] + env = os.environ.copy() + env["PYTHONIOENCODING"] = "utf-8" + res = subprocess.run( + cmd, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + env=env, + ) + if res.returncode: + return None + return res.stdout.decode("utf-8").strip(os.linesep) + + def _set_password(self, service_name: str, username: str, password: str) -> None: + """Mirror the implementation of keyring.set_password using cli""" + if self.keyring is None: + return None + env = os.environ.copy() + env["PYTHONIOENCODING"] = "utf-8" + subprocess.run( + [self.keyring, "set", service_name, username], + input=f"{password}{os.linesep}".encode(), + env=env, + check=True, + ) + return None + + +@lru_cache(maxsize=None) +def get_keyring_provider(provider: str) -> KeyRingBaseProvider: + logger.verbose("Keyring provider requested: %s", provider) + + # keyring has previously failed and been disabled + if KEYRING_DISABLED: + provider = "disabled" + if provider in ["import", "auto"]: + try: + impl = KeyRingPythonProvider() + logger.verbose("Keyring provider set: import") + return impl + except ImportError: + pass + except Exception as exc: + # In the event of an unexpected exception + # we should warn the user + msg = "Installed copy of keyring fails with exception %s" + if provider == "auto": + msg = msg + ", trying to find a keyring executable as a fallback" + logger.warning(msg, exc, exc_info=logger.isEnabledFor(logging.DEBUG)) + if provider in ["subprocess", "auto"]: + cli = shutil.which("keyring") + if cli and cli.startswith(sysconfig.get_path("scripts")): + # all code within this function is stolen from shutil.which implementation + @typing.no_type_check + def PATH_as_shutil_which_determines_it() -> str: + path = os.environ.get("PATH", None) + if path is None: + try: + path = os.confstr("CS_PATH") + except (AttributeError, ValueError): + # os.confstr() or CS_PATH is not available + path = os.defpath + # bpo-35755: Don't use os.defpath if the PATH environment variable is + # set to an empty string + + return path + + scripts = Path(sysconfig.get_path("scripts")) + + paths = [] + for path in PATH_as_shutil_which_determines_it().split(os.pathsep): + p = Path(path) + try: + if not p.samefile(scripts): + paths.append(path) + except FileNotFoundError: + pass + + path = os.pathsep.join(paths) + + cli = shutil.which("keyring", path=path) + + if cli: + logger.verbose("Keyring provider set: subprocess with executable %s", cli) + return KeyRingCliProvider(cli) + + logger.verbose("Keyring provider set: disabled") + return KeyRingNullProvider() + + +class MultiDomainBasicAuth(AuthBase): + def __init__( + self, + prompting: bool = True, + index_urls: Optional[List[str]] = None, + keyring_provider: str = "auto", + ) -> None: + self.prompting = prompting + self.index_urls = index_urls + self.keyring_provider = keyring_provider # type: ignore[assignment] + self.passwords: Dict[str, AuthInfo] = {} + # When the user is prompted to enter credentials and keyring is + # available, we will offer to save them. If the user accepts, + # this value is set to the credentials they entered. After the + # request authenticates, the caller should call + # ``save_credentials`` to save these. + self._credentials_to_save: Optional[Credentials] = None + + @property + def keyring_provider(self) -> KeyRingBaseProvider: + return get_keyring_provider(self._keyring_provider) + + @keyring_provider.setter + def keyring_provider(self, provider: str) -> None: + # The free function get_keyring_provider has been decorated with + # functools.cache. If an exception occurs in get_keyring_auth that + # cache will be cleared and keyring disabled, take that into account + # if you want to remove this indirection. + self._keyring_provider = provider + + @property + def use_keyring(self) -> bool: + # We won't use keyring when --no-input is passed unless + # a specific provider is requested because it might require + # user interaction + return self.prompting or self._keyring_provider not in ["auto", "disabled"] + + def _get_keyring_auth( + self, + url: Optional[str], + username: Optional[str], + ) -> Optional[AuthInfo]: + """Return the tuple auth for a given url from keyring.""" + # Do nothing if no url was provided + if not url: + return None + + try: + return self.keyring_provider.get_auth_info(url, username) + except Exception as exc: + # Log the full exception (with stacktrace) at debug, so it'll only + # show up when running in verbose mode. + logger.debug("Keyring is skipped due to an exception", exc_info=True) + # Always log a shortened version of the exception. + logger.warning( + "Keyring is skipped due to an exception: %s", + str(exc), + ) + global KEYRING_DISABLED + KEYRING_DISABLED = True + get_keyring_provider.cache_clear() + return None + + def _get_index_url(self, url: str) -> Optional[str]: + """Return the original index URL matching the requested URL. + + Cached or dynamically generated credentials may work against + the original index URL rather than just the netloc. + + The provided url should have had its username and password + removed already. If the original index url had credentials then + they will be included in the return value. + + Returns None if no matching index was found, or if --no-index + was specified by the user. + """ + if not url or not self.index_urls: + return None + + url = remove_auth_from_url(url).rstrip("/") + "/" + parsed_url = urllib.parse.urlsplit(url) + + candidates = [] + + for index in self.index_urls: + index = index.rstrip("/") + "/" + parsed_index = urllib.parse.urlsplit(remove_auth_from_url(index)) + if parsed_url == parsed_index: + return index + + if parsed_url.netloc != parsed_index.netloc: + continue + + candidate = urllib.parse.urlsplit(index) + candidates.append(candidate) + + if not candidates: + return None + + candidates.sort( + reverse=True, + key=lambda candidate: commonprefix( + [ + parsed_url.path, + candidate.path, + ] + ).rfind("/"), + ) + + return urllib.parse.urlunsplit(candidates[0]) + + def _get_new_credentials( + self, + original_url: str, + *, + allow_netrc: bool = True, + allow_keyring: bool = False, + ) -> AuthInfo: + """Find and return credentials for the specified URL.""" + # Split the credentials and netloc from the url. + url, netloc, url_user_password = split_auth_netloc_from_url( + original_url, + ) + + # Start with the credentials embedded in the url + username, password = url_user_password + if username is not None and password is not None: + logger.debug("Found credentials in url for %s", netloc) + return url_user_password + + # Find a matching index url for this request + index_url = self._get_index_url(url) + if index_url: + # Split the credentials from the url. + index_info = split_auth_netloc_from_url(index_url) + if index_info: + index_url, _, index_url_user_password = index_info + logger.debug("Found index url %s", index_url) + + # If an index URL was found, try its embedded credentials + if index_url and index_url_user_password[0] is not None: + username, password = index_url_user_password + if username is not None and password is not None: + logger.debug("Found credentials in index url for %s", netloc) + return index_url_user_password + + # Get creds from netrc if we still don't have them + if allow_netrc: + netrc_auth = get_netrc_auth(original_url) + if netrc_auth: + logger.debug("Found credentials in netrc for %s", netloc) + return netrc_auth + + # If we don't have a password and keyring is available, use it. + if allow_keyring: + # The index url is more specific than the netloc, so try it first + # fmt: off + kr_auth = ( + self._get_keyring_auth(index_url, username) or + self._get_keyring_auth(netloc, username) + ) + # fmt: on + if kr_auth: + logger.debug("Found credentials in keyring for %s", netloc) + return kr_auth + + return username, password + + def _get_url_and_credentials( + self, original_url: str + ) -> Tuple[str, Optional[str], Optional[str]]: + """Return the credentials to use for the provided URL. + + If allowed, netrc and keyring may be used to obtain the + correct credentials. + + Returns (url_without_credentials, username, password). Note + that even if the original URL contains credentials, this + function may return a different username and password. + """ + url, netloc, _ = split_auth_netloc_from_url(original_url) + + # Try to get credentials from original url + username, password = self._get_new_credentials(original_url) + + # If credentials not found, use any stored credentials for this netloc. + # Do this if either the username or the password is missing. + # This accounts for the situation in which the user has specified + # the username in the index url, but the password comes from keyring. + if (username is None or password is None) and netloc in self.passwords: + un, pw = self.passwords[netloc] + # It is possible that the cached credentials are for a different username, + # in which case the cache should be ignored. + if username is None or username == un: + username, password = un, pw + + if username is not None or password is not None: + # Convert the username and password if they're None, so that + # this netloc will show up as "cached" in the conditional above. + # Further, HTTPBasicAuth doesn't accept None, so it makes sense to + # cache the value that is going to be used. + username = username or "" + password = password or "" + + # Store any acquired credentials. + self.passwords[netloc] = (username, password) + + assert ( + # Credentials were found + (username is not None and password is not None) + # Credentials were not found + or (username is None and password is None) + ), f"Could not load credentials from url: {original_url}" + + return url, username, password + + def __call__(self, req: Request) -> Request: + # Get credentials for this request + url, username, password = self._get_url_and_credentials(req.url) + + # Set the url of the request to the url without any credentials + req.url = url + + if username is not None and password is not None: + # Send the basic auth with this request + req = HTTPBasicAuth(username, password)(req) + + # Attach a hook to handle 401 responses + req.register_hook("response", self.handle_401) + + return req + + # Factored out to allow for easy patching in tests + def _prompt_for_password( + self, netloc: str + ) -> Tuple[Optional[str], Optional[str], bool]: + username = ask_input(f"User for {netloc}: ") if self.prompting else None + if not username: + return None, None, False + if self.use_keyring: + auth = self._get_keyring_auth(netloc, username) + if auth and auth[0] is not None and auth[1] is not None: + return auth[0], auth[1], False + password = ask_password("Password: ") + return username, password, True + + # Factored out to allow for easy patching in tests + def _should_save_password_to_keyring(self) -> bool: + if ( + not self.prompting + or not self.use_keyring + or not self.keyring_provider.has_keyring + ): + return False + return ask("Save credentials to keyring [y/N]: ", ["y", "n"]) == "y" + + def handle_401(self, resp: Response, **kwargs: Any) -> Response: + # We only care about 401 responses, anything else we want to just + # pass through the actual response + if resp.status_code != 401: + return resp + + username, password = None, None + + # Query the keyring for credentials: + if self.use_keyring: + username, password = self._get_new_credentials( + resp.url, + allow_netrc=False, + allow_keyring=True, + ) + + # We are not able to prompt the user so simply return the response + if not self.prompting and not username and not password: + return resp + + parsed = urllib.parse.urlparse(resp.url) + + # Prompt the user for a new username and password + save = False + if not username and not password: + username, password, save = self._prompt_for_password(parsed.netloc) + + # Store the new username and password to use for future requests + self._credentials_to_save = None + if username is not None and password is not None: + self.passwords[parsed.netloc] = (username, password) + + # Prompt to save the password to keyring + if save and self._should_save_password_to_keyring(): + self._credentials_to_save = Credentials( + url=parsed.netloc, + username=username, + password=password, + ) + + # Consume content and release the original connection to allow our new + # request to reuse the same one. + # The result of the assignment isn't used, it's just needed to consume + # the content. + _ = resp.content + resp.raw.release_conn() + + # Add our new username and password to the request + req = HTTPBasicAuth(username or "", password or "")(resp.request) + req.register_hook("response", self.warn_on_401) + + # On successful request, save the credentials that were used to + # keyring. (Note that if the user responded "no" above, this member + # is not set and nothing will be saved.) + if self._credentials_to_save: + req.register_hook("response", self.save_credentials) + + # Send our new request + new_resp = resp.connection.send(req, **kwargs) + new_resp.history.append(resp) + + return new_resp + + def warn_on_401(self, resp: Response, **kwargs: Any) -> None: + """Response callback to warn about incorrect credentials.""" + if resp.status_code == 401: + logger.warning( + "401 Error, Credentials not correct for %s", + resp.request.url, + ) + + def save_credentials(self, resp: Response, **kwargs: Any) -> None: + """Response callback to save credentials on success.""" + assert ( + self.keyring_provider.has_keyring + ), "should never reach here without keyring" + + creds = self._credentials_to_save + self._credentials_to_save = None + if creds and resp.status_code < 400: + try: + logger.info("Saving credentials to keyring") + self.keyring_provider.save_auth_info( + creds.url, creds.username, creds.password + ) + except Exception: + logger.exception("Failed to save credentials") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/cache.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..fca04e6945fd8a926e559902ee68ae45f7265a4c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/cache.py @@ -0,0 +1,118 @@ +"""HTTP cache implementation. +""" + +import os +from contextlib import contextmanager +from datetime import datetime +from typing import BinaryIO, Generator, Optional, Union + +from pip._vendor.cachecontrol.cache import SeparateBodyBaseCache +from pip._vendor.cachecontrol.caches import SeparateBodyFileCache +from pip._vendor.requests.models import Response + +from pip._internal.utils.filesystem import adjacent_tmp_file, replace +from pip._internal.utils.misc import ensure_dir + + +def is_from_cache(response: Response) -> bool: + return getattr(response, "from_cache", False) + + +@contextmanager +def suppressed_cache_errors() -> Generator[None, None, None]: + """If we can't access the cache then we can just skip caching and process + requests as if caching wasn't enabled. + """ + try: + yield + except OSError: + pass + + +class SafeFileCache(SeparateBodyBaseCache): + """ + A file based cache which is safe to use even when the target directory may + not be accessible or writable. + + There is a race condition when two processes try to write and/or read the + same entry at the same time, since each entry consists of two separate + files (https://github.com/psf/cachecontrol/issues/324). We therefore have + additional logic that makes sure that both files to be present before + returning an entry; this fixes the read side of the race condition. + + For the write side, we assume that the server will only ever return the + same data for the same URL, which ought to be the case for files pip is + downloading. PyPI does not have a mechanism to swap out a wheel for + another wheel, for example. If this assumption is not true, the + CacheControl issue will need to be fixed. + """ + + def __init__(self, directory: str) -> None: + assert directory is not None, "Cache directory must not be None." + super().__init__() + self.directory = directory + + def _get_cache_path(self, name: str) -> str: + # From cachecontrol.caches.file_cache.FileCache._fn, brought into our + # class for backwards-compatibility and to avoid using a non-public + # method. + hashed = SeparateBodyFileCache.encode(name) + parts = list(hashed[:5]) + [hashed] + return os.path.join(self.directory, *parts) + + def get(self, key: str) -> Optional[bytes]: + # The cache entry is only valid if both metadata and body exist. + metadata_path = self._get_cache_path(key) + body_path = metadata_path + ".body" + if not (os.path.exists(metadata_path) and os.path.exists(body_path)): + return None + with suppressed_cache_errors(): + with open(metadata_path, "rb") as f: + return f.read() + + def _write(self, path: str, data: bytes) -> None: + with suppressed_cache_errors(): + ensure_dir(os.path.dirname(path)) + + with adjacent_tmp_file(path) as f: + f.write(data) + # Inherit the read/write permissions of the cache directory + # to enable multi-user cache use-cases. + mode = ( + os.stat(self.directory).st_mode + & 0o666 # select read/write permissions of cache directory + | 0o600 # set owner read/write permissions + ) + # Change permissions only if there is no risk of following a symlink. + if os.chmod in os.supports_fd: + os.chmod(f.fileno(), mode) + elif os.chmod in os.supports_follow_symlinks: + os.chmod(f.name, mode, follow_symlinks=False) + + replace(f.name, path) + + def set( + self, key: str, value: bytes, expires: Union[int, datetime, None] = None + ) -> None: + path = self._get_cache_path(key) + self._write(path, value) + + def delete(self, key: str) -> None: + path = self._get_cache_path(key) + with suppressed_cache_errors(): + os.remove(path) + with suppressed_cache_errors(): + os.remove(path + ".body") + + def get_body(self, key: str) -> Optional[BinaryIO]: + # The cache entry is only valid if both metadata and body exist. + metadata_path = self._get_cache_path(key) + body_path = metadata_path + ".body" + if not (os.path.exists(metadata_path) and os.path.exists(body_path)): + return None + with suppressed_cache_errors(): + return open(body_path, "rb") + + def set_body(self, key: str, body: bytes) -> None: + path = self._get_cache_path(key) + ".body" + self._write(path, body) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/download.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/download.py new file mode 100644 index 0000000000000000000000000000000000000000..5c3bce3d2fd0cd0678ab4af066dea803b7064067 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/download.py @@ -0,0 +1,187 @@ +"""Download files with progress indicators. +""" + +import email.message +import logging +import mimetypes +import os +from typing import Iterable, Optional, Tuple + +from pip._vendor.requests.models import Response + +from pip._internal.cli.progress_bars import get_download_progress_renderer +from pip._internal.exceptions import NetworkConnectionError +from pip._internal.models.index import PyPI +from pip._internal.models.link import Link +from pip._internal.network.cache import is_from_cache +from pip._internal.network.session import PipSession +from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks +from pip._internal.utils.misc import format_size, redact_auth_from_url, splitext + +logger = logging.getLogger(__name__) + + +def _get_http_response_size(resp: Response) -> Optional[int]: + try: + return int(resp.headers["content-length"]) + except (ValueError, KeyError, TypeError): + return None + + +def _prepare_download( + resp: Response, + link: Link, + progress_bar: str, +) -> Iterable[bytes]: + total_length = _get_http_response_size(resp) + + if link.netloc == PyPI.file_storage_domain: + url = link.show_url + else: + url = link.url_without_fragment + + logged_url = redact_auth_from_url(url) + + if total_length: + logged_url = f"{logged_url} ({format_size(total_length)})" + + if is_from_cache(resp): + logger.info("Using cached %s", logged_url) + else: + logger.info("Downloading %s", logged_url) + + if logger.getEffectiveLevel() > logging.INFO: + show_progress = False + elif is_from_cache(resp): + show_progress = False + elif not total_length: + show_progress = True + elif total_length > (512 * 1024): + show_progress = True + else: + show_progress = False + + chunks = response_chunks(resp) + + if not show_progress: + return chunks + + renderer = get_download_progress_renderer(bar_type=progress_bar, size=total_length) + return renderer(chunks) + + +def sanitize_content_filename(filename: str) -> str: + """ + Sanitize the "filename" value from a Content-Disposition header. + """ + return os.path.basename(filename) + + +def parse_content_disposition(content_disposition: str, default_filename: str) -> str: + """ + Parse the "filename" value from a Content-Disposition header, and + return the default filename if the result is empty. + """ + m = email.message.Message() + m["content-type"] = content_disposition + filename = m.get_param("filename") + if filename: + # We need to sanitize the filename to prevent directory traversal + # in case the filename contains ".." path parts. + filename = sanitize_content_filename(str(filename)) + return filename or default_filename + + +def _get_http_response_filename(resp: Response, link: Link) -> str: + """Get an ideal filename from the given HTTP response, falling back to + the link filename if not provided. + """ + filename = link.filename # fallback + # Have a look at the Content-Disposition header for a better guess + content_disposition = resp.headers.get("content-disposition") + if content_disposition: + filename = parse_content_disposition(content_disposition, filename) + ext: Optional[str] = splitext(filename)[1] + if not ext: + ext = mimetypes.guess_extension(resp.headers.get("content-type", "")) + if ext: + filename += ext + if not ext and link.url != resp.url: + ext = os.path.splitext(resp.url)[1] + if ext: + filename += ext + return filename + + +def _http_get_download(session: PipSession, link: Link) -> Response: + target_url = link.url.split("#", 1)[0] + resp = session.get(target_url, headers=HEADERS, stream=True) + raise_for_status(resp) + return resp + + +class Downloader: + def __init__( + self, + session: PipSession, + progress_bar: str, + ) -> None: + self._session = session + self._progress_bar = progress_bar + + def __call__(self, link: Link, location: str) -> Tuple[str, str]: + """Download the file given by link into location.""" + try: + resp = _http_get_download(self._session, link) + except NetworkConnectionError as e: + assert e.response is not None + logger.critical( + "HTTP error %s while getting %s", e.response.status_code, link + ) + raise + + filename = _get_http_response_filename(resp, link) + filepath = os.path.join(location, filename) + + chunks = _prepare_download(resp, link, self._progress_bar) + with open(filepath, "wb") as content_file: + for chunk in chunks: + content_file.write(chunk) + content_type = resp.headers.get("Content-Type", "") + return filepath, content_type + + +class BatchDownloader: + def __init__( + self, + session: PipSession, + progress_bar: str, + ) -> None: + self._session = session + self._progress_bar = progress_bar + + def __call__( + self, links: Iterable[Link], location: str + ) -> Iterable[Tuple[Link, Tuple[str, str]]]: + """Download the files given by links into location.""" + for link in links: + try: + resp = _http_get_download(self._session, link) + except NetworkConnectionError as e: + assert e.response is not None + logger.critical( + "HTTP error %s while getting %s", + e.response.status_code, + link, + ) + raise + + filename = _get_http_response_filename(resp, link) + filepath = os.path.join(location, filename) + + chunks = _prepare_download(resp, link, self._progress_bar) + with open(filepath, "wb") as content_file: + for chunk in chunks: + content_file.write(chunk) + content_type = resp.headers.get("Content-Type", "") + yield link, (filepath, content_type) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/lazy_wheel.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/lazy_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..03f883c1fc46d374e2b4556c361e4d173aacf027 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/lazy_wheel.py @@ -0,0 +1,210 @@ +"""Lazy ZIP over HTTP""" + +__all__ = ["HTTPRangeRequestUnsupported", "dist_from_wheel_url"] + +from bisect import bisect_left, bisect_right +from contextlib import contextmanager +from tempfile import NamedTemporaryFile +from typing import Any, Dict, Generator, List, Optional, Tuple +from zipfile import BadZipFile, ZipFile + +from pip._vendor.packaging.utils import canonicalize_name +from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response + +from pip._internal.metadata import BaseDistribution, MemoryWheel, get_wheel_distribution +from pip._internal.network.session import PipSession +from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks + + +class HTTPRangeRequestUnsupported(Exception): + pass + + +def dist_from_wheel_url(name: str, url: str, session: PipSession) -> BaseDistribution: + """Return a distribution object from the given wheel URL. + + This uses HTTP range requests to only fetch the portion of the wheel + containing metadata, just enough for the object to be constructed. + If such requests are not supported, HTTPRangeRequestUnsupported + is raised. + """ + with LazyZipOverHTTP(url, session) as zf: + # For read-only ZIP files, ZipFile only needs methods read, + # seek, seekable and tell, not the whole IO protocol. + wheel = MemoryWheel(zf.name, zf) # type: ignore + # After context manager exit, wheel.name + # is an invalid file by intention. + return get_wheel_distribution(wheel, canonicalize_name(name)) + + +class LazyZipOverHTTP: + """File-like object mapped to a ZIP file over HTTP. + + This uses HTTP range requests to lazily fetch the file's content, + which is supposed to be fed to ZipFile. If such requests are not + supported by the server, raise HTTPRangeRequestUnsupported + during initialization. + """ + + def __init__( + self, url: str, session: PipSession, chunk_size: int = CONTENT_CHUNK_SIZE + ) -> None: + head = session.head(url, headers=HEADERS) + raise_for_status(head) + assert head.status_code == 200 + self._session, self._url, self._chunk_size = session, url, chunk_size + self._length = int(head.headers["Content-Length"]) + self._file = NamedTemporaryFile() + self.truncate(self._length) + self._left: List[int] = [] + self._right: List[int] = [] + if "bytes" not in head.headers.get("Accept-Ranges", "none"): + raise HTTPRangeRequestUnsupported("range request is not supported") + self._check_zip() + + @property + def mode(self) -> str: + """Opening mode, which is always rb.""" + return "rb" + + @property + def name(self) -> str: + """Path to the underlying file.""" + return self._file.name + + def seekable(self) -> bool: + """Return whether random access is supported, which is True.""" + return True + + def close(self) -> None: + """Close the file.""" + self._file.close() + + @property + def closed(self) -> bool: + """Whether the file is closed.""" + return self._file.closed + + def read(self, size: int = -1) -> bytes: + """Read up to size bytes from the object and return them. + + As a convenience, if size is unspecified or -1, + all bytes until EOF are returned. Fewer than + size bytes may be returned if EOF is reached. + """ + download_size = max(size, self._chunk_size) + start, length = self.tell(), self._length + stop = length if size < 0 else min(start + download_size, length) + start = max(0, stop - download_size) + self._download(start, stop - 1) + return self._file.read(size) + + def readable(self) -> bool: + """Return whether the file is readable, which is True.""" + return True + + def seek(self, offset: int, whence: int = 0) -> int: + """Change stream position and return the new absolute position. + + Seek to offset relative position indicated by whence: + * 0: Start of stream (the default). pos should be >= 0; + * 1: Current position - pos may be negative; + * 2: End of stream - pos usually negative. + """ + return self._file.seek(offset, whence) + + def tell(self) -> int: + """Return the current position.""" + return self._file.tell() + + def truncate(self, size: Optional[int] = None) -> int: + """Resize the stream to the given size in bytes. + + If size is unspecified resize to the current position. + The current stream position isn't changed. + + Return the new file size. + """ + return self._file.truncate(size) + + def writable(self) -> bool: + """Return False.""" + return False + + def __enter__(self) -> "LazyZipOverHTTP": + self._file.__enter__() + return self + + def __exit__(self, *exc: Any) -> None: + self._file.__exit__(*exc) + + @contextmanager + def _stay(self) -> Generator[None, None, None]: + """Return a context manager keeping the position. + + At the end of the block, seek back to original position. + """ + pos = self.tell() + try: + yield + finally: + self.seek(pos) + + def _check_zip(self) -> None: + """Check and download until the file is a valid ZIP.""" + end = self._length - 1 + for start in reversed(range(0, end, self._chunk_size)): + self._download(start, end) + with self._stay(): + try: + # For read-only ZIP files, ZipFile only needs + # methods read, seek, seekable and tell. + ZipFile(self) + except BadZipFile: + pass + else: + break + + def _stream_response( + self, start: int, end: int, base_headers: Dict[str, str] = HEADERS + ) -> Response: + """Return HTTP response to a range request from start to end.""" + headers = base_headers.copy() + headers["Range"] = f"bytes={start}-{end}" + # TODO: Get range requests to be correctly cached + headers["Cache-Control"] = "no-cache" + return self._session.get(self._url, headers=headers, stream=True) + + def _merge( + self, start: int, end: int, left: int, right: int + ) -> Generator[Tuple[int, int], None, None]: + """Return a generator of intervals to be fetched. + + Args: + start (int): Start of needed interval + end (int): End of needed interval + left (int): Index of first overlapping downloaded data + right (int): Index after last overlapping downloaded data + """ + lslice, rslice = self._left[left:right], self._right[left:right] + i = start = min([start] + lslice[:1]) + end = max([end] + rslice[-1:]) + for j, k in zip(lslice, rslice): + if j > i: + yield i, j - 1 + i = k + 1 + if i <= end: + yield i, end + self._left[left:right], self._right[left:right] = [start], [end] + + def _download(self, start: int, end: int) -> None: + """Download bytes from start to end inclusively.""" + with self._stay(): + left = bisect_left(self._right, start) + right = bisect_right(self._left, end) + for start, end in self._merge(start, end, left, right): + response = self._stream_response(start, end) + response.raise_for_status() + self.seek(start) + for chunk in response_chunks(response, self._chunk_size): + self._file.write(chunk) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/session.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/session.py new file mode 100644 index 0000000000000000000000000000000000000000..5e10f8f56154032bd06400db48afc890326dc5f6 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/session.py @@ -0,0 +1,523 @@ +"""PipSession and supporting code, containing all pip-specific +network request configuration and behavior. +""" + +import email.utils +import functools +import io +import ipaddress +import json +import logging +import mimetypes +import os +import platform +import shutil +import subprocess +import sys +import urllib.parse +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Generator, + List, + Mapping, + Optional, + Sequence, + Tuple, + Union, +) + +from pip._vendor import requests, urllib3 +from pip._vendor.cachecontrol import CacheControlAdapter as _BaseCacheControlAdapter +from pip._vendor.requests.adapters import DEFAULT_POOLBLOCK, BaseAdapter +from pip._vendor.requests.adapters import HTTPAdapter as _BaseHTTPAdapter +from pip._vendor.requests.models import PreparedRequest, Response +from pip._vendor.requests.structures import CaseInsensitiveDict +from pip._vendor.urllib3.connectionpool import ConnectionPool +from pip._vendor.urllib3.exceptions import InsecureRequestWarning + +from pip import __version__ +from pip._internal.metadata import get_default_environment +from pip._internal.models.link import Link +from pip._internal.network.auth import MultiDomainBasicAuth +from pip._internal.network.cache import SafeFileCache + +# Import ssl from compat so the initial import occurs in only one place. +from pip._internal.utils.compat import has_tls +from pip._internal.utils.glibc import libc_ver +from pip._internal.utils.misc import build_url_from_netloc, parse_netloc +from pip._internal.utils.urls import url_to_path + +if TYPE_CHECKING: + from ssl import SSLContext + + from pip._vendor.urllib3.poolmanager import PoolManager + + +logger = logging.getLogger(__name__) + +SecureOrigin = Tuple[str, str, Optional[Union[int, str]]] + + +# Ignore warning raised when using --trusted-host. +warnings.filterwarnings("ignore", category=InsecureRequestWarning) + + +SECURE_ORIGINS: List[SecureOrigin] = [ + # protocol, hostname, port + # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC) + ("https", "*", "*"), + ("*", "localhost", "*"), + ("*", "127.0.0.0/8", "*"), + ("*", "::1/128", "*"), + ("file", "*", None), + # ssh is always secure. + ("ssh", "*", "*"), +] + + +# These are environment variables present when running under various +# CI systems. For each variable, some CI systems that use the variable +# are indicated. The collection was chosen so that for each of a number +# of popular systems, at least one of the environment variables is used. +# This list is used to provide some indication of and lower bound for +# CI traffic to PyPI. Thus, it is okay if the list is not comprehensive. +# For more background, see: https://github.com/pypa/pip/issues/5499 +CI_ENVIRONMENT_VARIABLES = ( + # Azure Pipelines + "BUILD_BUILDID", + # Jenkins + "BUILD_ID", + # AppVeyor, CircleCI, Codeship, Gitlab CI, Shippable, Travis CI + "CI", + # Explicit environment variable. + "PIP_IS_CI", +) + + +def looks_like_ci() -> bool: + """ + Return whether it looks like pip is running under CI. + """ + # We don't use the method of checking for a tty (e.g. using isatty()) + # because some CI systems mimic a tty (e.g. Travis CI). Thus that + # method doesn't provide definitive information in either direction. + return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES) + + +@functools.lru_cache(maxsize=1) +def user_agent() -> str: + """ + Return a string representing the user agent. + """ + data: Dict[str, Any] = { + "installer": {"name": "pip", "version": __version__}, + "python": platform.python_version(), + "implementation": { + "name": platform.python_implementation(), + }, + } + + if data["implementation"]["name"] == "CPython": + data["implementation"]["version"] = platform.python_version() + elif data["implementation"]["name"] == "PyPy": + pypy_version_info = sys.pypy_version_info # type: ignore + if pypy_version_info.releaselevel == "final": + pypy_version_info = pypy_version_info[:3] + data["implementation"]["version"] = ".".join( + [str(x) for x in pypy_version_info] + ) + elif data["implementation"]["name"] == "Jython": + # Complete Guess + data["implementation"]["version"] = platform.python_version() + elif data["implementation"]["name"] == "IronPython": + # Complete Guess + data["implementation"]["version"] = platform.python_version() + + if sys.platform.startswith("linux"): + from pip._vendor import distro + + linux_distribution = distro.name(), distro.version(), distro.codename() + distro_infos: Dict[str, Any] = dict( + filter( + lambda x: x[1], + zip(["name", "version", "id"], linux_distribution), + ) + ) + libc = dict( + filter( + lambda x: x[1], + zip(["lib", "version"], libc_ver()), + ) + ) + if libc: + distro_infos["libc"] = libc + if distro_infos: + data["distro"] = distro_infos + + if sys.platform.startswith("darwin") and platform.mac_ver()[0]: + data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]} + + if platform.system(): + data.setdefault("system", {})["name"] = platform.system() + + if platform.release(): + data.setdefault("system", {})["release"] = platform.release() + + if platform.machine(): + data["cpu"] = platform.machine() + + if has_tls(): + import _ssl as ssl + + data["openssl_version"] = ssl.OPENSSL_VERSION + + setuptools_dist = get_default_environment().get_distribution("setuptools") + if setuptools_dist is not None: + data["setuptools_version"] = str(setuptools_dist.version) + + if shutil.which("rustc") is not None: + # If for any reason `rustc --version` fails, silently ignore it + try: + rustc_output = subprocess.check_output( + ["rustc", "--version"], stderr=subprocess.STDOUT, timeout=0.5 + ) + except Exception: + pass + else: + if rustc_output.startswith(b"rustc "): + # The format of `rustc --version` is: + # `b'rustc 1.52.1 (9bc8c42bb 2021-05-09)\n'` + # We extract just the middle (1.52.1) part + data["rustc_version"] = rustc_output.split(b" ")[1].decode() + + # Use None rather than False so as not to give the impression that + # pip knows it is not being run under CI. Rather, it is a null or + # inconclusive result. Also, we include some value rather than no + # value to make it easier to know that the check has been run. + data["ci"] = True if looks_like_ci() else None + + user_data = os.environ.get("PIP_USER_AGENT_USER_DATA") + if user_data is not None: + data["user_data"] = user_data + + return "{data[installer][name]}/{data[installer][version]} {json}".format( + data=data, + json=json.dumps(data, separators=(",", ":"), sort_keys=True), + ) + + +class LocalFSAdapter(BaseAdapter): + def send( + self, + request: PreparedRequest, + stream: bool = False, + timeout: Optional[Union[float, Tuple[float, float]]] = None, + verify: Union[bool, str] = True, + cert: Optional[Union[str, Tuple[str, str]]] = None, + proxies: Optional[Mapping[str, str]] = None, + ) -> Response: + pathname = url_to_path(request.url) + + resp = Response() + resp.status_code = 200 + resp.url = request.url + + try: + stats = os.stat(pathname) + except OSError as exc: + # format the exception raised as a io.BytesIO object, + # to return a better error message: + resp.status_code = 404 + resp.reason = type(exc).__name__ + resp.raw = io.BytesIO(f"{resp.reason}: {exc}".encode()) + else: + modified = email.utils.formatdate(stats.st_mtime, usegmt=True) + content_type = mimetypes.guess_type(pathname)[0] or "text/plain" + resp.headers = CaseInsensitiveDict( + { + "Content-Type": content_type, + "Content-Length": stats.st_size, + "Last-Modified": modified, + } + ) + + resp.raw = open(pathname, "rb") + resp.close = resp.raw.close + + return resp + + def close(self) -> None: + pass + + +class _SSLContextAdapterMixin: + """Mixin to add the ``ssl_context`` constructor argument to HTTP adapters. + + The additional argument is forwarded directly to the pool manager. This allows us + to dynamically decide what SSL store to use at runtime, which is used to implement + the optional ``truststore`` backend. + """ + + def __init__( + self, + *, + ssl_context: Optional["SSLContext"] = None, + **kwargs: Any, + ) -> None: + self._ssl_context = ssl_context + super().__init__(**kwargs) + + def init_poolmanager( + self, + connections: int, + maxsize: int, + block: bool = DEFAULT_POOLBLOCK, + **pool_kwargs: Any, + ) -> "PoolManager": + if self._ssl_context is not None: + pool_kwargs.setdefault("ssl_context", self._ssl_context) + return super().init_poolmanager( # type: ignore[misc] + connections=connections, + maxsize=maxsize, + block=block, + **pool_kwargs, + ) + + +class HTTPAdapter(_SSLContextAdapterMixin, _BaseHTTPAdapter): + pass + + +class CacheControlAdapter(_SSLContextAdapterMixin, _BaseCacheControlAdapter): + pass + + +class InsecureHTTPAdapter(HTTPAdapter): + def cert_verify( + self, + conn: ConnectionPool, + url: str, + verify: Union[bool, str], + cert: Optional[Union[str, Tuple[str, str]]], + ) -> None: + super().cert_verify(conn=conn, url=url, verify=False, cert=cert) + + +class InsecureCacheControlAdapter(CacheControlAdapter): + def cert_verify( + self, + conn: ConnectionPool, + url: str, + verify: Union[bool, str], + cert: Optional[Union[str, Tuple[str, str]]], + ) -> None: + super().cert_verify(conn=conn, url=url, verify=False, cert=cert) + + +class PipSession(requests.Session): + timeout: Optional[int] = None + + def __init__( + self, + *args: Any, + retries: int = 0, + cache: Optional[str] = None, + trusted_hosts: Sequence[str] = (), + index_urls: Optional[List[str]] = None, + ssl_context: Optional["SSLContext"] = None, + **kwargs: Any, + ) -> None: + """ + :param trusted_hosts: Domains not to emit warnings for when not using + HTTPS. + """ + super().__init__(*args, **kwargs) + + # Namespace the attribute with "pip_" just in case to prevent + # possible conflicts with the base class. + self.pip_trusted_origins: List[Tuple[str, Optional[int]]] = [] + self.pip_proxy = None + + # Attach our User Agent to the request + self.headers["User-Agent"] = user_agent() + + # Attach our Authentication handler to the session + self.auth = MultiDomainBasicAuth(index_urls=index_urls) + + # Create our urllib3.Retry instance which will allow us to customize + # how we handle retries. + retries = urllib3.Retry( + # Set the total number of retries that a particular request can + # have. + total=retries, + # A 503 error from PyPI typically means that the Fastly -> Origin + # connection got interrupted in some way. A 503 error in general + # is typically considered a transient error so we'll go ahead and + # retry it. + # A 500 may indicate transient error in Amazon S3 + # A 502 may be a transient error from a CDN like CloudFlare or CloudFront + # A 520 or 527 - may indicate transient error in CloudFlare + status_forcelist=[500, 502, 503, 520, 527], + # Add a small amount of back off between failed requests in + # order to prevent hammering the service. + backoff_factor=0.25, + ) # type: ignore + + # Our Insecure HTTPAdapter disables HTTPS validation. It does not + # support caching so we'll use it for all http:// URLs. + # If caching is disabled, we will also use it for + # https:// hosts that we've marked as ignoring + # TLS errors for (trusted-hosts). + insecure_adapter = InsecureHTTPAdapter(max_retries=retries) + + # We want to _only_ cache responses on securely fetched origins or when + # the host is specified as trusted. We do this because + # we can't validate the response of an insecurely/untrusted fetched + # origin, and we don't want someone to be able to poison the cache and + # require manual eviction from the cache to fix it. + if cache: + secure_adapter = CacheControlAdapter( + cache=SafeFileCache(cache), + max_retries=retries, + ssl_context=ssl_context, + ) + self._trusted_host_adapter = InsecureCacheControlAdapter( + cache=SafeFileCache(cache), + max_retries=retries, + ) + else: + secure_adapter = HTTPAdapter(max_retries=retries, ssl_context=ssl_context) + self._trusted_host_adapter = insecure_adapter + + self.mount("https://", secure_adapter) + self.mount("http://", insecure_adapter) + + # Enable file:// urls + self.mount("file://", LocalFSAdapter()) + + for host in trusted_hosts: + self.add_trusted_host(host, suppress_logging=True) + + def update_index_urls(self, new_index_urls: List[str]) -> None: + """ + :param new_index_urls: New index urls to update the authentication + handler with. + """ + self.auth.index_urls = new_index_urls + + def add_trusted_host( + self, host: str, source: Optional[str] = None, suppress_logging: bool = False + ) -> None: + """ + :param host: It is okay to provide a host that has previously been + added. + :param source: An optional source string, for logging where the host + string came from. + """ + if not suppress_logging: + msg = f"adding trusted host: {host!r}" + if source is not None: + msg += f" (from {source})" + logger.info(msg) + + parsed_host, parsed_port = parse_netloc(host) + if parsed_host is None: + raise ValueError(f"Trusted host URL must include a host part: {host!r}") + if (parsed_host, parsed_port) not in self.pip_trusted_origins: + self.pip_trusted_origins.append((parsed_host, parsed_port)) + + self.mount( + build_url_from_netloc(host, scheme="http") + "/", self._trusted_host_adapter + ) + self.mount(build_url_from_netloc(host) + "/", self._trusted_host_adapter) + if not parsed_port: + self.mount( + build_url_from_netloc(host, scheme="http") + ":", + self._trusted_host_adapter, + ) + # Mount wildcard ports for the same host. + self.mount(build_url_from_netloc(host) + ":", self._trusted_host_adapter) + + def iter_secure_origins(self) -> Generator[SecureOrigin, None, None]: + yield from SECURE_ORIGINS + for host, port in self.pip_trusted_origins: + yield ("*", host, "*" if port is None else port) + + def is_secure_origin(self, location: Link) -> bool: + # Determine if this url used a secure transport mechanism + parsed = urllib.parse.urlparse(str(location)) + origin_protocol, origin_host, origin_port = ( + parsed.scheme, + parsed.hostname, + parsed.port, + ) + + # The protocol to use to see if the protocol matches. + # Don't count the repository type as part of the protocol: in + # cases such as "git+ssh", only use "ssh". (I.e., Only verify against + # the last scheme.) + origin_protocol = origin_protocol.rsplit("+", 1)[-1] + + # Determine if our origin is a secure origin by looking through our + # hardcoded list of secure origins, as well as any additional ones + # configured on this PackageFinder instance. + for secure_origin in self.iter_secure_origins(): + secure_protocol, secure_host, secure_port = secure_origin + if origin_protocol != secure_protocol and secure_protocol != "*": + continue + + try: + addr = ipaddress.ip_address(origin_host or "") + network = ipaddress.ip_network(secure_host) + except ValueError: + # We don't have both a valid address or a valid network, so + # we'll check this origin against hostnames. + if ( + origin_host + and origin_host.lower() != secure_host.lower() + and secure_host != "*" + ): + continue + else: + # We have a valid address and network, so see if the address + # is contained within the network. + if addr not in network: + continue + + # Check to see if the port matches. + if ( + origin_port != secure_port + and secure_port != "*" + and secure_port is not None + ): + continue + + # If we've gotten here, then this origin matches the current + # secure origin and we should return True + return True + + # If we've gotten to this point, then the origin isn't secure and we + # will not accept it as a valid location to search. We will however + # log a warning that we are ignoring it. + logger.warning( + "The repository located at %s is not a trusted or secure host and " + "is being ignored. If this repository is available via HTTPS we " + "recommend you use HTTPS instead, otherwise you may silence " + "this warning and allow it anyway with '--trusted-host %s'.", + origin_host, + origin_host, + ) + + return False + + def request(self, method: str, url: str, *args: Any, **kwargs: Any) -> Response: + # Allow setting a default timeout on a session + kwargs.setdefault("timeout", self.timeout) + # Allow setting a default proxies on a session + kwargs.setdefault("proxies", self.proxies) + + # Dispatch the actual request + return super().request(method, url, *args, **kwargs) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/utils.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bba4c265e89b1ce570ceeeebf1a321eebec919b4 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/utils.py @@ -0,0 +1,98 @@ +from typing import Dict, Generator + +from pip._vendor.requests.models import Response + +from pip._internal.exceptions import NetworkConnectionError + +# The following comments and HTTP headers were originally added by +# Donald Stufft in git commit 22c562429a61bb77172039e480873fb239dd8c03. +# +# We use Accept-Encoding: identity here because requests defaults to +# accepting compressed responses. This breaks in a variety of ways +# depending on how the server is configured. +# - Some servers will notice that the file isn't a compressible file +# and will leave the file alone and with an empty Content-Encoding +# - Some servers will notice that the file is already compressed and +# will leave the file alone, adding a Content-Encoding: gzip header +# - Some servers won't notice anything at all and will take a file +# that's already been compressed and compress it again, and set +# the Content-Encoding: gzip header +# By setting this to request only the identity encoding we're hoping +# to eliminate the third case. Hopefully there does not exist a server +# which when given a file will notice it is already compressed and that +# you're not asking for a compressed file and will then decompress it +# before sending because if that's the case I don't think it'll ever be +# possible to make this work. +HEADERS: Dict[str, str] = {"Accept-Encoding": "identity"} + +DOWNLOAD_CHUNK_SIZE = 256 * 1024 + + +def raise_for_status(resp: Response) -> None: + http_error_msg = "" + if isinstance(resp.reason, bytes): + # We attempt to decode utf-8 first because some servers + # choose to localize their reason strings. If the string + # isn't utf-8, we fall back to iso-8859-1 for all other + # encodings. + try: + reason = resp.reason.decode("utf-8") + except UnicodeDecodeError: + reason = resp.reason.decode("iso-8859-1") + else: + reason = resp.reason + + if 400 <= resp.status_code < 500: + http_error_msg = ( + f"{resp.status_code} Client Error: {reason} for url: {resp.url}" + ) + + elif 500 <= resp.status_code < 600: + http_error_msg = ( + f"{resp.status_code} Server Error: {reason} for url: {resp.url}" + ) + + if http_error_msg: + raise NetworkConnectionError(http_error_msg, response=resp) + + +def response_chunks( + response: Response, chunk_size: int = DOWNLOAD_CHUNK_SIZE +) -> Generator[bytes, None, None]: + """Given a requests Response, provide the data chunks.""" + try: + # Special case for urllib3. + for chunk in response.raw.stream( + chunk_size, + # We use decode_content=False here because we don't + # want urllib3 to mess with the raw bytes we get + # from the server. If we decompress inside of + # urllib3 then we cannot verify the checksum + # because the checksum will be of the compressed + # file. This breakage will only occur if the + # server adds a Content-Encoding header, which + # depends on how the server was configured: + # - Some servers will notice that the file isn't a + # compressible file and will leave the file alone + # and with an empty Content-Encoding + # - Some servers will notice that the file is + # already compressed and will leave the file + # alone and will add a Content-Encoding: gzip + # header + # - Some servers won't notice anything at all and + # will take a file that's already been compressed + # and compress it again and set the + # Content-Encoding: gzip header + # + # By setting this not to decode automatically we + # hope to eliminate problems with the second case. + decode_content=False, + ): + yield chunk + except AttributeError: + # Standard file-like object. + while True: + chunk = response.raw.read(chunk_size) + if not chunk: + break + yield chunk diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py new file mode 100644 index 0000000000000000000000000000000000000000..22ec8d2f4a6b276aedf2249d50ff10a21922513c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/network/xmlrpc.py @@ -0,0 +1,62 @@ +"""xmlrpclib.Transport implementation +""" + +import logging +import urllib.parse +import xmlrpc.client +from typing import TYPE_CHECKING, Tuple + +from pip._internal.exceptions import NetworkConnectionError +from pip._internal.network.session import PipSession +from pip._internal.network.utils import raise_for_status + +if TYPE_CHECKING: + from xmlrpc.client import _HostType, _Marshallable + + from _typeshed import SizedBuffer + +logger = logging.getLogger(__name__) + + +class PipXmlrpcTransport(xmlrpc.client.Transport): + """Provide a `xmlrpclib.Transport` implementation via a `PipSession` + object. + """ + + def __init__( + self, index_url: str, session: PipSession, use_datetime: bool = False + ) -> None: + super().__init__(use_datetime) + index_parts = urllib.parse.urlparse(index_url) + self._scheme = index_parts.scheme + self._session = session + + def request( + self, + host: "_HostType", + handler: str, + request_body: "SizedBuffer", + verbose: bool = False, + ) -> Tuple["_Marshallable", ...]: + assert isinstance(host, str) + parts = (self._scheme, host, handler, None, None, None) + url = urllib.parse.urlunparse(parts) + try: + headers = {"Content-Type": "text/xml"} + response = self._session.post( + url, + data=request_body, + headers=headers, + stream=True, + ) + raise_for_status(response) + self.verbose = verbose + return self.parse_response(response.raw) + except NetworkConnectionError as exc: + assert exc.response + logger.critical( + "HTTP error %s while getting %s", + exc.response.status_code, + url, + ) + raise diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64724f377ef4c32152983bd369e25f90c6d8340c Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/check.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/check.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95f52fcceef9d44be1771fc602d706e7c05e0802 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/check.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/freeze.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/freeze.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e61f7ba587d992f5be368bfc421f2c17323dea0e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/freeze.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/prepare.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/prepare.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2bab8f25100ef4766884eacae6d7da40fd401b4 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/__pycache__/prepare.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bfd8870ebcb1cd11bcc6e9abd8c4cab5a5ded7e Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/build_tracker.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/build_tracker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3eead6441e5dadd3af27e010fd24af6fbfe511f Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/build_tracker.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d4773373b9943c6322c2ca763eb88101a2318ed Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f305df12961b83fe88ee903fde73340b0e756307 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/metadata_editable.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0fb7f38328329aa936e312505bef303ed82893b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43c433ac9752ce46a53f32f9aa0a9a21b96dd228 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/wheel_editable.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/wheel_editable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7698d5bbe4e43786e31e52f98ab010a75b2fe24d Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/wheel_editable.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..568be00bae139586b9d32d9553c7a826a167efcf Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/build_tracker.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/build_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed8dd235960bf406e26d5c0069b12c7f2d463e9 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/build_tracker.py @@ -0,0 +1,138 @@ +import contextlib +import hashlib +import logging +import os +from types import TracebackType +from typing import Dict, Generator, Optional, Type, Union + +from pip._internal.req.req_install import InstallRequirement +from pip._internal.utils.temp_dir import TempDirectory + +logger = logging.getLogger(__name__) + + +@contextlib.contextmanager +def update_env_context_manager(**changes: str) -> Generator[None, None, None]: + target = os.environ + + # Save values from the target and change them. + non_existent_marker = object() + saved_values: Dict[str, Union[object, str]] = {} + for name, new_value in changes.items(): + try: + saved_values[name] = target[name] + except KeyError: + saved_values[name] = non_existent_marker + target[name] = new_value + + try: + yield + finally: + # Restore original values in the target. + for name, original_value in saved_values.items(): + if original_value is non_existent_marker: + del target[name] + else: + assert isinstance(original_value, str) # for mypy + target[name] = original_value + + +@contextlib.contextmanager +def get_build_tracker() -> Generator["BuildTracker", None, None]: + root = os.environ.get("PIP_BUILD_TRACKER") + with contextlib.ExitStack() as ctx: + if root is None: + root = ctx.enter_context(TempDirectory(kind="build-tracker")).path + ctx.enter_context(update_env_context_manager(PIP_BUILD_TRACKER=root)) + logger.debug("Initialized build tracking at %s", root) + + with BuildTracker(root) as tracker: + yield tracker + + +class TrackerId(str): + """Uniquely identifying string provided to the build tracker.""" + + +class BuildTracker: + """Ensure that an sdist cannot request itself as a setup requirement. + + When an sdist is prepared, it identifies its setup requirements in the + context of ``BuildTracker.track()``. If a requirement shows up recursively, this + raises an exception. + + This stops fork bombs embedded in malicious packages.""" + + def __init__(self, root: str) -> None: + self._root = root + self._entries: Dict[TrackerId, InstallRequirement] = {} + logger.debug("Created build tracker: %s", self._root) + + def __enter__(self) -> "BuildTracker": + logger.debug("Entered build tracker: %s", self._root) + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + self.cleanup() + + def _entry_path(self, key: TrackerId) -> str: + hashed = hashlib.sha224(key.encode()).hexdigest() + return os.path.join(self._root, hashed) + + def add(self, req: InstallRequirement, key: TrackerId) -> None: + """Add an InstallRequirement to build tracking.""" + + # Get the file to write information about this requirement. + entry_path = self._entry_path(key) + + # Try reading from the file. If it exists and can be read from, a build + # is already in progress, so a LookupError is raised. + try: + with open(entry_path) as fp: + contents = fp.read() + except FileNotFoundError: + pass + else: + message = f"{req.link} is already being built: {contents}" + raise LookupError(message) + + # If we're here, req should really not be building already. + assert key not in self._entries + + # Start tracking this requirement. + with open(entry_path, "w", encoding="utf-8") as fp: + fp.write(str(req)) + self._entries[key] = req + + logger.debug("Added %s to build tracker %r", req, self._root) + + def remove(self, req: InstallRequirement, key: TrackerId) -> None: + """Remove an InstallRequirement from build tracking.""" + + # Delete the created file and the corresponding entry. + os.unlink(self._entry_path(key)) + del self._entries[key] + + logger.debug("Removed %s from build tracker %r", req, self._root) + + def cleanup(self) -> None: + for key, req in list(self._entries.items()): + self.remove(req, key) + + logger.debug("Removed build tracker: %r", self._root) + + @contextlib.contextmanager + def track(self, req: InstallRequirement, key: str) -> Generator[None, None, None]: + """Ensure that `key` cannot install itself as a setup requirement. + + :raises LookupError: If `key` was already provided in a parent invocation of + the context introduced by this method.""" + tracker_id = TrackerId(key) + self.add(req, tracker_id) + yield + self.remove(req, tracker_id) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/metadata.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..c66ac354deb035405fe0e4040dac539d28570257 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/metadata.py @@ -0,0 +1,39 @@ +"""Metadata generation logic for source distributions. +""" + +import os + +from pip._vendor.pyproject_hooks import BuildBackendHookCaller + +from pip._internal.build_env import BuildEnvironment +from pip._internal.exceptions import ( + InstallationSubprocessError, + MetadataGenerationFailed, +) +from pip._internal.utils.subprocess import runner_with_spinner_message +from pip._internal.utils.temp_dir import TempDirectory + + +def generate_metadata( + build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str +) -> str: + """Generate metadata using mechanisms described in PEP 517. + + Returns the generated metadata directory. + """ + metadata_tmpdir = TempDirectory(kind="modern-metadata", globally_managed=True) + + metadata_dir = metadata_tmpdir.path + + with build_env: + # Note that BuildBackendHookCaller implements a fallback for + # prepare_metadata_for_build_wheel, so we don't have to + # consider the possibility that this hook doesn't exist. + runner = runner_with_spinner_message("Preparing metadata (pyproject.toml)") + with backend.subprocess_runner(runner): + try: + distinfo_dir = backend.prepare_metadata_for_build_wheel(metadata_dir) + except InstallationSubprocessError as error: + raise MetadataGenerationFailed(package_details=details) from error + + return os.path.join(metadata_dir, distinfo_dir) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/metadata_editable.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/metadata_editable.py new file mode 100644 index 0000000000000000000000000000000000000000..3397ccf0f92d5903281866a693979fdcfa7d3d61 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/metadata_editable.py @@ -0,0 +1,42 @@ +"""Metadata generation logic for source distributions. +""" + +import os + +from pip._vendor.pyproject_hooks import BuildBackendHookCaller + +from pip._internal.build_env import BuildEnvironment +from pip._internal.exceptions import ( + InstallationSubprocessError, + MetadataGenerationFailed, +) +from pip._internal.utils.subprocess import runner_with_spinner_message +from pip._internal.utils.temp_dir import TempDirectory + + +def generate_editable_metadata( + build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str +) -> str: + """Generate metadata using mechanisms described in PEP 660. + + Returns the generated metadata directory. + """ + metadata_tmpdir = TempDirectory(kind="modern-metadata", globally_managed=True) + + metadata_dir = metadata_tmpdir.path + + with build_env: + # Note that BuildBackendHookCaller implements a fallback for + # prepare_metadata_for_build_wheel/editable, so we don't have to + # consider the possibility that this hook doesn't exist. + runner = runner_with_spinner_message( + "Preparing editable metadata (pyproject.toml)" + ) + with backend.subprocess_runner(runner): + try: + distinfo_dir = backend.prepare_metadata_for_build_editable(metadata_dir) + except InstallationSubprocessError as error: + raise MetadataGenerationFailed(package_details=details) from error + + assert distinfo_dir is not None + return os.path.join(metadata_dir, distinfo_dir) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/metadata_legacy.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/metadata_legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..c01dd1c678a083c17190fc9b7e214eca5c91f4f1 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/metadata_legacy.py @@ -0,0 +1,74 @@ +"""Metadata generation logic for legacy source distributions. +""" + +import logging +import os + +from pip._internal.build_env import BuildEnvironment +from pip._internal.cli.spinners import open_spinner +from pip._internal.exceptions import ( + InstallationError, + InstallationSubprocessError, + MetadataGenerationFailed, +) +from pip._internal.utils.setuptools_build import make_setuptools_egg_info_args +from pip._internal.utils.subprocess import call_subprocess +from pip._internal.utils.temp_dir import TempDirectory + +logger = logging.getLogger(__name__) + + +def _find_egg_info(directory: str) -> str: + """Find an .egg-info subdirectory in `directory`.""" + filenames = [f for f in os.listdir(directory) if f.endswith(".egg-info")] + + if not filenames: + raise InstallationError(f"No .egg-info directory found in {directory}") + + if len(filenames) > 1: + raise InstallationError( + f"More than one .egg-info directory found in {directory}" + ) + + return os.path.join(directory, filenames[0]) + + +def generate_metadata( + build_env: BuildEnvironment, + setup_py_path: str, + source_dir: str, + isolated: bool, + details: str, +) -> str: + """Generate metadata using setup.py-based defacto mechanisms. + + Returns the generated metadata directory. + """ + logger.debug( + "Running setup.py (path:%s) egg_info for package %s", + setup_py_path, + details, + ) + + egg_info_dir = TempDirectory(kind="pip-egg-info", globally_managed=True).path + + args = make_setuptools_egg_info_args( + setup_py_path, + egg_info_dir=egg_info_dir, + no_user_config=isolated, + ) + + with build_env: + with open_spinner("Preparing metadata (setup.py)") as spinner: + try: + call_subprocess( + args, + cwd=source_dir, + command_desc="python setup.py egg_info", + spinner=spinner, + ) + except InstallationSubprocessError as error: + raise MetadataGenerationFailed(package_details=details) from error + + # Return the .egg-info directory. + return _find_egg_info(egg_info_dir) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/wheel.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..064811ad11bb07b2b7bc8e30ec6c03f21997d6b2 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/wheel.py @@ -0,0 +1,37 @@ +import logging +import os +from typing import Optional + +from pip._vendor.pyproject_hooks import BuildBackendHookCaller + +from pip._internal.utils.subprocess import runner_with_spinner_message + +logger = logging.getLogger(__name__) + + +def build_wheel_pep517( + name: str, + backend: BuildBackendHookCaller, + metadata_directory: str, + tempd: str, +) -> Optional[str]: + """Build one InstallRequirement using the PEP 517 build process. + + Returns path to wheel if successfully built. Otherwise, returns None. + """ + assert metadata_directory is not None + try: + logger.debug("Destination directory: %s", tempd) + + runner = runner_with_spinner_message( + f"Building wheel for {name} (pyproject.toml)" + ) + with backend.subprocess_runner(runner): + wheel_name = backend.build_wheel( + tempd, + metadata_directory=metadata_directory, + ) + except Exception: + logger.error("Failed building wheel for %s", name) + return None + return os.path.join(tempd, wheel_name) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/wheel_editable.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/wheel_editable.py new file mode 100644 index 0000000000000000000000000000000000000000..719d69dd801b78b360c6c2234080eee638b8de82 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/wheel_editable.py @@ -0,0 +1,46 @@ +import logging +import os +from typing import Optional + +from pip._vendor.pyproject_hooks import BuildBackendHookCaller, HookMissing + +from pip._internal.utils.subprocess import runner_with_spinner_message + +logger = logging.getLogger(__name__) + + +def build_wheel_editable( + name: str, + backend: BuildBackendHookCaller, + metadata_directory: str, + tempd: str, +) -> Optional[str]: + """Build one InstallRequirement using the PEP 660 build process. + + Returns path to wheel if successfully built. Otherwise, returns None. + """ + assert metadata_directory is not None + try: + logger.debug("Destination directory: %s", tempd) + + runner = runner_with_spinner_message( + f"Building editable for {name} (pyproject.toml)" + ) + with backend.subprocess_runner(runner): + try: + wheel_name = backend.build_editable( + tempd, + metadata_directory=metadata_directory, + ) + except HookMissing as e: + logger.error( + "Cannot build editable %s because the build " + "backend does not have the %s hook", + name, + e, + ) + return None + except Exception: + logger.error("Failed building editable for %s", name) + return None + return os.path.join(tempd, wheel_name) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/wheel_legacy.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/wheel_legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..3ee2a7058d323e41f3c930f14685f68e6a599fa5 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/build/wheel_legacy.py @@ -0,0 +1,102 @@ +import logging +import os.path +from typing import List, Optional + +from pip._internal.cli.spinners import open_spinner +from pip._internal.utils.setuptools_build import make_setuptools_bdist_wheel_args +from pip._internal.utils.subprocess import call_subprocess, format_command_args + +logger = logging.getLogger(__name__) + + +def format_command_result( + command_args: List[str], + command_output: str, +) -> str: + """Format command information for logging.""" + command_desc = format_command_args(command_args) + text = f"Command arguments: {command_desc}\n" + + if not command_output: + text += "Command output: None" + elif logger.getEffectiveLevel() > logging.DEBUG: + text += "Command output: [use --verbose to show]" + else: + if not command_output.endswith("\n"): + command_output += "\n" + text += f"Command output:\n{command_output}" + + return text + + +def get_legacy_build_wheel_path( + names: List[str], + temp_dir: str, + name: str, + command_args: List[str], + command_output: str, +) -> Optional[str]: + """Return the path to the wheel in the temporary build directory.""" + # Sort for determinism. + names = sorted(names) + if not names: + msg = f"Legacy build of wheel for {name!r} created no files.\n" + msg += format_command_result(command_args, command_output) + logger.warning(msg) + return None + + if len(names) > 1: + msg = ( + f"Legacy build of wheel for {name!r} created more than one file.\n" + f"Filenames (choosing first): {names}\n" + ) + msg += format_command_result(command_args, command_output) + logger.warning(msg) + + return os.path.join(temp_dir, names[0]) + + +def build_wheel_legacy( + name: str, + setup_py_path: str, + source_dir: str, + global_options: List[str], + build_options: List[str], + tempd: str, +) -> Optional[str]: + """Build one unpacked package using the "legacy" build process. + + Returns path to wheel if successfully built. Otherwise, returns None. + """ + wheel_args = make_setuptools_bdist_wheel_args( + setup_py_path, + global_options=global_options, + build_options=build_options, + destination_dir=tempd, + ) + + spin_message = f"Building wheel for {name} (setup.py)" + with open_spinner(spin_message) as spinner: + logger.debug("Destination directory: %s", tempd) + + try: + output = call_subprocess( + wheel_args, + command_desc="python setup.py bdist_wheel", + cwd=source_dir, + spinner=spinner, + ) + except Exception: + spinner.finish("error") + logger.error("Failed building wheel for %s", name) + return None + + names = os.listdir(tempd) + wheel_path = get_legacy_build_wheel_path( + names=names, + temp_dir=tempd, + name=name, + command_args=wheel_args, + command_output=output, + ) + return wheel_path diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/check.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6fbc4c37599588ad69da3dc8a4d9628dc89b96 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/check.py @@ -0,0 +1,181 @@ +"""Validation of dependencies of packages +""" + +import logging +from contextlib import suppress +from email.parser import Parser +from functools import reduce +from typing import ( + Callable, + Dict, + FrozenSet, + Generator, + Iterable, + List, + NamedTuple, + Optional, + Set, + Tuple, +) + +from pip._vendor.packaging.requirements import Requirement +from pip._vendor.packaging.tags import Tag, parse_tag +from pip._vendor.packaging.utils import NormalizedName, canonicalize_name +from pip._vendor.packaging.version import Version + +from pip._internal.distributions import make_distribution_for_install_requirement +from pip._internal.metadata import get_default_environment +from pip._internal.metadata.base import BaseDistribution +from pip._internal.req.req_install import InstallRequirement + +logger = logging.getLogger(__name__) + + +class PackageDetails(NamedTuple): + version: Version + dependencies: List[Requirement] + + +# Shorthands +PackageSet = Dict[NormalizedName, PackageDetails] +Missing = Tuple[NormalizedName, Requirement] +Conflicting = Tuple[NormalizedName, Version, Requirement] + +MissingDict = Dict[NormalizedName, List[Missing]] +ConflictingDict = Dict[NormalizedName, List[Conflicting]] +CheckResult = Tuple[MissingDict, ConflictingDict] +ConflictDetails = Tuple[PackageSet, CheckResult] + + +def create_package_set_from_installed() -> Tuple[PackageSet, bool]: + """Converts a list of distributions into a PackageSet.""" + package_set = {} + problems = False + env = get_default_environment() + for dist in env.iter_installed_distributions(local_only=False, skip=()): + name = dist.canonical_name + try: + dependencies = list(dist.iter_dependencies()) + package_set[name] = PackageDetails(dist.version, dependencies) + except (OSError, ValueError) as e: + # Don't crash on unreadable or broken metadata. + logger.warning("Error parsing dependencies of %s: %s", name, e) + problems = True + return package_set, problems + + +def check_package_set( + package_set: PackageSet, should_ignore: Optional[Callable[[str], bool]] = None +) -> CheckResult: + """Check if a package set is consistent + + If should_ignore is passed, it should be a callable that takes a + package name and returns a boolean. + """ + + missing = {} + conflicting = {} + + for package_name, package_detail in package_set.items(): + # Info about dependencies of package_name + missing_deps: Set[Missing] = set() + conflicting_deps: Set[Conflicting] = set() + + if should_ignore and should_ignore(package_name): + continue + + for req in package_detail.dependencies: + name = canonicalize_name(req.name) + + # Check if it's missing + if name not in package_set: + missed = True + if req.marker is not None: + missed = req.marker.evaluate({"extra": ""}) + if missed: + missing_deps.add((name, req)) + continue + + # Check if there's a conflict + version = package_set[name].version + if not req.specifier.contains(version, prereleases=True): + conflicting_deps.add((name, version, req)) + + if missing_deps: + missing[package_name] = sorted(missing_deps, key=str) + if conflicting_deps: + conflicting[package_name] = sorted(conflicting_deps, key=str) + + return missing, conflicting + + +def check_install_conflicts(to_install: List[InstallRequirement]) -> ConflictDetails: + """For checking if the dependency graph would be consistent after \ + installing given requirements + """ + # Start from the current state + package_set, _ = create_package_set_from_installed() + # Install packages + would_be_installed = _simulate_installation_of(to_install, package_set) + + # Only warn about directly-dependent packages; create a whitelist of them + whitelist = _create_whitelist(would_be_installed, package_set) + + return ( + package_set, + check_package_set( + package_set, should_ignore=lambda name: name not in whitelist + ), + ) + + +def check_unsupported( + packages: Iterable[BaseDistribution], + supported_tags: Iterable[Tag], +) -> Generator[BaseDistribution, None, None]: + for p in packages: + with suppress(FileNotFoundError): + wheel_file = p.read_text("WHEEL") + wheel_tags: FrozenSet[Tag] = reduce( + frozenset.union, + map(parse_tag, Parser().parsestr(wheel_file).get_all("Tag", [])), + frozenset(), + ) + if wheel_tags.isdisjoint(supported_tags): + yield p + + +def _simulate_installation_of( + to_install: List[InstallRequirement], package_set: PackageSet +) -> Set[NormalizedName]: + """Computes the version of packages after installing to_install.""" + # Keep track of packages that were installed + installed = set() + + # Modify it as installing requirement_set would (assuming no errors) + for inst_req in to_install: + abstract_dist = make_distribution_for_install_requirement(inst_req) + dist = abstract_dist.get_metadata_distribution() + name = dist.canonical_name + package_set[name] = PackageDetails(dist.version, list(dist.iter_dependencies())) + + installed.add(name) + + return installed + + +def _create_whitelist( + would_be_installed: Set[NormalizedName], package_set: PackageSet +) -> Set[NormalizedName]: + packages_affected = set(would_be_installed) + + for package_name in package_set: + if package_name in packages_affected: + continue + + for req in package_set[package_name].dependencies: + if canonicalize_name(req.name) in packages_affected: + packages_affected.add(package_name) + break + + return packages_affected diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/freeze.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/freeze.py new file mode 100644 index 0000000000000000000000000000000000000000..ae5dd37f9db6e50dd48de55660bcb90e80b0ea64 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/freeze.py @@ -0,0 +1,256 @@ +import collections +import logging +import os +from dataclasses import dataclass, field +from typing import Container, Dict, Generator, Iterable, List, NamedTuple, Optional, Set + +from pip._vendor.packaging.utils import NormalizedName, canonicalize_name +from pip._vendor.packaging.version import InvalidVersion + +from pip._internal.exceptions import BadCommand, InstallationError +from pip._internal.metadata import BaseDistribution, get_environment +from pip._internal.req.constructors import ( + install_req_from_editable, + install_req_from_line, +) +from pip._internal.req.req_file import COMMENT_RE +from pip._internal.utils.direct_url_helpers import direct_url_as_pep440_direct_reference + +logger = logging.getLogger(__name__) + + +class _EditableInfo(NamedTuple): + requirement: str + comments: List[str] + + +def freeze( + requirement: Optional[List[str]] = None, + local_only: bool = False, + user_only: bool = False, + paths: Optional[List[str]] = None, + isolated: bool = False, + exclude_editable: bool = False, + skip: Container[str] = (), +) -> Generator[str, None, None]: + installations: Dict[str, FrozenRequirement] = {} + + dists = get_environment(paths).iter_installed_distributions( + local_only=local_only, + skip=(), + user_only=user_only, + ) + for dist in dists: + req = FrozenRequirement.from_dist(dist) + if exclude_editable and req.editable: + continue + installations[req.canonical_name] = req + + if requirement: + # the options that don't get turned into an InstallRequirement + # should only be emitted once, even if the same option is in multiple + # requirements files, so we need to keep track of what has been emitted + # so that we don't emit it again if it's seen again + emitted_options: Set[str] = set() + # keep track of which files a requirement is in so that we can + # give an accurate warning if a requirement appears multiple times. + req_files: Dict[str, List[str]] = collections.defaultdict(list) + for req_file_path in requirement: + with open(req_file_path) as req_file: + for line in req_file: + if ( + not line.strip() + or line.strip().startswith("#") + or line.startswith( + ( + "-r", + "--requirement", + "-f", + "--find-links", + "-i", + "--index-url", + "--pre", + "--trusted-host", + "--process-dependency-links", + "--extra-index-url", + "--use-feature", + ) + ) + ): + line = line.rstrip() + if line not in emitted_options: + emitted_options.add(line) + yield line + continue + + if line.startswith("-e") or line.startswith("--editable"): + if line.startswith("-e"): + line = line[2:].strip() + else: + line = line[len("--editable") :].strip().lstrip("=") + line_req = install_req_from_editable( + line, + isolated=isolated, + ) + else: + line_req = install_req_from_line( + COMMENT_RE.sub("", line).strip(), + isolated=isolated, + ) + + if not line_req.name: + logger.info( + "Skipping line in requirement file [%s] because " + "it's not clear what it would install: %s", + req_file_path, + line.strip(), + ) + logger.info( + " (add #egg=PackageName to the URL to avoid" + " this warning)" + ) + else: + line_req_canonical_name = canonicalize_name(line_req.name) + if line_req_canonical_name not in installations: + # either it's not installed, or it is installed + # but has been processed already + if not req_files[line_req.name]: + logger.warning( + "Requirement file [%s] contains %s, but " + "package %r is not installed", + req_file_path, + COMMENT_RE.sub("", line).strip(), + line_req.name, + ) + else: + req_files[line_req.name].append(req_file_path) + else: + yield str(installations[line_req_canonical_name]).rstrip() + del installations[line_req_canonical_name] + req_files[line_req.name].append(req_file_path) + + # Warn about requirements that were included multiple times (in a + # single requirements file or in different requirements files). + for name, files in req_files.items(): + if len(files) > 1: + logger.warning( + "Requirement %s included multiple times [%s]", + name, + ", ".join(sorted(set(files))), + ) + + yield ("## The following requirements were added by pip freeze:") + for installation in sorted(installations.values(), key=lambda x: x.name.lower()): + if installation.canonical_name not in skip: + yield str(installation).rstrip() + + +def _format_as_name_version(dist: BaseDistribution) -> str: + try: + dist_version = dist.version + except InvalidVersion: + # legacy version + return f"{dist.raw_name}==={dist.raw_version}" + else: + return f"{dist.raw_name}=={dist_version}" + + +def _get_editable_info(dist: BaseDistribution) -> _EditableInfo: + """ + Compute and return values (req, comments) for use in + FrozenRequirement.from_dist(). + """ + editable_project_location = dist.editable_project_location + assert editable_project_location + location = os.path.normcase(os.path.abspath(editable_project_location)) + + from pip._internal.vcs import RemoteNotFoundError, RemoteNotValidError, vcs + + vcs_backend = vcs.get_backend_for_dir(location) + + if vcs_backend is None: + display = _format_as_name_version(dist) + logger.debug( + 'No VCS found for editable requirement "%s" in: %r', + display, + location, + ) + return _EditableInfo( + requirement=location, + comments=[f"# Editable install with no version control ({display})"], + ) + + vcs_name = type(vcs_backend).__name__ + + try: + req = vcs_backend.get_src_requirement(location, dist.raw_name) + except RemoteNotFoundError: + display = _format_as_name_version(dist) + return _EditableInfo( + requirement=location, + comments=[f"# Editable {vcs_name} install with no remote ({display})"], + ) + except RemoteNotValidError as ex: + display = _format_as_name_version(dist) + return _EditableInfo( + requirement=location, + comments=[ + f"# Editable {vcs_name} install ({display}) with either a deleted " + f"local remote or invalid URI:", + f"# '{ex.url}'", + ], + ) + except BadCommand: + logger.warning( + "cannot determine version of editable source in %s " + "(%s command not found in path)", + location, + vcs_backend.name, + ) + return _EditableInfo(requirement=location, comments=[]) + except InstallationError as exc: + logger.warning("Error when trying to get requirement for VCS system %s", exc) + else: + return _EditableInfo(requirement=req, comments=[]) + + logger.warning("Could not determine repository location of %s", location) + + return _EditableInfo( + requirement=location, + comments=["## !! Could not determine repository location"], + ) + + +@dataclass(frozen=True) +class FrozenRequirement: + name: str + req: str + editable: bool + comments: Iterable[str] = field(default_factory=tuple) + + @property + def canonical_name(self) -> NormalizedName: + return canonicalize_name(self.name) + + @classmethod + def from_dist(cls, dist: BaseDistribution) -> "FrozenRequirement": + editable = dist.editable + if editable: + req, comments = _get_editable_info(dist) + else: + comments = [] + direct_url = dist.direct_url + if direct_url: + # if PEP 610 metadata is present, use it + req = direct_url_as_pep440_direct_reference(direct_url, dist.raw_name) + else: + # name==version requirement + req = _format_as_name_version(dist) + + return cls(dist.raw_name, req, editable, comments=comments) + + def __str__(self) -> str: + req = self.req + if self.editable: + req = f"-e {req}" + return "\n".join(list(self.comments) + [str(req)]) + "\n" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..24d6a5dd31fe33b03f90ed0f9ee465253686900c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__init__.py @@ -0,0 +1,2 @@ +"""For modules related to installing packages. +""" diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe38c106ea5f390e95753ffdb86a38b1aaaa8153 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__pycache__/editable_legacy.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__pycache__/editable_legacy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d02078038fcb24d26929de26134fd864d768e8f8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__pycache__/editable_legacy.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__pycache__/wheel.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__pycache__/wheel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e6c02e625744c2d171d1503edb42468c94c92c0 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/__pycache__/wheel.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/editable_legacy.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/editable_legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..9aaa699a645e03d5971dbb5e43ff73d2f412a550 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/editable_legacy.py @@ -0,0 +1,47 @@ +"""Legacy editable installation process, i.e. `setup.py develop`. +""" + +import logging +from typing import Optional, Sequence + +from pip._internal.build_env import BuildEnvironment +from pip._internal.utils.logging import indent_log +from pip._internal.utils.setuptools_build import make_setuptools_develop_args +from pip._internal.utils.subprocess import call_subprocess + +logger = logging.getLogger(__name__) + + +def install_editable( + *, + global_options: Sequence[str], + prefix: Optional[str], + home: Optional[str], + use_user_site: bool, + name: str, + setup_py_path: str, + isolated: bool, + build_env: BuildEnvironment, + unpacked_source_directory: str, +) -> None: + """Install a package in editable mode. Most arguments are pass-through + to setuptools. + """ + logger.info("Running setup.py develop for %s", name) + + args = make_setuptools_develop_args( + setup_py_path, + global_options=global_options, + no_user_config=isolated, + prefix=prefix, + home=home, + use_user_site=use_user_site, + ) + + with indent_log(): + with build_env: + call_subprocess( + args, + command_desc="python setup.py develop", + cwd=unpacked_source_directory, + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/wheel.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..aef42aa9eefae7cae4a3d877b6dab1c53d85ad5f --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/install/wheel.py @@ -0,0 +1,741 @@ +"""Support for installing and building the "wheel" binary package format. +""" + +import collections +import compileall +import contextlib +import csv +import importlib +import logging +import os.path +import re +import shutil +import sys +import warnings +from base64 import urlsafe_b64encode +from email.message import Message +from itertools import chain, filterfalse, starmap +from typing import ( + IO, + TYPE_CHECKING, + Any, + BinaryIO, + Callable, + Dict, + Generator, + Iterable, + Iterator, + List, + NewType, + Optional, + Protocol, + Sequence, + Set, + Tuple, + Union, + cast, +) +from zipfile import ZipFile, ZipInfo + +from pip._vendor.distlib.scripts import ScriptMaker +from pip._vendor.distlib.util import get_export_entry +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.exceptions import InstallationError +from pip._internal.locations import get_major_minor_version +from pip._internal.metadata import ( + BaseDistribution, + FilesystemWheel, + get_wheel_distribution, +) +from pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl +from pip._internal.models.scheme import SCHEME_KEYS, Scheme +from pip._internal.utils.filesystem import adjacent_tmp_file, replace +from pip._internal.utils.misc import StreamWrapper, ensure_dir, hash_file, partition +from pip._internal.utils.unpacking import ( + current_umask, + is_within_directory, + set_extracted_file_to_default_mode_plus_executable, + zip_item_is_executable, +) +from pip._internal.utils.wheel import parse_wheel + +if TYPE_CHECKING: + + class File(Protocol): + src_record_path: "RecordPath" + dest_path: str + changed: bool + + def save(self) -> None: + pass + + +logger = logging.getLogger(__name__) + +RecordPath = NewType("RecordPath", str) +InstalledCSVRow = Tuple[RecordPath, str, Union[int, str]] + + +def rehash(path: str, blocksize: int = 1 << 20) -> Tuple[str, str]: + """Return (encoded_digest, length) for path using hashlib.sha256()""" + h, length = hash_file(path, blocksize) + digest = "sha256=" + urlsafe_b64encode(h.digest()).decode("latin1").rstrip("=") + return (digest, str(length)) + + +def csv_io_kwargs(mode: str) -> Dict[str, Any]: + """Return keyword arguments to properly open a CSV file + in the given mode. + """ + return {"mode": mode, "newline": "", "encoding": "utf-8"} + + +def fix_script(path: str) -> bool: + """Replace #!python with #!/path/to/python + Return True if file was changed. + """ + # XXX RECORD hashes will need to be updated + assert os.path.isfile(path) + + with open(path, "rb") as script: + firstline = script.readline() + if not firstline.startswith(b"#!python"): + return False + exename = sys.executable.encode(sys.getfilesystemencoding()) + firstline = b"#!" + exename + os.linesep.encode("ascii") + rest = script.read() + with open(path, "wb") as script: + script.write(firstline) + script.write(rest) + return True + + +def wheel_root_is_purelib(metadata: Message) -> bool: + return metadata.get("Root-Is-Purelib", "").lower() == "true" + + +def get_entrypoints(dist: BaseDistribution) -> Tuple[Dict[str, str], Dict[str, str]]: + console_scripts = {} + gui_scripts = {} + for entry_point in dist.iter_entry_points(): + if entry_point.group == "console_scripts": + console_scripts[entry_point.name] = entry_point.value + elif entry_point.group == "gui_scripts": + gui_scripts[entry_point.name] = entry_point.value + return console_scripts, gui_scripts + + +def message_about_scripts_not_on_PATH(scripts: Sequence[str]) -> Optional[str]: + """Determine if any scripts are not on PATH and format a warning. + Returns a warning message if one or more scripts are not on PATH, + otherwise None. + """ + if not scripts: + return None + + # Group scripts by the path they were installed in + grouped_by_dir: Dict[str, Set[str]] = collections.defaultdict(set) + for destfile in scripts: + parent_dir = os.path.dirname(destfile) + script_name = os.path.basename(destfile) + grouped_by_dir[parent_dir].add(script_name) + + # We don't want to warn for directories that are on PATH. + not_warn_dirs = [ + os.path.normcase(os.path.normpath(i)).rstrip(os.sep) + for i in os.environ.get("PATH", "").split(os.pathsep) + ] + # If an executable sits with sys.executable, we don't warn for it. + # This covers the case of venv invocations without activating the venv. + not_warn_dirs.append( + os.path.normcase(os.path.normpath(os.path.dirname(sys.executable))) + ) + warn_for: Dict[str, Set[str]] = { + parent_dir: scripts + for parent_dir, scripts in grouped_by_dir.items() + if os.path.normcase(os.path.normpath(parent_dir)) not in not_warn_dirs + } + if not warn_for: + return None + + # Format a message + msg_lines = [] + for parent_dir, dir_scripts in warn_for.items(): + sorted_scripts: List[str] = sorted(dir_scripts) + if len(sorted_scripts) == 1: + start_text = f"script {sorted_scripts[0]} is" + else: + start_text = "scripts {} are".format( + ", ".join(sorted_scripts[:-1]) + " and " + sorted_scripts[-1] + ) + + msg_lines.append( + f"The {start_text} installed in '{parent_dir}' which is not on PATH." + ) + + last_line_fmt = ( + "Consider adding {} to PATH or, if you prefer " + "to suppress this warning, use --no-warn-script-location." + ) + if len(msg_lines) == 1: + msg_lines.append(last_line_fmt.format("this directory")) + else: + msg_lines.append(last_line_fmt.format("these directories")) + + # Add a note if any directory starts with ~ + warn_for_tilde = any( + i[0] == "~" for i in os.environ.get("PATH", "").split(os.pathsep) if i + ) + if warn_for_tilde: + tilde_warning_msg = ( + "NOTE: The current PATH contains path(s) starting with `~`, " + "which may not be expanded by all applications." + ) + msg_lines.append(tilde_warning_msg) + + # Returns the formatted multiline message + return "\n".join(msg_lines) + + +def _normalized_outrows( + outrows: Iterable[InstalledCSVRow], +) -> List[Tuple[str, str, str]]: + """Normalize the given rows of a RECORD file. + + Items in each row are converted into str. Rows are then sorted to make + the value more predictable for tests. + + Each row is a 3-tuple (path, hash, size) and corresponds to a record of + a RECORD file (see PEP 376 and PEP 427 for details). For the rows + passed to this function, the size can be an integer as an int or string, + or the empty string. + """ + # Normally, there should only be one row per path, in which case the + # second and third elements don't come into play when sorting. + # However, in cases in the wild where a path might happen to occur twice, + # we don't want the sort operation to trigger an error (but still want + # determinism). Since the third element can be an int or string, we + # coerce each element to a string to avoid a TypeError in this case. + # For additional background, see-- + # https://github.com/pypa/pip/issues/5868 + return sorted( + (record_path, hash_, str(size)) for record_path, hash_, size in outrows + ) + + +def _record_to_fs_path(record_path: RecordPath, lib_dir: str) -> str: + return os.path.join(lib_dir, record_path) + + +def _fs_to_record_path(path: str, lib_dir: str) -> RecordPath: + # On Windows, do not handle relative paths if they belong to different + # logical disks + if os.path.splitdrive(path)[0].lower() == os.path.splitdrive(lib_dir)[0].lower(): + path = os.path.relpath(path, lib_dir) + + path = path.replace(os.path.sep, "/") + return cast("RecordPath", path) + + +def get_csv_rows_for_installed( + old_csv_rows: List[List[str]], + installed: Dict[RecordPath, RecordPath], + changed: Set[RecordPath], + generated: List[str], + lib_dir: str, +) -> List[InstalledCSVRow]: + """ + :param installed: A map from archive RECORD path to installation RECORD + path. + """ + installed_rows: List[InstalledCSVRow] = [] + for row in old_csv_rows: + if len(row) > 3: + logger.warning("RECORD line has more than three elements: %s", row) + old_record_path = cast("RecordPath", row[0]) + new_record_path = installed.pop(old_record_path, old_record_path) + if new_record_path in changed: + digest, length = rehash(_record_to_fs_path(new_record_path, lib_dir)) + else: + digest = row[1] if len(row) > 1 else "" + length = row[2] if len(row) > 2 else "" + installed_rows.append((new_record_path, digest, length)) + for f in generated: + path = _fs_to_record_path(f, lib_dir) + digest, length = rehash(f) + installed_rows.append((path, digest, length)) + return installed_rows + [ + (installed_record_path, "", "") for installed_record_path in installed.values() + ] + + +def get_console_script_specs(console: Dict[str, str]) -> List[str]: + """ + Given the mapping from entrypoint name to callable, return the relevant + console script specs. + """ + # Don't mutate caller's version + console = console.copy() + + scripts_to_generate = [] + + # Special case pip and setuptools to generate versioned wrappers + # + # The issue is that some projects (specifically, pip and setuptools) use + # code in setup.py to create "versioned" entry points - pip2.7 on Python + # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into + # the wheel metadata at build time, and so if the wheel is installed with + # a *different* version of Python the entry points will be wrong. The + # correct fix for this is to enhance the metadata to be able to describe + # such versioned entry points. + # Currently, projects using versioned entry points will either have + # incorrect versioned entry points, or they will not be able to distribute + # "universal" wheels (i.e., they will need a wheel per Python version). + # + # Because setuptools and pip are bundled with _ensurepip and virtualenv, + # we need to use universal wheels. As a workaround, we + # override the versioned entry points in the wheel and generate the + # correct ones. + # + # To add the level of hack in this section of code, in order to support + # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment + # variable which will control which version scripts get installed. + # + # ENSUREPIP_OPTIONS=altinstall + # - Only pipX.Y and easy_install-X.Y will be generated and installed + # ENSUREPIP_OPTIONS=install + # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note + # that this option is technically if ENSUREPIP_OPTIONS is set and is + # not altinstall + # DEFAULT + # - The default behavior is to install pip, pipX, pipX.Y, easy_install + # and easy_install-X.Y. + pip_script = console.pop("pip", None) + if pip_script: + if "ENSUREPIP_OPTIONS" not in os.environ: + scripts_to_generate.append("pip = " + pip_script) + + if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall": + scripts_to_generate.append(f"pip{sys.version_info[0]} = {pip_script}") + + scripts_to_generate.append(f"pip{get_major_minor_version()} = {pip_script}") + # Delete any other versioned pip entry points + pip_ep = [k for k in console if re.match(r"pip(\d+(\.\d+)?)?$", k)] + for k in pip_ep: + del console[k] + easy_install_script = console.pop("easy_install", None) + if easy_install_script: + if "ENSUREPIP_OPTIONS" not in os.environ: + scripts_to_generate.append("easy_install = " + easy_install_script) + + scripts_to_generate.append( + f"easy_install-{get_major_minor_version()} = {easy_install_script}" + ) + # Delete any other versioned easy_install entry points + easy_install_ep = [ + k for k in console if re.match(r"easy_install(-\d+\.\d+)?$", k) + ] + for k in easy_install_ep: + del console[k] + + # Generate the console entry points specified in the wheel + scripts_to_generate.extend(starmap("{} = {}".format, console.items())) + + return scripts_to_generate + + +class ZipBackedFile: + def __init__( + self, src_record_path: RecordPath, dest_path: str, zip_file: ZipFile + ) -> None: + self.src_record_path = src_record_path + self.dest_path = dest_path + self._zip_file = zip_file + self.changed = False + + def _getinfo(self) -> ZipInfo: + return self._zip_file.getinfo(self.src_record_path) + + def save(self) -> None: + # When we open the output file below, any existing file is truncated + # before we start writing the new contents. This is fine in most + # cases, but can cause a segfault if pip has loaded a shared + # object (e.g. from pyopenssl through its vendored urllib3) + # Since the shared object is mmap'd an attempt to call a + # symbol in it will then cause a segfault. Unlinking the file + # allows writing of new contents while allowing the process to + # continue to use the old copy. + if os.path.exists(self.dest_path): + os.unlink(self.dest_path) + + zipinfo = self._getinfo() + + # optimization: the file is created by open(), + # skip the decompression when there is 0 bytes to decompress. + with open(self.dest_path, "wb") as dest: + if zipinfo.file_size > 0: + with self._zip_file.open(zipinfo) as f: + blocksize = min(zipinfo.file_size, 1024 * 1024) + shutil.copyfileobj(f, dest, blocksize) + + if zip_item_is_executable(zipinfo): + set_extracted_file_to_default_mode_plus_executable(self.dest_path) + + +class ScriptFile: + def __init__(self, file: "File") -> None: + self._file = file + self.src_record_path = self._file.src_record_path + self.dest_path = self._file.dest_path + self.changed = False + + def save(self) -> None: + self._file.save() + self.changed = fix_script(self.dest_path) + + +class MissingCallableSuffix(InstallationError): + def __init__(self, entry_point: str) -> None: + super().__init__( + f"Invalid script entry point: {entry_point} - A callable " + "suffix is required. Cf https://packaging.python.org/" + "specifications/entry-points/#use-for-scripts for more " + "information." + ) + + +def _raise_for_invalid_entrypoint(specification: str) -> None: + entry = get_export_entry(specification) + if entry is not None and entry.suffix is None: + raise MissingCallableSuffix(str(entry)) + + +class PipScriptMaker(ScriptMaker): + def make( + self, specification: str, options: Optional[Dict[str, Any]] = None + ) -> List[str]: + _raise_for_invalid_entrypoint(specification) + return super().make(specification, options) + + +def _install_wheel( # noqa: C901, PLR0915 function is too long + name: str, + wheel_zip: ZipFile, + wheel_path: str, + scheme: Scheme, + pycompile: bool = True, + warn_script_location: bool = True, + direct_url: Optional[DirectUrl] = None, + requested: bool = False, +) -> None: + """Install a wheel. + + :param name: Name of the project to install + :param wheel_zip: open ZipFile for wheel being installed + :param scheme: Distutils scheme dictating the install directories + :param req_description: String used in place of the requirement, for + logging + :param pycompile: Whether to byte-compile installed Python files + :param warn_script_location: Whether to check that scripts are installed + into a directory on PATH + :raises UnsupportedWheel: + * when the directory holds an unpacked wheel with incompatible + Wheel-Version + * when the .dist-info dir does not match the wheel + """ + info_dir, metadata = parse_wheel(wheel_zip, name) + + if wheel_root_is_purelib(metadata): + lib_dir = scheme.purelib + else: + lib_dir = scheme.platlib + + # Record details of the files moved + # installed = files copied from the wheel to the destination + # changed = files changed while installing (scripts #! line typically) + # generated = files newly generated during the install (script wrappers) + installed: Dict[RecordPath, RecordPath] = {} + changed: Set[RecordPath] = set() + generated: List[str] = [] + + def record_installed( + srcfile: RecordPath, destfile: str, modified: bool = False + ) -> None: + """Map archive RECORD paths to installation RECORD paths.""" + newpath = _fs_to_record_path(destfile, lib_dir) + installed[srcfile] = newpath + if modified: + changed.add(newpath) + + def is_dir_path(path: RecordPath) -> bool: + return path.endswith("/") + + def assert_no_path_traversal(dest_dir_path: str, target_path: str) -> None: + if not is_within_directory(dest_dir_path, target_path): + message = ( + "The wheel {!r} has a file {!r} trying to install" + " outside the target directory {!r}" + ) + raise InstallationError( + message.format(wheel_path, target_path, dest_dir_path) + ) + + def root_scheme_file_maker( + zip_file: ZipFile, dest: str + ) -> Callable[[RecordPath], "File"]: + def make_root_scheme_file(record_path: RecordPath) -> "File": + normed_path = os.path.normpath(record_path) + dest_path = os.path.join(dest, normed_path) + assert_no_path_traversal(dest, dest_path) + return ZipBackedFile(record_path, dest_path, zip_file) + + return make_root_scheme_file + + def data_scheme_file_maker( + zip_file: ZipFile, scheme: Scheme + ) -> Callable[[RecordPath], "File"]: + scheme_paths = {key: getattr(scheme, key) for key in SCHEME_KEYS} + + def make_data_scheme_file(record_path: RecordPath) -> "File": + normed_path = os.path.normpath(record_path) + try: + _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2) + except ValueError: + message = ( + f"Unexpected file in {wheel_path}: {record_path!r}. .data directory" + " contents should be named like: '/'." + ) + raise InstallationError(message) + + try: + scheme_path = scheme_paths[scheme_key] + except KeyError: + valid_scheme_keys = ", ".join(sorted(scheme_paths)) + message = ( + f"Unknown scheme key used in {wheel_path}: {scheme_key} " + f"(for file {record_path!r}). .data directory contents " + f"should be in subdirectories named with a valid scheme " + f"key ({valid_scheme_keys})" + ) + raise InstallationError(message) + + dest_path = os.path.join(scheme_path, dest_subpath) + assert_no_path_traversal(scheme_path, dest_path) + return ZipBackedFile(record_path, dest_path, zip_file) + + return make_data_scheme_file + + def is_data_scheme_path(path: RecordPath) -> bool: + return path.split("/", 1)[0].endswith(".data") + + paths = cast(List[RecordPath], wheel_zip.namelist()) + file_paths = filterfalse(is_dir_path, paths) + root_scheme_paths, data_scheme_paths = partition(is_data_scheme_path, file_paths) + + make_root_scheme_file = root_scheme_file_maker(wheel_zip, lib_dir) + files: Iterator[File] = map(make_root_scheme_file, root_scheme_paths) + + def is_script_scheme_path(path: RecordPath) -> bool: + parts = path.split("/", 2) + return len(parts) > 2 and parts[0].endswith(".data") and parts[1] == "scripts" + + other_scheme_paths, script_scheme_paths = partition( + is_script_scheme_path, data_scheme_paths + ) + + make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme) + other_scheme_files = map(make_data_scheme_file, other_scheme_paths) + files = chain(files, other_scheme_files) + + # Get the defined entry points + distribution = get_wheel_distribution( + FilesystemWheel(wheel_path), + canonicalize_name(name), + ) + console, gui = get_entrypoints(distribution) + + def is_entrypoint_wrapper(file: "File") -> bool: + # EP, EP.exe and EP-script.py are scripts generated for + # entry point EP by setuptools + path = file.dest_path + name = os.path.basename(path) + if name.lower().endswith(".exe"): + matchname = name[:-4] + elif name.lower().endswith("-script.py"): + matchname = name[:-10] + elif name.lower().endswith(".pya"): + matchname = name[:-4] + else: + matchname = name + # Ignore setuptools-generated scripts + return matchname in console or matchname in gui + + script_scheme_files: Iterator[File] = map( + make_data_scheme_file, script_scheme_paths + ) + script_scheme_files = filterfalse(is_entrypoint_wrapper, script_scheme_files) + script_scheme_files = map(ScriptFile, script_scheme_files) + files = chain(files, script_scheme_files) + + existing_parents = set() + for file in files: + # directory creation is lazy and after file filtering + # to ensure we don't install empty dirs; empty dirs can't be + # uninstalled. + parent_dir = os.path.dirname(file.dest_path) + if parent_dir not in existing_parents: + ensure_dir(parent_dir) + existing_parents.add(parent_dir) + file.save() + record_installed(file.src_record_path, file.dest_path, file.changed) + + def pyc_source_file_paths() -> Generator[str, None, None]: + # We de-duplicate installation paths, since there can be overlap (e.g. + # file in .data maps to same location as file in wheel root). + # Sorting installation paths makes it easier to reproduce and debug + # issues related to permissions on existing files. + for installed_path in sorted(set(installed.values())): + full_installed_path = os.path.join(lib_dir, installed_path) + if not os.path.isfile(full_installed_path): + continue + if not full_installed_path.endswith(".py"): + continue + yield full_installed_path + + def pyc_output_path(path: str) -> str: + """Return the path the pyc file would have been written to.""" + return importlib.util.cache_from_source(path) + + # Compile all of the pyc files for the installed files + if pycompile: + with contextlib.redirect_stdout( + StreamWrapper.from_stream(sys.stdout) + ) as stdout: + with warnings.catch_warnings(): + warnings.filterwarnings("ignore") + for path in pyc_source_file_paths(): + success = compileall.compile_file(path, force=True, quiet=True) + if success: + pyc_path = pyc_output_path(path) + assert os.path.exists(pyc_path) + pyc_record_path = cast( + "RecordPath", pyc_path.replace(os.path.sep, "/") + ) + record_installed(pyc_record_path, pyc_path) + logger.debug(stdout.getvalue()) + + maker = PipScriptMaker(None, scheme.scripts) + + # Ensure old scripts are overwritten. + # See https://github.com/pypa/pip/issues/1800 + maker.clobber = True + + # Ensure we don't generate any variants for scripts because this is almost + # never what somebody wants. + # See https://bitbucket.org/pypa/distlib/issue/35/ + maker.variants = {""} + + # This is required because otherwise distlib creates scripts that are not + # executable. + # See https://bitbucket.org/pypa/distlib/issue/32/ + maker.set_mode = True + + # Generate the console and GUI entry points specified in the wheel + scripts_to_generate = get_console_script_specs(console) + + gui_scripts_to_generate = list(starmap("{} = {}".format, gui.items())) + + generated_console_scripts = maker.make_multiple(scripts_to_generate) + generated.extend(generated_console_scripts) + + generated.extend(maker.make_multiple(gui_scripts_to_generate, {"gui": True})) + + if warn_script_location: + msg = message_about_scripts_not_on_PATH(generated_console_scripts) + if msg is not None: + logger.warning(msg) + + generated_file_mode = 0o666 & ~current_umask() + + @contextlib.contextmanager + def _generate_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]: + with adjacent_tmp_file(path, **kwargs) as f: + yield f + os.chmod(f.name, generated_file_mode) + replace(f.name, path) + + dest_info_dir = os.path.join(lib_dir, info_dir) + + # Record pip as the installer + installer_path = os.path.join(dest_info_dir, "INSTALLER") + with _generate_file(installer_path) as installer_file: + installer_file.write(b"pip\n") + generated.append(installer_path) + + # Record the PEP 610 direct URL reference + if direct_url is not None: + direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME) + with _generate_file(direct_url_path) as direct_url_file: + direct_url_file.write(direct_url.to_json().encode("utf-8")) + generated.append(direct_url_path) + + # Record the REQUESTED file + if requested: + requested_path = os.path.join(dest_info_dir, "REQUESTED") + with open(requested_path, "wb"): + pass + generated.append(requested_path) + + record_text = distribution.read_text("RECORD") + record_rows = list(csv.reader(record_text.splitlines())) + + rows = get_csv_rows_for_installed( + record_rows, + installed=installed, + changed=changed, + generated=generated, + lib_dir=lib_dir, + ) + + # Record details of all files installed + record_path = os.path.join(dest_info_dir, "RECORD") + + with _generate_file(record_path, **csv_io_kwargs("w")) as record_file: + # Explicitly cast to typing.IO[str] as a workaround for the mypy error: + # "writer" has incompatible type "BinaryIO"; expected "_Writer" + writer = csv.writer(cast("IO[str]", record_file)) + writer.writerows(_normalized_outrows(rows)) + + +@contextlib.contextmanager +def req_error_context(req_description: str) -> Generator[None, None, None]: + try: + yield + except InstallationError as e: + message = f"For req: {req_description}. {e.args[0]}" + raise InstallationError(message) from e + + +def install_wheel( + name: str, + wheel_path: str, + scheme: Scheme, + req_description: str, + pycompile: bool = True, + warn_script_location: bool = True, + direct_url: Optional[DirectUrl] = None, + requested: bool = False, +) -> None: + with ZipFile(wheel_path, allowZip64=True) as z: + with req_error_context(req_description): + _install_wheel( + name=name, + wheel_zip=z, + wheel_path=wheel_path, + scheme=scheme, + pycompile=pycompile, + warn_script_location=warn_script_location, + direct_url=direct_url, + requested=requested, + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/prepare.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..e6aa344720028f422840a720d26f5cfab358062c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/operations/prepare.py @@ -0,0 +1,732 @@ +"""Prepares a distribution for installation +""" + +# The following comment should be removed at some point in the future. +# mypy: strict-optional=False + +import mimetypes +import os +import shutil +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, Iterable, List, Optional + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.distributions import make_distribution_for_install_requirement +from pip._internal.distributions.installed import InstalledDistribution +from pip._internal.exceptions import ( + DirectoryUrlHashUnsupported, + HashMismatch, + HashUnpinned, + InstallationError, + MetadataInconsistent, + NetworkConnectionError, + VcsHashUnsupported, +) +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata import BaseDistribution, get_metadata_distribution +from pip._internal.models.direct_url import ArchiveInfo +from pip._internal.models.link import Link +from pip._internal.models.wheel import Wheel +from pip._internal.network.download import BatchDownloader, Downloader +from pip._internal.network.lazy_wheel import ( + HTTPRangeRequestUnsupported, + dist_from_wheel_url, +) +from pip._internal.network.session import PipSession +from pip._internal.operations.build.build_tracker import BuildTracker +from pip._internal.req.req_install import InstallRequirement +from pip._internal.utils._log import getLogger +from pip._internal.utils.direct_url_helpers import ( + direct_url_for_editable, + direct_url_from_link, +) +from pip._internal.utils.hashes import Hashes, MissingHashes +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import ( + display_path, + hash_file, + hide_url, + redact_auth_from_requirement, +) +from pip._internal.utils.temp_dir import TempDirectory +from pip._internal.utils.unpacking import unpack_file +from pip._internal.vcs import vcs + +logger = getLogger(__name__) + + +def _get_prepared_distribution( + req: InstallRequirement, + build_tracker: BuildTracker, + finder: PackageFinder, + build_isolation: bool, + check_build_deps: bool, +) -> BaseDistribution: + """Prepare a distribution for installation.""" + abstract_dist = make_distribution_for_install_requirement(req) + tracker_id = abstract_dist.build_tracker_id + if tracker_id is not None: + with build_tracker.track(req, tracker_id): + abstract_dist.prepare_distribution_metadata( + finder, build_isolation, check_build_deps + ) + return abstract_dist.get_metadata_distribution() + + +def unpack_vcs_link(link: Link, location: str, verbosity: int) -> None: + vcs_backend = vcs.get_backend_for_scheme(link.scheme) + assert vcs_backend is not None + vcs_backend.unpack(location, url=hide_url(link.url), verbosity=verbosity) + + +@dataclass +class File: + path: str + content_type: Optional[str] = None + + def __post_init__(self) -> None: + if self.content_type is None: + self.content_type = mimetypes.guess_type(self.path)[0] + + +def get_http_url( + link: Link, + download: Downloader, + download_dir: Optional[str] = None, + hashes: Optional[Hashes] = None, +) -> File: + temp_dir = TempDirectory(kind="unpack", globally_managed=True) + # If a download dir is specified, is the file already downloaded there? + already_downloaded_path = None + if download_dir: + already_downloaded_path = _check_download_dir(link, download_dir, hashes) + + if already_downloaded_path: + from_path = already_downloaded_path + content_type = None + else: + # let's download to a tmp dir + from_path, content_type = download(link, temp_dir.path) + if hashes: + hashes.check_against_path(from_path) + + return File(from_path, content_type) + + +def get_file_url( + link: Link, download_dir: Optional[str] = None, hashes: Optional[Hashes] = None +) -> File: + """Get file and optionally check its hash.""" + # If a download dir is specified, is the file already there and valid? + already_downloaded_path = None + if download_dir: + already_downloaded_path = _check_download_dir(link, download_dir, hashes) + + if already_downloaded_path: + from_path = already_downloaded_path + else: + from_path = link.file_path + + # If --require-hashes is off, `hashes` is either empty, the + # link's embedded hash, or MissingHashes; it is required to + # match. If --require-hashes is on, we are satisfied by any + # hash in `hashes` matching: a URL-based or an option-based + # one; no internet-sourced hash will be in `hashes`. + if hashes: + hashes.check_against_path(from_path) + return File(from_path, None) + + +def unpack_url( + link: Link, + location: str, + download: Downloader, + verbosity: int, + download_dir: Optional[str] = None, + hashes: Optional[Hashes] = None, +) -> Optional[File]: + """Unpack link into location, downloading if required. + + :param hashes: A Hashes object, one of whose embedded hashes must match, + or HashMismatch will be raised. If the Hashes is empty, no matches are + required, and unhashable types of requirements (like VCS ones, which + would ordinarily raise HashUnsupported) are allowed. + """ + # non-editable vcs urls + if link.is_vcs: + unpack_vcs_link(link, location, verbosity=verbosity) + return None + + assert not link.is_existing_dir() + + # file urls + if link.is_file: + file = get_file_url(link, download_dir, hashes=hashes) + + # http urls + else: + file = get_http_url( + link, + download, + download_dir, + hashes=hashes, + ) + + # unpack the archive to the build dir location. even when only downloading + # archives, they have to be unpacked to parse dependencies, except wheels + if not link.is_wheel: + unpack_file(file.path, location, file.content_type) + + return file + + +def _check_download_dir( + link: Link, + download_dir: str, + hashes: Optional[Hashes], + warn_on_hash_mismatch: bool = True, +) -> Optional[str]: + """Check download_dir for previously downloaded file with correct hash + If a correct file is found return its path else None + """ + download_path = os.path.join(download_dir, link.filename) + + if not os.path.exists(download_path): + return None + + # If already downloaded, does its hash match? + logger.info("File was already downloaded %s", download_path) + if hashes: + try: + hashes.check_against_path(download_path) + except HashMismatch: + if warn_on_hash_mismatch: + logger.warning( + "Previously-downloaded file %s has bad hash. Re-downloading.", + download_path, + ) + os.unlink(download_path) + return None + return download_path + + +class RequirementPreparer: + """Prepares a Requirement""" + + def __init__( + self, + build_dir: str, + download_dir: Optional[str], + src_dir: str, + build_isolation: bool, + check_build_deps: bool, + build_tracker: BuildTracker, + session: PipSession, + progress_bar: str, + finder: PackageFinder, + require_hashes: bool, + use_user_site: bool, + lazy_wheel: bool, + verbosity: int, + legacy_resolver: bool, + ) -> None: + super().__init__() + + self.src_dir = src_dir + self.build_dir = build_dir + self.build_tracker = build_tracker + self._session = session + self._download = Downloader(session, progress_bar) + self._batch_download = BatchDownloader(session, progress_bar) + self.finder = finder + + # Where still-packed archives should be written to. If None, they are + # not saved, and are deleted immediately after unpacking. + self.download_dir = download_dir + + # Is build isolation allowed? + self.build_isolation = build_isolation + + # Should check build dependencies? + self.check_build_deps = check_build_deps + + # Should hash-checking be required? + self.require_hashes = require_hashes + + # Should install in user site-packages? + self.use_user_site = use_user_site + + # Should wheels be downloaded lazily? + self.use_lazy_wheel = lazy_wheel + + # How verbose should underlying tooling be? + self.verbosity = verbosity + + # Are we using the legacy resolver? + self.legacy_resolver = legacy_resolver + + # Memoized downloaded files, as mapping of url: path. + self._downloaded: Dict[str, str] = {} + + # Previous "header" printed for a link-based InstallRequirement + self._previous_requirement_header = ("", "") + + def _log_preparing_link(self, req: InstallRequirement) -> None: + """Provide context for the requirement being prepared.""" + if req.link.is_file and not req.is_wheel_from_cache: + message = "Processing %s" + information = str(display_path(req.link.file_path)) + else: + message = "Collecting %s" + information = redact_auth_from_requirement(req.req) if req.req else str(req) + + # If we used req.req, inject requirement source if available (this + # would already be included if we used req directly) + if req.req and req.comes_from: + if isinstance(req.comes_from, str): + comes_from: Optional[str] = req.comes_from + else: + comes_from = req.comes_from.from_path() + if comes_from: + information += f" (from {comes_from})" + + if (message, information) != self._previous_requirement_header: + self._previous_requirement_header = (message, information) + logger.info(message, information) + + if req.is_wheel_from_cache: + with indent_log(): + logger.info("Using cached %s", req.link.filename) + + def _ensure_link_req_src_dir( + self, req: InstallRequirement, parallel_builds: bool + ) -> None: + """Ensure source_dir of a linked InstallRequirement.""" + # Since source_dir is only set for editable requirements. + if req.link.is_wheel: + # We don't need to unpack wheels, so no need for a source + # directory. + return + assert req.source_dir is None + if req.link.is_existing_dir(): + # build local directories in-tree + req.source_dir = req.link.file_path + return + + # We always delete unpacked sdists after pip runs. + req.ensure_has_source_dir( + self.build_dir, + autodelete=True, + parallel_builds=parallel_builds, + ) + req.ensure_pristine_source_checkout() + + def _get_linked_req_hashes(self, req: InstallRequirement) -> Hashes: + # By the time this is called, the requirement's link should have + # been checked so we can tell what kind of requirements req is + # and raise some more informative errors than otherwise. + # (For example, we can raise VcsHashUnsupported for a VCS URL + # rather than HashMissing.) + if not self.require_hashes: + return req.hashes(trust_internet=True) + + # We could check these first 2 conditions inside unpack_url + # and save repetition of conditions, but then we would + # report less-useful error messages for unhashable + # requirements, complaining that there's no hash provided. + if req.link.is_vcs: + raise VcsHashUnsupported() + if req.link.is_existing_dir(): + raise DirectoryUrlHashUnsupported() + + # Unpinned packages are asking for trouble when a new version + # is uploaded. This isn't a security check, but it saves users + # a surprising hash mismatch in the future. + # file:/// URLs aren't pinnable, so don't complain about them + # not being pinned. + if not req.is_direct and not req.is_pinned: + raise HashUnpinned() + + # If known-good hashes are missing for this requirement, + # shim it with a facade object that will provoke hash + # computation and then raise a HashMissing exception + # showing the user what the hash should be. + return req.hashes(trust_internet=False) or MissingHashes() + + def _fetch_metadata_only( + self, + req: InstallRequirement, + ) -> Optional[BaseDistribution]: + if self.legacy_resolver: + logger.debug( + "Metadata-only fetching is not used in the legacy resolver", + ) + return None + if self.require_hashes: + logger.debug( + "Metadata-only fetching is not used as hash checking is required", + ) + return None + # Try PEP 658 metadata first, then fall back to lazy wheel if unavailable. + return self._fetch_metadata_using_link_data_attr( + req + ) or self._fetch_metadata_using_lazy_wheel(req.link) + + def _fetch_metadata_using_link_data_attr( + self, + req: InstallRequirement, + ) -> Optional[BaseDistribution]: + """Fetch metadata from the data-dist-info-metadata attribute, if possible.""" + # (1) Get the link to the metadata file, if provided by the backend. + metadata_link = req.link.metadata_link() + if metadata_link is None: + return None + assert req.req is not None + logger.verbose( + "Obtaining dependency information for %s from %s", + req.req, + metadata_link, + ) + # (2) Download the contents of the METADATA file, separate from the dist itself. + metadata_file = get_http_url( + metadata_link, + self._download, + hashes=metadata_link.as_hashes(), + ) + with open(metadata_file.path, "rb") as f: + metadata_contents = f.read() + # (3) Generate a dist just from those file contents. + metadata_dist = get_metadata_distribution( + metadata_contents, + req.link.filename, + req.req.name, + ) + # (4) Ensure the Name: field from the METADATA file matches the name from the + # install requirement. + # + # NB: raw_name will fall back to the name from the install requirement if + # the Name: field is not present, but it's noted in the raw_name docstring + # that that should NEVER happen anyway. + if canonicalize_name(metadata_dist.raw_name) != canonicalize_name(req.req.name): + raise MetadataInconsistent( + req, "Name", req.req.name, metadata_dist.raw_name + ) + return metadata_dist + + def _fetch_metadata_using_lazy_wheel( + self, + link: Link, + ) -> Optional[BaseDistribution]: + """Fetch metadata using lazy wheel, if possible.""" + # --use-feature=fast-deps must be provided. + if not self.use_lazy_wheel: + return None + if link.is_file or not link.is_wheel: + logger.debug( + "Lazy wheel is not used as %r does not point to a remote wheel", + link, + ) + return None + + wheel = Wheel(link.filename) + name = canonicalize_name(wheel.name) + logger.info( + "Obtaining dependency information from %s %s", + name, + wheel.version, + ) + url = link.url.split("#", 1)[0] + try: + return dist_from_wheel_url(name, url, self._session) + except HTTPRangeRequestUnsupported: + logger.debug("%s does not support range requests", url) + return None + + def _complete_partial_requirements( + self, + partially_downloaded_reqs: Iterable[InstallRequirement], + parallel_builds: bool = False, + ) -> None: + """Download any requirements which were only fetched by metadata.""" + # Download to a temporary directory. These will be copied over as + # needed for downstream 'download', 'wheel', and 'install' commands. + temp_dir = TempDirectory(kind="unpack", globally_managed=True).path + + # Map each link to the requirement that owns it. This allows us to set + # `req.local_file_path` on the appropriate requirement after passing + # all the links at once into BatchDownloader. + links_to_fully_download: Dict[Link, InstallRequirement] = {} + for req in partially_downloaded_reqs: + assert req.link + links_to_fully_download[req.link] = req + + batch_download = self._batch_download( + links_to_fully_download.keys(), + temp_dir, + ) + for link, (filepath, _) in batch_download: + logger.debug("Downloading link %s to %s", link, filepath) + req = links_to_fully_download[link] + # Record the downloaded file path so wheel reqs can extract a Distribution + # in .get_dist(). + req.local_file_path = filepath + # Record that the file is downloaded so we don't do it again in + # _prepare_linked_requirement(). + self._downloaded[req.link.url] = filepath + + # If this is an sdist, we need to unpack it after downloading, but the + # .source_dir won't be set up until we are in _prepare_linked_requirement(). + # Add the downloaded archive to the install requirement to unpack after + # preparing the source dir. + if not req.is_wheel: + req.needs_unpacked_archive(Path(filepath)) + + # This step is necessary to ensure all lazy wheels are processed + # successfully by the 'download', 'wheel', and 'install' commands. + for req in partially_downloaded_reqs: + self._prepare_linked_requirement(req, parallel_builds) + + def prepare_linked_requirement( + self, req: InstallRequirement, parallel_builds: bool = False + ) -> BaseDistribution: + """Prepare a requirement to be obtained from req.link.""" + assert req.link + self._log_preparing_link(req) + with indent_log(): + # Check if the relevant file is already available + # in the download directory + file_path = None + if self.download_dir is not None and req.link.is_wheel: + hashes = self._get_linked_req_hashes(req) + file_path = _check_download_dir( + req.link, + self.download_dir, + hashes, + # When a locally built wheel has been found in cache, we don't warn + # about re-downloading when the already downloaded wheel hash does + # not match. This is because the hash must be checked against the + # original link, not the cached link. It that case the already + # downloaded file will be removed and re-fetched from cache (which + # implies a hash check against the cache entry's origin.json). + warn_on_hash_mismatch=not req.is_wheel_from_cache, + ) + + if file_path is not None: + # The file is already available, so mark it as downloaded + self._downloaded[req.link.url] = file_path + else: + # The file is not available, attempt to fetch only metadata + metadata_dist = self._fetch_metadata_only(req) + if metadata_dist is not None: + req.needs_more_preparation = True + return metadata_dist + + # None of the optimizations worked, fully prepare the requirement + return self._prepare_linked_requirement(req, parallel_builds) + + def prepare_linked_requirements_more( + self, reqs: Iterable[InstallRequirement], parallel_builds: bool = False + ) -> None: + """Prepare linked requirements more, if needed.""" + reqs = [req for req in reqs if req.needs_more_preparation] + for req in reqs: + # Determine if any of these requirements were already downloaded. + if self.download_dir is not None and req.link.is_wheel: + hashes = self._get_linked_req_hashes(req) + file_path = _check_download_dir(req.link, self.download_dir, hashes) + if file_path is not None: + self._downloaded[req.link.url] = file_path + req.needs_more_preparation = False + + # Prepare requirements we found were already downloaded for some + # reason. The other downloads will be completed separately. + partially_downloaded_reqs: List[InstallRequirement] = [] + for req in reqs: + if req.needs_more_preparation: + partially_downloaded_reqs.append(req) + else: + self._prepare_linked_requirement(req, parallel_builds) + + # TODO: separate this part out from RequirementPreparer when the v1 + # resolver can be removed! + self._complete_partial_requirements( + partially_downloaded_reqs, + parallel_builds=parallel_builds, + ) + + def _prepare_linked_requirement( + self, req: InstallRequirement, parallel_builds: bool + ) -> BaseDistribution: + assert req.link + link = req.link + + hashes = self._get_linked_req_hashes(req) + + if hashes and req.is_wheel_from_cache: + assert req.download_info is not None + assert link.is_wheel + assert link.is_file + # We need to verify hashes, and we have found the requirement in the cache + # of locally built wheels. + if ( + isinstance(req.download_info.info, ArchiveInfo) + and req.download_info.info.hashes + and hashes.has_one_of(req.download_info.info.hashes) + ): + # At this point we know the requirement was built from a hashable source + # artifact, and we verified that the cache entry's hash of the original + # artifact matches one of the hashes we expect. We don't verify hashes + # against the cached wheel, because the wheel is not the original. + hashes = None + else: + logger.warning( + "The hashes of the source archive found in cache entry " + "don't match, ignoring cached built wheel " + "and re-downloading source." + ) + req.link = req.cached_wheel_source_link + link = req.link + + self._ensure_link_req_src_dir(req, parallel_builds) + + if link.is_existing_dir(): + local_file = None + elif link.url not in self._downloaded: + try: + local_file = unpack_url( + link, + req.source_dir, + self._download, + self.verbosity, + self.download_dir, + hashes, + ) + except NetworkConnectionError as exc: + raise InstallationError( + f"Could not install requirement {req} because of HTTP " + f"error {exc} for URL {link}" + ) + else: + file_path = self._downloaded[link.url] + if hashes: + hashes.check_against_path(file_path) + local_file = File(file_path, content_type=None) + + # If download_info is set, we got it from the wheel cache. + if req.download_info is None: + # Editables don't go through this function (see + # prepare_editable_requirement). + assert not req.editable + req.download_info = direct_url_from_link(link, req.source_dir) + # Make sure we have a hash in download_info. If we got it as part of the + # URL, it will have been verified and we can rely on it. Otherwise we + # compute it from the downloaded file. + # FIXME: https://github.com/pypa/pip/issues/11943 + if ( + isinstance(req.download_info.info, ArchiveInfo) + and not req.download_info.info.hashes + and local_file + ): + hash = hash_file(local_file.path)[0].hexdigest() + # We populate info.hash for backward compatibility. + # This will automatically populate info.hashes. + req.download_info.info.hash = f"sha256={hash}" + + # For use in later processing, + # preserve the file path on the requirement. + if local_file: + req.local_file_path = local_file.path + + dist = _get_prepared_distribution( + req, + self.build_tracker, + self.finder, + self.build_isolation, + self.check_build_deps, + ) + return dist + + def save_linked_requirement(self, req: InstallRequirement) -> None: + assert self.download_dir is not None + assert req.link is not None + link = req.link + if link.is_vcs or (link.is_existing_dir() and req.editable): + # Make a .zip of the source_dir we already created. + req.archive(self.download_dir) + return + + if link.is_existing_dir(): + logger.debug( + "Not copying link to destination directory " + "since it is a directory: %s", + link, + ) + return + if req.local_file_path is None: + # No distribution was downloaded for this requirement. + return + + download_location = os.path.join(self.download_dir, link.filename) + if not os.path.exists(download_location): + shutil.copy(req.local_file_path, download_location) + download_path = display_path(download_location) + logger.info("Saved %s", download_path) + + def prepare_editable_requirement( + self, + req: InstallRequirement, + ) -> BaseDistribution: + """Prepare an editable requirement.""" + assert req.editable, "cannot prepare a non-editable req as editable" + + logger.info("Obtaining %s", req) + + with indent_log(): + if self.require_hashes: + raise InstallationError( + f"The editable requirement {req} cannot be installed when " + "requiring hashes, because there is no single file to " + "hash." + ) + req.ensure_has_source_dir(self.src_dir) + req.update_editable() + assert req.source_dir + req.download_info = direct_url_for_editable(req.unpacked_source_directory) + + dist = _get_prepared_distribution( + req, + self.build_tracker, + self.finder, + self.build_isolation, + self.check_build_deps, + ) + + req.check_if_exists(self.use_user_site) + + return dist + + def prepare_installed_requirement( + self, + req: InstallRequirement, + skip_reason: str, + ) -> BaseDistribution: + """Prepare an already-installed requirement.""" + assert req.satisfied_by, "req should have been satisfied but isn't" + assert skip_reason is not None, ( + "did not get skip reason skipped but req.satisfied_by " + f"is set to {req.satisfied_by}" + ) + logger.info( + "Requirement %s: %s (%s)", skip_reason, req, req.satisfied_by.version + ) + with indent_log(): + if self.require_hashes: + logger.debug( + "Since it is already installed, we are trusting this " + "package without checking its hash. To ensure a " + "completely repeatable environment, install into an " + "empty virtualenv." + ) + return InstalledDistribution(req).get_metadata_distribution() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/pyproject.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/pyproject.py new file mode 100644 index 0000000000000000000000000000000000000000..0e8452f39dca0ab98888ab65c4ff34e4ac94f1c3 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/pyproject.py @@ -0,0 +1,185 @@ +import importlib.util +import os +import sys +from collections import namedtuple +from typing import Any, List, Optional + +if sys.version_info >= (3, 11): + import tomllib +else: + from pip._vendor import tomli as tomllib + +from pip._vendor.packaging.requirements import InvalidRequirement + +from pip._internal.exceptions import ( + InstallationError, + InvalidPyProjectBuildRequires, + MissingPyProjectBuildRequires, +) +from pip._internal.utils.packaging import get_requirement + + +def _is_list_of_str(obj: Any) -> bool: + return isinstance(obj, list) and all(isinstance(item, str) for item in obj) + + +def make_pyproject_path(unpacked_source_directory: str) -> str: + return os.path.join(unpacked_source_directory, "pyproject.toml") + + +BuildSystemDetails = namedtuple( + "BuildSystemDetails", ["requires", "backend", "check", "backend_path"] +) + + +def load_pyproject_toml( + use_pep517: Optional[bool], pyproject_toml: str, setup_py: str, req_name: str +) -> Optional[BuildSystemDetails]: + """Load the pyproject.toml file. + + Parameters: + use_pep517 - Has the user requested PEP 517 processing? None + means the user hasn't explicitly specified. + pyproject_toml - Location of the project's pyproject.toml file + setup_py - Location of the project's setup.py file + req_name - The name of the requirement we're processing (for + error reporting) + + Returns: + None if we should use the legacy code path, otherwise a tuple + ( + requirements from pyproject.toml, + name of PEP 517 backend, + requirements we should check are installed after setting + up the build environment + directory paths to import the backend from (backend-path), + relative to the project root. + ) + """ + has_pyproject = os.path.isfile(pyproject_toml) + has_setup = os.path.isfile(setup_py) + + if not has_pyproject and not has_setup: + raise InstallationError( + f"{req_name} does not appear to be a Python project: " + f"neither 'setup.py' nor 'pyproject.toml' found." + ) + + if has_pyproject: + with open(pyproject_toml, encoding="utf-8") as f: + pp_toml = tomllib.loads(f.read()) + build_system = pp_toml.get("build-system") + else: + build_system = None + + # The following cases must use PEP 517 + # We check for use_pep517 being non-None and falsy because that means + # the user explicitly requested --no-use-pep517. The value 0 as + # opposed to False can occur when the value is provided via an + # environment variable or config file option (due to the quirk of + # strtobool() returning an integer in pip's configuration code). + if has_pyproject and not has_setup: + if use_pep517 is not None and not use_pep517: + raise InstallationError( + "Disabling PEP 517 processing is invalid: " + "project does not have a setup.py" + ) + use_pep517 = True + elif build_system and "build-backend" in build_system: + if use_pep517 is not None and not use_pep517: + raise InstallationError( + "Disabling PEP 517 processing is invalid: " + "project specifies a build backend of {} " + "in pyproject.toml".format(build_system["build-backend"]) + ) + use_pep517 = True + + # If we haven't worked out whether to use PEP 517 yet, + # and the user hasn't explicitly stated a preference, + # we do so if the project has a pyproject.toml file + # or if we cannot import setuptools or wheels. + + # We fallback to PEP 517 when without setuptools or without the wheel package, + # so setuptools can be installed as a default build backend. + # For more info see: + # https://discuss.python.org/t/pip-without-setuptools-could-the-experience-be-improved/11810/9 + # https://github.com/pypa/pip/issues/8559 + elif use_pep517 is None: + use_pep517 = ( + has_pyproject + or not importlib.util.find_spec("setuptools") + or not importlib.util.find_spec("wheel") + ) + + # At this point, we know whether we're going to use PEP 517. + assert use_pep517 is not None + + # If we're using the legacy code path, there is nothing further + # for us to do here. + if not use_pep517: + return None + + if build_system is None: + # Either the user has a pyproject.toml with no build-system + # section, or the user has no pyproject.toml, but has opted in + # explicitly via --use-pep517. + # In the absence of any explicit backend specification, we + # assume the setuptools backend that most closely emulates the + # traditional direct setup.py execution, and require wheel and + # a version of setuptools that supports that backend. + + build_system = { + "requires": ["setuptools>=40.8.0"], + "build-backend": "setuptools.build_meta:__legacy__", + } + + # If we're using PEP 517, we have build system information (either + # from pyproject.toml, or defaulted by the code above). + # Note that at this point, we do not know if the user has actually + # specified a backend, though. + assert build_system is not None + + # Ensure that the build-system section in pyproject.toml conforms + # to PEP 518. + + # Specifying the build-system table but not the requires key is invalid + if "requires" not in build_system: + raise MissingPyProjectBuildRequires(package=req_name) + + # Error out if requires is not a list of strings + requires = build_system["requires"] + if not _is_list_of_str(requires): + raise InvalidPyProjectBuildRequires( + package=req_name, + reason="It is not a list of strings.", + ) + + # Each requirement must be valid as per PEP 508 + for requirement in requires: + try: + get_requirement(requirement) + except InvalidRequirement as error: + raise InvalidPyProjectBuildRequires( + package=req_name, + reason=f"It contains an invalid requirement: {requirement!r}", + ) from error + + backend = build_system.get("build-backend") + backend_path = build_system.get("backend-path", []) + check: List[str] = [] + if backend is None: + # If the user didn't specify a backend, we assume they want to use + # the setuptools backend. But we can't be sure they have included + # a version of setuptools which supplies the backend. So we + # make a note to check that this requirement is present once + # we have set up the environment. + # This is quite a lot of work to check for a very specific case. But + # the problem is, that case is potentially quite common - projects that + # adopted PEP 518 early for the ability to specify requirements to + # execute setup.py, but never considered needing to mention the build + # tools themselves. The original PEP 518 code had a similar check (but + # implemented in a different way). + backend = "setuptools.build_meta:__legacy__" + check = ["setuptools>=40.8.0"] + + return BuildSystemDetails(requires, backend, check, backend_path) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..422d851d7293d702f1a4c5e79f92b428703dc852 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__init__.py @@ -0,0 +1,90 @@ +import collections +import logging +from dataclasses import dataclass +from typing import Generator, List, Optional, Sequence, Tuple + +from pip._internal.utils.logging import indent_log + +from .req_file import parse_requirements +from .req_install import InstallRequirement +from .req_set import RequirementSet + +__all__ = [ + "RequirementSet", + "InstallRequirement", + "parse_requirements", + "install_given_reqs", +] + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class InstallationResult: + name: str + + +def _validate_requirements( + requirements: List[InstallRequirement], +) -> Generator[Tuple[str, InstallRequirement], None, None]: + for req in requirements: + assert req.name, f"invalid to-be-installed requirement: {req}" + yield req.name, req + + +def install_given_reqs( + requirements: List[InstallRequirement], + global_options: Sequence[str], + root: Optional[str], + home: Optional[str], + prefix: Optional[str], + warn_script_location: bool, + use_user_site: bool, + pycompile: bool, +) -> List[InstallationResult]: + """ + Install everything in the given list. + + (to be called after having downloaded and unpacked the packages) + """ + to_install = collections.OrderedDict(_validate_requirements(requirements)) + + if to_install: + logger.info( + "Installing collected packages: %s", + ", ".join(to_install.keys()), + ) + + installed = [] + + with indent_log(): + for req_name, requirement in to_install.items(): + if requirement.should_reinstall: + logger.info("Attempting uninstall: %s", req_name) + with indent_log(): + uninstalled_pathset = requirement.uninstall(auto_confirm=True) + else: + uninstalled_pathset = None + + try: + requirement.install( + global_options, + root=root, + home=home, + prefix=prefix, + warn_script_location=warn_script_location, + use_user_site=use_user_site, + pycompile=pycompile, + ) + except Exception: + # if install did not succeed, rollback previous uninstall + if uninstalled_pathset and not requirement.install_succeeded: + uninstalled_pathset.rollback() + raise + else: + if uninstalled_pathset and requirement.install_succeeded: + uninstalled_pathset.commit() + + installed.append(InstallationResult(req_name)) + + return installed diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c71c65bf7aec1734e8628746965ca566728fd577 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/constructors.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/constructors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f11a627af5334cf3719965026fe75fe79a548133 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/constructors.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_file.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_file.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0f5b3e552b620898cc264234cf4066e0aff4380 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_file.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_install.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_install.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..986be0462c786053fcfddca826f0c658ded43a92 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_install.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_set.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_set.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7407a31adeade5e155c52c658bf25d02001269ad Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_set.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_uninstall.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_uninstall.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f9fd526f97cfdd96f136cf0c2cf8e3a42d54dcc Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/__pycache__/req_uninstall.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/constructors.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/constructors.py new file mode 100644 index 0000000000000000000000000000000000000000..56a964f3177dc47d747ccf55361fccb8aea70ebf --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/constructors.py @@ -0,0 +1,560 @@ +"""Backing implementation for InstallRequirement's various constructors + +The idea here is that these formed a major chunk of InstallRequirement's size +so, moving them and support code dedicated to them outside of that class +helps creates for better understandability for the rest of the code. + +These are meant to be used elsewhere within pip to create instances of +InstallRequirement. +""" + +import copy +import logging +import os +import re +from dataclasses import dataclass +from typing import Collection, Dict, List, Optional, Set, Tuple, Union + +from pip._vendor.packaging.markers import Marker +from pip._vendor.packaging.requirements import InvalidRequirement, Requirement +from pip._vendor.packaging.specifiers import Specifier + +from pip._internal.exceptions import InstallationError +from pip._internal.models.index import PyPI, TestPyPI +from pip._internal.models.link import Link +from pip._internal.models.wheel import Wheel +from pip._internal.req.req_file import ParsedRequirement +from pip._internal.req.req_install import InstallRequirement +from pip._internal.utils.filetypes import is_archive_file +from pip._internal.utils.misc import is_installable_dir +from pip._internal.utils.packaging import get_requirement +from pip._internal.utils.urls import path_to_url +from pip._internal.vcs import is_url, vcs + +__all__ = [ + "install_req_from_editable", + "install_req_from_line", + "parse_editable", +] + +logger = logging.getLogger(__name__) +operators = Specifier._operators.keys() + + +def _strip_extras(path: str) -> Tuple[str, Optional[str]]: + m = re.match(r"^(.+)(\[[^\]]+\])$", path) + extras = None + if m: + path_no_extras = m.group(1) + extras = m.group(2) + else: + path_no_extras = path + + return path_no_extras, extras + + +def convert_extras(extras: Optional[str]) -> Set[str]: + if not extras: + return set() + return get_requirement("placeholder" + extras.lower()).extras + + +def _set_requirement_extras(req: Requirement, new_extras: Set[str]) -> Requirement: + """ + Returns a new requirement based on the given one, with the supplied extras. If the + given requirement already has extras those are replaced (or dropped if no new extras + are given). + """ + match: Optional[re.Match[str]] = re.fullmatch( + # see https://peps.python.org/pep-0508/#complete-grammar + r"([\w\t .-]+)(\[[^\]]*\])?(.*)", + str(req), + flags=re.ASCII, + ) + # ireq.req is a valid requirement so the regex should always match + assert ( + match is not None + ), f"regex match on requirement {req} failed, this should never happen" + pre: Optional[str] = match.group(1) + post: Optional[str] = match.group(3) + assert ( + pre is not None and post is not None + ), f"regex group selection for requirement {req} failed, this should never happen" + extras: str = "[{}]".format(",".join(sorted(new_extras)) if new_extras else "") + return get_requirement(f"{pre}{extras}{post}") + + +def parse_editable(editable_req: str) -> Tuple[Optional[str], str, Set[str]]: + """Parses an editable requirement into: + - a requirement name + - an URL + - extras + - editable options + Accepted requirements: + svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir + .[some_extra] + """ + + url = editable_req + + # If a file path is specified with extras, strip off the extras. + url_no_extras, extras = _strip_extras(url) + + if os.path.isdir(url_no_extras): + # Treating it as code that has already been checked out + url_no_extras = path_to_url(url_no_extras) + + if url_no_extras.lower().startswith("file:"): + package_name = Link(url_no_extras).egg_fragment + if extras: + return ( + package_name, + url_no_extras, + get_requirement("placeholder" + extras.lower()).extras, + ) + else: + return package_name, url_no_extras, set() + + for version_control in vcs: + if url.lower().startswith(f"{version_control}:"): + url = f"{version_control}+{url}" + break + + link = Link(url) + + if not link.is_vcs: + backends = ", ".join(vcs.all_schemes) + raise InstallationError( + f"{editable_req} is not a valid editable requirement. " + f"It should either be a path to a local project or a VCS URL " + f"(beginning with {backends})." + ) + + package_name = link.egg_fragment + if not package_name: + raise InstallationError( + f"Could not detect requirement name for '{editable_req}', " + "please specify one with #egg=your_package_name" + ) + return package_name, url, set() + + +def check_first_requirement_in_file(filename: str) -> None: + """Check if file is parsable as a requirements file. + + This is heavily based on ``pkg_resources.parse_requirements``, but + simplified to just check the first meaningful line. + + :raises InvalidRequirement: If the first meaningful line cannot be parsed + as an requirement. + """ + with open(filename, encoding="utf-8", errors="ignore") as f: + # Create a steppable iterator, so we can handle \-continuations. + lines = ( + line + for line in (line.strip() for line in f) + if line and not line.startswith("#") # Skip blank lines/comments. + ) + + for line in lines: + # Drop comments -- a hash without a space may be in a URL. + if " #" in line: + line = line[: line.find(" #")] + # If there is a line continuation, drop it, and append the next line. + if line.endswith("\\"): + line = line[:-2].strip() + next(lines, "") + get_requirement(line) + return + + +def deduce_helpful_msg(req: str) -> str: + """Returns helpful msg in case requirements file does not exist, + or cannot be parsed. + + :params req: Requirements file path + """ + if not os.path.exists(req): + return f" File '{req}' does not exist." + msg = " The path does exist. " + # Try to parse and check if it is a requirements file. + try: + check_first_requirement_in_file(req) + except InvalidRequirement: + logger.debug("Cannot parse '%s' as requirements file", req) + else: + msg += ( + f"The argument you provided " + f"({req}) appears to be a" + f" requirements file. If that is the" + f" case, use the '-r' flag to install" + f" the packages specified within it." + ) + return msg + + +@dataclass(frozen=True) +class RequirementParts: + requirement: Optional[Requirement] + link: Optional[Link] + markers: Optional[Marker] + extras: Set[str] + + +def parse_req_from_editable(editable_req: str) -> RequirementParts: + name, url, extras_override = parse_editable(editable_req) + + if name is not None: + try: + req: Optional[Requirement] = get_requirement(name) + except InvalidRequirement as exc: + raise InstallationError(f"Invalid requirement: {name!r}: {exc}") + else: + req = None + + link = Link(url) + + return RequirementParts(req, link, None, extras_override) + + +# ---- The actual constructors follow ---- + + +def install_req_from_editable( + editable_req: str, + comes_from: Optional[Union[InstallRequirement, str]] = None, + *, + use_pep517: Optional[bool] = None, + isolated: bool = False, + global_options: Optional[List[str]] = None, + hash_options: Optional[Dict[str, List[str]]] = None, + constraint: bool = False, + user_supplied: bool = False, + permit_editable_wheels: bool = False, + config_settings: Optional[Dict[str, Union[str, List[str]]]] = None, +) -> InstallRequirement: + parts = parse_req_from_editable(editable_req) + + return InstallRequirement( + parts.requirement, + comes_from=comes_from, + user_supplied=user_supplied, + editable=True, + permit_editable_wheels=permit_editable_wheels, + link=parts.link, + constraint=constraint, + use_pep517=use_pep517, + isolated=isolated, + global_options=global_options, + hash_options=hash_options, + config_settings=config_settings, + extras=parts.extras, + ) + + +def _looks_like_path(name: str) -> bool: + """Checks whether the string "looks like" a path on the filesystem. + + This does not check whether the target actually exists, only judge from the + appearance. + + Returns true if any of the following conditions is true: + * a path separator is found (either os.path.sep or os.path.altsep); + * a dot is found (which represents the current directory). + """ + if os.path.sep in name: + return True + if os.path.altsep is not None and os.path.altsep in name: + return True + if name.startswith("."): + return True + return False + + +def _get_url_from_path(path: str, name: str) -> Optional[str]: + """ + First, it checks whether a provided path is an installable directory. If it + is, returns the path. + + If false, check if the path is an archive file (such as a .whl). + The function checks if the path is a file. If false, if the path has + an @, it will treat it as a PEP 440 URL requirement and return the path. + """ + if _looks_like_path(name) and os.path.isdir(path): + if is_installable_dir(path): + return path_to_url(path) + # TODO: The is_installable_dir test here might not be necessary + # now that it is done in load_pyproject_toml too. + raise InstallationError( + f"Directory {name!r} is not installable. Neither 'setup.py' " + "nor 'pyproject.toml' found." + ) + if not is_archive_file(path): + return None + if os.path.isfile(path): + return path_to_url(path) + urlreq_parts = name.split("@", 1) + if len(urlreq_parts) >= 2 and not _looks_like_path(urlreq_parts[0]): + # If the path contains '@' and the part before it does not look + # like a path, try to treat it as a PEP 440 URL req instead. + return None + logger.warning( + "Requirement %r looks like a filename, but the file does not exist", + name, + ) + return path_to_url(path) + + +def parse_req_from_line(name: str, line_source: Optional[str]) -> RequirementParts: + if is_url(name): + marker_sep = "; " + else: + marker_sep = ";" + if marker_sep in name: + name, markers_as_string = name.split(marker_sep, 1) + markers_as_string = markers_as_string.strip() + if not markers_as_string: + markers = None + else: + markers = Marker(markers_as_string) + else: + markers = None + name = name.strip() + req_as_string = None + path = os.path.normpath(os.path.abspath(name)) + link = None + extras_as_string = None + + if is_url(name): + link = Link(name) + else: + p, extras_as_string = _strip_extras(path) + url = _get_url_from_path(p, name) + if url is not None: + link = Link(url) + + # it's a local file, dir, or url + if link: + # Handle relative file URLs + if link.scheme == "file" and re.search(r"\.\./", link.url): + link = Link(path_to_url(os.path.normpath(os.path.abspath(link.path)))) + # wheel file + if link.is_wheel: + wheel = Wheel(link.filename) # can raise InvalidWheelFilename + req_as_string = f"{wheel.name}=={wheel.version}" + else: + # set the req to the egg fragment. when it's not there, this + # will become an 'unnamed' requirement + req_as_string = link.egg_fragment + + # a requirement specifier + else: + req_as_string = name + + extras = convert_extras(extras_as_string) + + def with_source(text: str) -> str: + if not line_source: + return text + return f"{text} (from {line_source})" + + def _parse_req_string(req_as_string: str) -> Requirement: + try: + return get_requirement(req_as_string) + except InvalidRequirement as exc: + if os.path.sep in req_as_string: + add_msg = "It looks like a path." + add_msg += deduce_helpful_msg(req_as_string) + elif "=" in req_as_string and not any( + op in req_as_string for op in operators + ): + add_msg = "= is not a valid operator. Did you mean == ?" + else: + add_msg = "" + msg = with_source(f"Invalid requirement: {req_as_string!r}: {exc}") + if add_msg: + msg += f"\nHint: {add_msg}" + raise InstallationError(msg) + + if req_as_string is not None: + req: Optional[Requirement] = _parse_req_string(req_as_string) + else: + req = None + + return RequirementParts(req, link, markers, extras) + + +def install_req_from_line( + name: str, + comes_from: Optional[Union[str, InstallRequirement]] = None, + *, + use_pep517: Optional[bool] = None, + isolated: bool = False, + global_options: Optional[List[str]] = None, + hash_options: Optional[Dict[str, List[str]]] = None, + constraint: bool = False, + line_source: Optional[str] = None, + user_supplied: bool = False, + config_settings: Optional[Dict[str, Union[str, List[str]]]] = None, +) -> InstallRequirement: + """Creates an InstallRequirement from a name, which might be a + requirement, directory containing 'setup.py', filename, or URL. + + :param line_source: An optional string describing where the line is from, + for logging purposes in case of an error. + """ + parts = parse_req_from_line(name, line_source) + + return InstallRequirement( + parts.requirement, + comes_from, + link=parts.link, + markers=parts.markers, + use_pep517=use_pep517, + isolated=isolated, + global_options=global_options, + hash_options=hash_options, + config_settings=config_settings, + constraint=constraint, + extras=parts.extras, + user_supplied=user_supplied, + ) + + +def install_req_from_req_string( + req_string: str, + comes_from: Optional[InstallRequirement] = None, + isolated: bool = False, + use_pep517: Optional[bool] = None, + user_supplied: bool = False, +) -> InstallRequirement: + try: + req = get_requirement(req_string) + except InvalidRequirement as exc: + raise InstallationError(f"Invalid requirement: {req_string!r}: {exc}") + + domains_not_allowed = [ + PyPI.file_storage_domain, + TestPyPI.file_storage_domain, + ] + if ( + req.url + and comes_from + and comes_from.link + and comes_from.link.netloc in domains_not_allowed + ): + # Explicitly disallow pypi packages that depend on external urls + raise InstallationError( + "Packages installed from PyPI cannot depend on packages " + "which are not also hosted on PyPI.\n" + f"{comes_from.name} depends on {req} " + ) + + return InstallRequirement( + req, + comes_from, + isolated=isolated, + use_pep517=use_pep517, + user_supplied=user_supplied, + ) + + +def install_req_from_parsed_requirement( + parsed_req: ParsedRequirement, + isolated: bool = False, + use_pep517: Optional[bool] = None, + user_supplied: bool = False, + config_settings: Optional[Dict[str, Union[str, List[str]]]] = None, +) -> InstallRequirement: + if parsed_req.is_editable: + req = install_req_from_editable( + parsed_req.requirement, + comes_from=parsed_req.comes_from, + use_pep517=use_pep517, + constraint=parsed_req.constraint, + isolated=isolated, + user_supplied=user_supplied, + config_settings=config_settings, + ) + + else: + req = install_req_from_line( + parsed_req.requirement, + comes_from=parsed_req.comes_from, + use_pep517=use_pep517, + isolated=isolated, + global_options=( + parsed_req.options.get("global_options", []) + if parsed_req.options + else [] + ), + hash_options=( + parsed_req.options.get("hashes", {}) if parsed_req.options else {} + ), + constraint=parsed_req.constraint, + line_source=parsed_req.line_source, + user_supplied=user_supplied, + config_settings=config_settings, + ) + return req + + +def install_req_from_link_and_ireq( + link: Link, ireq: InstallRequirement +) -> InstallRequirement: + return InstallRequirement( + req=ireq.req, + comes_from=ireq.comes_from, + editable=ireq.editable, + link=link, + markers=ireq.markers, + use_pep517=ireq.use_pep517, + isolated=ireq.isolated, + global_options=ireq.global_options, + hash_options=ireq.hash_options, + config_settings=ireq.config_settings, + user_supplied=ireq.user_supplied, + ) + + +def install_req_drop_extras(ireq: InstallRequirement) -> InstallRequirement: + """ + Creates a new InstallationRequirement using the given template but without + any extras. Sets the original requirement as the new one's parent + (comes_from). + """ + return InstallRequirement( + req=( + _set_requirement_extras(ireq.req, set()) if ireq.req is not None else None + ), + comes_from=ireq, + editable=ireq.editable, + link=ireq.link, + markers=ireq.markers, + use_pep517=ireq.use_pep517, + isolated=ireq.isolated, + global_options=ireq.global_options, + hash_options=ireq.hash_options, + constraint=ireq.constraint, + extras=[], + config_settings=ireq.config_settings, + user_supplied=ireq.user_supplied, + permit_editable_wheels=ireq.permit_editable_wheels, + ) + + +def install_req_extend_extras( + ireq: InstallRequirement, + extras: Collection[str], +) -> InstallRequirement: + """ + Returns a copy of an installation requirement with some additional extras. + Makes a shallow copy of the ireq object. + """ + result = copy.copy(ireq) + result.extras = {*ireq.extras, *extras} + result.req = ( + _set_requirement_extras(ireq.req, result.extras) + if ireq.req is not None + else None + ) + return result diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_file.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_file.py new file mode 100644 index 0000000000000000000000000000000000000000..f6ba70fe7f69cf6de1967c015b8c3ebd5da37145 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_file.py @@ -0,0 +1,623 @@ +""" +Requirements file parsing +""" + +import codecs +import locale +import logging +import optparse +import os +import re +import shlex +import sys +import urllib.parse +from dataclasses import dataclass +from optparse import Values +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Generator, + Iterable, + List, + NoReturn, + Optional, + Tuple, +) + +from pip._internal.cli import cmdoptions +from pip._internal.exceptions import InstallationError, RequirementsFileParseError +from pip._internal.models.search_scope import SearchScope + +if TYPE_CHECKING: + from pip._internal.index.package_finder import PackageFinder + from pip._internal.network.session import PipSession + +__all__ = ["parse_requirements"] + +ReqFileLines = Iterable[Tuple[int, str]] + +LineParser = Callable[[str], Tuple[str, Values]] + +SCHEME_RE = re.compile(r"^(http|https|file):", re.I) +COMMENT_RE = re.compile(r"(^|\s+)#.*$") + +# Matches environment variable-style values in '${MY_VARIABLE_1}' with the +# variable name consisting of only uppercase letters, digits or the '_' +# (underscore). This follows the POSIX standard defined in IEEE Std 1003.1, +# 2013 Edition. +ENV_VAR_RE = re.compile(r"(?P\$\{(?P[A-Z0-9_]+)\})") + +SUPPORTED_OPTIONS: List[Callable[..., optparse.Option]] = [ + cmdoptions.index_url, + cmdoptions.extra_index_url, + cmdoptions.no_index, + cmdoptions.constraints, + cmdoptions.requirements, + cmdoptions.editable, + cmdoptions.find_links, + cmdoptions.no_binary, + cmdoptions.only_binary, + cmdoptions.prefer_binary, + cmdoptions.require_hashes, + cmdoptions.pre, + cmdoptions.trusted_host, + cmdoptions.use_new_feature, +] + +# options to be passed to requirements +SUPPORTED_OPTIONS_REQ: List[Callable[..., optparse.Option]] = [ + cmdoptions.global_options, + cmdoptions.hash, + cmdoptions.config_settings, +] + +SUPPORTED_OPTIONS_EDITABLE_REQ: List[Callable[..., optparse.Option]] = [ + cmdoptions.config_settings, +] + + +# the 'dest' string values +SUPPORTED_OPTIONS_REQ_DEST = [str(o().dest) for o in SUPPORTED_OPTIONS_REQ] +SUPPORTED_OPTIONS_EDITABLE_REQ_DEST = [ + str(o().dest) for o in SUPPORTED_OPTIONS_EDITABLE_REQ +] + +# order of BOMS is important: codecs.BOM_UTF16_LE is a prefix of codecs.BOM_UTF32_LE +# so data.startswith(BOM_UTF16_LE) would be true for UTF32_LE data +BOMS: List[Tuple[bytes, str]] = [ + (codecs.BOM_UTF8, "utf-8"), + (codecs.BOM_UTF32, "utf-32"), + (codecs.BOM_UTF32_BE, "utf-32-be"), + (codecs.BOM_UTF32_LE, "utf-32-le"), + (codecs.BOM_UTF16, "utf-16"), + (codecs.BOM_UTF16_BE, "utf-16-be"), + (codecs.BOM_UTF16_LE, "utf-16-le"), +] + +PEP263_ENCODING_RE = re.compile(rb"coding[:=]\s*([-\w.]+)") +DEFAULT_ENCODING = "utf-8" + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class ParsedRequirement: + # TODO: replace this with slots=True when dropping Python 3.9 support. + __slots__ = ( + "requirement", + "is_editable", + "comes_from", + "constraint", + "options", + "line_source", + ) + + requirement: str + is_editable: bool + comes_from: str + constraint: bool + options: Optional[Dict[str, Any]] + line_source: Optional[str] + + +@dataclass(frozen=True) +class ParsedLine: + __slots__ = ("filename", "lineno", "args", "opts", "constraint") + + filename: str + lineno: int + args: str + opts: Values + constraint: bool + + @property + def is_editable(self) -> bool: + return bool(self.opts.editables) + + @property + def requirement(self) -> Optional[str]: + if self.args: + return self.args + elif self.is_editable: + # We don't support multiple -e on one line + return self.opts.editables[0] + return None + + +def parse_requirements( + filename: str, + session: "PipSession", + finder: Optional["PackageFinder"] = None, + options: Optional[optparse.Values] = None, + constraint: bool = False, +) -> Generator[ParsedRequirement, None, None]: + """Parse a requirements file and yield ParsedRequirement instances. + + :param filename: Path or url of requirements file. + :param session: PipSession instance. + :param finder: Instance of pip.index.PackageFinder. + :param options: cli options. + :param constraint: If true, parsing a constraint file rather than + requirements file. + """ + line_parser = get_line_parser(finder) + parser = RequirementsFileParser(session, line_parser) + + for parsed_line in parser.parse(filename, constraint): + parsed_req = handle_line( + parsed_line, options=options, finder=finder, session=session + ) + if parsed_req is not None: + yield parsed_req + + +def preprocess(content: str) -> ReqFileLines: + """Split, filter, and join lines, and return a line iterator + + :param content: the content of the requirements file + """ + lines_enum: ReqFileLines = enumerate(content.splitlines(), start=1) + lines_enum = join_lines(lines_enum) + lines_enum = ignore_comments(lines_enum) + lines_enum = expand_env_variables(lines_enum) + return lines_enum + + +def handle_requirement_line( + line: ParsedLine, + options: Optional[optparse.Values] = None, +) -> ParsedRequirement: + # preserve for the nested code path + line_comes_from = "{} {} (line {})".format( + "-c" if line.constraint else "-r", + line.filename, + line.lineno, + ) + + assert line.requirement is not None + + # get the options that apply to requirements + if line.is_editable: + supported_dest = SUPPORTED_OPTIONS_EDITABLE_REQ_DEST + else: + supported_dest = SUPPORTED_OPTIONS_REQ_DEST + req_options = {} + for dest in supported_dest: + if dest in line.opts.__dict__ and line.opts.__dict__[dest]: + req_options[dest] = line.opts.__dict__[dest] + + line_source = f"line {line.lineno} of {line.filename}" + return ParsedRequirement( + requirement=line.requirement, + is_editable=line.is_editable, + comes_from=line_comes_from, + constraint=line.constraint, + options=req_options, + line_source=line_source, + ) + + +def handle_option_line( + opts: Values, + filename: str, + lineno: int, + finder: Optional["PackageFinder"] = None, + options: Optional[optparse.Values] = None, + session: Optional["PipSession"] = None, +) -> None: + if opts.hashes: + logger.warning( + "%s line %s has --hash but no requirement, and will be ignored.", + filename, + lineno, + ) + + if options: + # percolate options upward + if opts.require_hashes: + options.require_hashes = opts.require_hashes + if opts.features_enabled: + options.features_enabled.extend( + f for f in opts.features_enabled if f not in options.features_enabled + ) + + # set finder options + if finder: + find_links = finder.find_links + index_urls = finder.index_urls + no_index = finder.search_scope.no_index + if opts.no_index is True: + no_index = True + index_urls = [] + if opts.index_url and not no_index: + index_urls = [opts.index_url] + if opts.extra_index_urls and not no_index: + index_urls.extend(opts.extra_index_urls) + if opts.find_links: + # FIXME: it would be nice to keep track of the source + # of the find_links: support a find-links local path + # relative to a requirements file. + value = opts.find_links[0] + req_dir = os.path.dirname(os.path.abspath(filename)) + relative_to_reqs_file = os.path.join(req_dir, value) + if os.path.exists(relative_to_reqs_file): + value = relative_to_reqs_file + find_links.append(value) + + if session: + # We need to update the auth urls in session + session.update_index_urls(index_urls) + + search_scope = SearchScope( + find_links=find_links, + index_urls=index_urls, + no_index=no_index, + ) + finder.search_scope = search_scope + + if opts.pre: + finder.set_allow_all_prereleases() + + if opts.prefer_binary: + finder.set_prefer_binary() + + if session: + for host in opts.trusted_hosts or []: + source = f"line {lineno} of {filename}" + session.add_trusted_host(host, source=source) + + +def handle_line( + line: ParsedLine, + options: Optional[optparse.Values] = None, + finder: Optional["PackageFinder"] = None, + session: Optional["PipSession"] = None, +) -> Optional[ParsedRequirement]: + """Handle a single parsed requirements line; This can result in + creating/yielding requirements, or updating the finder. + + :param line: The parsed line to be processed. + :param options: CLI options. + :param finder: The finder - updated by non-requirement lines. + :param session: The session - updated by non-requirement lines. + + Returns a ParsedRequirement object if the line is a requirement line, + otherwise returns None. + + For lines that contain requirements, the only options that have an effect + are from SUPPORTED_OPTIONS_REQ, and they are scoped to the + requirement. Other options from SUPPORTED_OPTIONS may be present, but are + ignored. + + For lines that do not contain requirements, the only options that have an + effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may + be present, but are ignored. These lines may contain multiple options + (although our docs imply only one is supported), and all our parsed and + affect the finder. + """ + + if line.requirement is not None: + parsed_req = handle_requirement_line(line, options) + return parsed_req + else: + handle_option_line( + line.opts, + line.filename, + line.lineno, + finder, + options, + session, + ) + return None + + +class RequirementsFileParser: + def __init__( + self, + session: "PipSession", + line_parser: LineParser, + ) -> None: + self._session = session + self._line_parser = line_parser + + def parse( + self, filename: str, constraint: bool + ) -> Generator[ParsedLine, None, None]: + """Parse a given file, yielding parsed lines.""" + yield from self._parse_and_recurse( + filename, constraint, [{os.path.abspath(filename): None}] + ) + + def _parse_and_recurse( + self, + filename: str, + constraint: bool, + parsed_files_stack: List[Dict[str, Optional[str]]], + ) -> Generator[ParsedLine, None, None]: + for line in self._parse_file(filename, constraint): + if line.requirement is None and ( + line.opts.requirements or line.opts.constraints + ): + # parse a nested requirements file + if line.opts.requirements: + req_path = line.opts.requirements[0] + nested_constraint = False + else: + req_path = line.opts.constraints[0] + nested_constraint = True + + # original file is over http + if SCHEME_RE.search(filename): + # do a url join so relative paths work + req_path = urllib.parse.urljoin(filename, req_path) + # original file and nested file are paths + elif not SCHEME_RE.search(req_path): + # do a join so relative paths work + # and then abspath so that we can identify recursive references + req_path = os.path.abspath( + os.path.join( + os.path.dirname(filename), + req_path, + ) + ) + parsed_files = parsed_files_stack[0] + if req_path in parsed_files: + initial_file = parsed_files[req_path] + tail = ( + f" and again in {initial_file}" + if initial_file is not None + else "" + ) + raise RequirementsFileParseError( + f"{req_path} recursively references itself in {filename}{tail}" + ) + # Keeping a track where was each file first included in + new_parsed_files = parsed_files.copy() + new_parsed_files[req_path] = filename + yield from self._parse_and_recurse( + req_path, nested_constraint, [new_parsed_files, *parsed_files_stack] + ) + else: + yield line + + def _parse_file( + self, filename: str, constraint: bool + ) -> Generator[ParsedLine, None, None]: + _, content = get_file_content(filename, self._session) + + lines_enum = preprocess(content) + + for line_number, line in lines_enum: + try: + args_str, opts = self._line_parser(line) + except OptionParsingError as e: + # add offending line + msg = f"Invalid requirement: {line}\n{e.msg}" + raise RequirementsFileParseError(msg) + + yield ParsedLine( + filename, + line_number, + args_str, + opts, + constraint, + ) + + +def get_line_parser(finder: Optional["PackageFinder"]) -> LineParser: + def parse_line(line: str) -> Tuple[str, Values]: + # Build new parser for each line since it accumulates appendable + # options. + parser = build_parser() + defaults = parser.get_default_values() + defaults.index_url = None + if finder: + defaults.format_control = finder.format_control + + args_str, options_str = break_args_options(line) + + try: + options = shlex.split(options_str) + except ValueError as e: + raise OptionParsingError(f"Could not split options: {options_str}") from e + + opts, _ = parser.parse_args(options, defaults) + + return args_str, opts + + return parse_line + + +def break_args_options(line: str) -> Tuple[str, str]: + """Break up the line into an args and options string. We only want to shlex + (and then optparse) the options, not the args. args can contain markers + which are corrupted by shlex. + """ + tokens = line.split(" ") + args = [] + options = tokens[:] + for token in tokens: + if token.startswith("-") or token.startswith("--"): + break + else: + args.append(token) + options.pop(0) + return " ".join(args), " ".join(options) + + +class OptionParsingError(Exception): + def __init__(self, msg: str) -> None: + self.msg = msg + + +def build_parser() -> optparse.OptionParser: + """ + Return a parser for parsing requirement lines + """ + parser = optparse.OptionParser(add_help_option=False) + + option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ + for option_factory in option_factories: + option = option_factory() + parser.add_option(option) + + # By default optparse sys.exits on parsing errors. We want to wrap + # that in our own exception. + def parser_exit(self: Any, msg: str) -> "NoReturn": + raise OptionParsingError(msg) + + # NOTE: mypy disallows assigning to a method + # https://github.com/python/mypy/issues/2427 + parser.exit = parser_exit # type: ignore + + return parser + + +def join_lines(lines_enum: ReqFileLines) -> ReqFileLines: + """Joins a line ending in '\' with the previous line (except when following + comments). The joined line takes on the index of the first line. + """ + primary_line_number = None + new_line: List[str] = [] + for line_number, line in lines_enum: + if not line.endswith("\\") or COMMENT_RE.match(line): + if COMMENT_RE.match(line): + # this ensures comments are always matched later + line = " " + line + if new_line: + new_line.append(line) + assert primary_line_number is not None + yield primary_line_number, "".join(new_line) + new_line = [] + else: + yield line_number, line + else: + if not new_line: + primary_line_number = line_number + new_line.append(line.strip("\\")) + + # last line contains \ + if new_line: + assert primary_line_number is not None + yield primary_line_number, "".join(new_line) + + # TODO: handle space after '\'. + + +def ignore_comments(lines_enum: ReqFileLines) -> ReqFileLines: + """ + Strips comments and filter empty lines. + """ + for line_number, line in lines_enum: + line = COMMENT_RE.sub("", line) + line = line.strip() + if line: + yield line_number, line + + +def expand_env_variables(lines_enum: ReqFileLines) -> ReqFileLines: + """Replace all environment variables that can be retrieved via `os.getenv`. + + The only allowed format for environment variables defined in the + requirement file is `${MY_VARIABLE_1}` to ensure two things: + + 1. Strings that contain a `$` aren't accidentally (partially) expanded. + 2. Ensure consistency across platforms for requirement files. + + These points are the result of a discussion on the `github pull + request #3514 `_. + + Valid characters in variable names follow the `POSIX standard + `_ and are limited + to uppercase letter, digits and the `_` (underscore). + """ + for line_number, line in lines_enum: + for env_var, var_name in ENV_VAR_RE.findall(line): + value = os.getenv(var_name) + if not value: + continue + + line = line.replace(env_var, value) + + yield line_number, line + + +def get_file_content(url: str, session: "PipSession") -> Tuple[str, str]: + """Gets the content of a file; it may be a filename, file: URL, or + http: URL. Returns (location, content). Content is unicode. + Respects # -*- coding: declarations on the retrieved files. + + :param url: File path or url. + :param session: PipSession instance. + """ + scheme = urllib.parse.urlsplit(url).scheme + # Pip has special support for file:// URLs (LocalFSAdapter). + if scheme in ["http", "https", "file"]: + # Delay importing heavy network modules until absolutely necessary. + from pip._internal.network.utils import raise_for_status + + resp = session.get(url) + raise_for_status(resp) + return resp.url, resp.text + + # Assume this is a bare path. + try: + with open(url, "rb") as f: + raw_content = f.read() + except OSError as exc: + raise InstallationError(f"Could not open requirements file: {exc}") + + content = _decode_req_file(raw_content, url) + + return url, content + + +def _decode_req_file(data: bytes, url: str) -> str: + for bom, encoding in BOMS: + if data.startswith(bom): + return data[len(bom) :].decode(encoding) + + for line in data.split(b"\n")[:2]: + if line[0:1] == b"#": + result = PEP263_ENCODING_RE.search(line) + if result is not None: + encoding = result.groups()[0].decode("ascii") + return data.decode(encoding) + + try: + return data.decode(DEFAULT_ENCODING) + except UnicodeDecodeError: + locale_encoding = locale.getpreferredencoding(False) or sys.getdefaultencoding() + logging.warning( + "unable to decode data from %s with default encoding %s, " + "falling back to encoding from locale: %s. " + "If this is intentional you should specify the encoding with a " + "PEP-263 style comment, e.g. '# -*- coding: %s -*-'", + url, + DEFAULT_ENCODING, + locale_encoding, + locale_encoding, + ) + return data.decode(locale_encoding) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_install.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_install.py new file mode 100644 index 0000000000000000000000000000000000000000..3262d82658e93c3a7a71d88d6f14f786fa64b14a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_install.py @@ -0,0 +1,934 @@ +import functools +import logging +import os +import shutil +import sys +import uuid +import zipfile +from optparse import Values +from pathlib import Path +from typing import Any, Collection, Dict, Iterable, List, Optional, Sequence, Union + +from pip._vendor.packaging.markers import Marker +from pip._vendor.packaging.requirements import Requirement +from pip._vendor.packaging.specifiers import SpecifierSet +from pip._vendor.packaging.utils import canonicalize_name +from pip._vendor.packaging.version import Version +from pip._vendor.packaging.version import parse as parse_version +from pip._vendor.pyproject_hooks import BuildBackendHookCaller + +from pip._internal.build_env import BuildEnvironment, NoOpBuildEnvironment +from pip._internal.exceptions import InstallationError, PreviousBuildDirError +from pip._internal.locations import get_scheme +from pip._internal.metadata import ( + BaseDistribution, + get_default_environment, + get_directory_distribution, + get_wheel_distribution, +) +from pip._internal.metadata.base import FilesystemWheel +from pip._internal.models.direct_url import DirectUrl +from pip._internal.models.link import Link +from pip._internal.operations.build.metadata import generate_metadata +from pip._internal.operations.build.metadata_editable import generate_editable_metadata +from pip._internal.operations.build.metadata_legacy import ( + generate_metadata as generate_metadata_legacy, +) +from pip._internal.operations.install.editable_legacy import ( + install_editable as install_editable_legacy, +) +from pip._internal.operations.install.wheel import install_wheel +from pip._internal.pyproject import load_pyproject_toml, make_pyproject_path +from pip._internal.req.req_uninstall import UninstallPathSet +from pip._internal.utils.deprecation import deprecated +from pip._internal.utils.hashes import Hashes +from pip._internal.utils.misc import ( + ConfiguredBuildBackendHookCaller, + ask_path_exists, + backup_dir, + display_path, + hide_url, + is_installable_dir, + redact_auth_from_requirement, + redact_auth_from_url, +) +from pip._internal.utils.packaging import get_requirement +from pip._internal.utils.subprocess import runner_with_spinner_message +from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds +from pip._internal.utils.unpacking import unpack_file +from pip._internal.utils.virtualenv import running_under_virtualenv +from pip._internal.vcs import vcs + +logger = logging.getLogger(__name__) + + +class InstallRequirement: + """ + Represents something that may be installed later on, may have information + about where to fetch the relevant requirement and also contains logic for + installing the said requirement. + """ + + def __init__( + self, + req: Optional[Requirement], + comes_from: Optional[Union[str, "InstallRequirement"]], + editable: bool = False, + link: Optional[Link] = None, + markers: Optional[Marker] = None, + use_pep517: Optional[bool] = None, + isolated: bool = False, + *, + global_options: Optional[List[str]] = None, + hash_options: Optional[Dict[str, List[str]]] = None, + config_settings: Optional[Dict[str, Union[str, List[str]]]] = None, + constraint: bool = False, + extras: Collection[str] = (), + user_supplied: bool = False, + permit_editable_wheels: bool = False, + ) -> None: + assert req is None or isinstance(req, Requirement), req + self.req = req + self.comes_from = comes_from + self.constraint = constraint + self.editable = editable + self.permit_editable_wheels = permit_editable_wheels + + # source_dir is the local directory where the linked requirement is + # located, or unpacked. In case unpacking is needed, creating and + # populating source_dir is done by the RequirementPreparer. Note this + # is not necessarily the directory where pyproject.toml or setup.py is + # located - that one is obtained via unpacked_source_directory. + self.source_dir: Optional[str] = None + if self.editable: + assert link + if link.is_file: + self.source_dir = os.path.normpath(os.path.abspath(link.file_path)) + + # original_link is the direct URL that was provided by the user for the + # requirement, either directly or via a constraints file. + if link is None and req and req.url: + # PEP 508 URL requirement + link = Link(req.url) + self.link = self.original_link = link + + # When this InstallRequirement is a wheel obtained from the cache of locally + # built wheels, this is the source link corresponding to the cache entry, which + # was used to download and build the cached wheel. + self.cached_wheel_source_link: Optional[Link] = None + + # Information about the location of the artifact that was downloaded . This + # property is guaranteed to be set in resolver results. + self.download_info: Optional[DirectUrl] = None + + # Path to any downloaded or already-existing package. + self.local_file_path: Optional[str] = None + if self.link and self.link.is_file: + self.local_file_path = self.link.file_path + + if extras: + self.extras = extras + elif req: + self.extras = req.extras + else: + self.extras = set() + if markers is None and req: + markers = req.marker + self.markers = markers + + # This holds the Distribution object if this requirement is already installed. + self.satisfied_by: Optional[BaseDistribution] = None + # Whether the installation process should try to uninstall an existing + # distribution before installing this requirement. + self.should_reinstall = False + # Temporary build location + self._temp_build_dir: Optional[TempDirectory] = None + # Set to True after successful installation + self.install_succeeded: Optional[bool] = None + # Supplied options + self.global_options = global_options if global_options else [] + self.hash_options = hash_options if hash_options else {} + self.config_settings = config_settings + # Set to True after successful preparation of this requirement + self.prepared = False + # User supplied requirement are explicitly requested for installation + # by the user via CLI arguments or requirements files, as opposed to, + # e.g. dependencies, extras or constraints. + self.user_supplied = user_supplied + + self.isolated = isolated + self.build_env: BuildEnvironment = NoOpBuildEnvironment() + + # For PEP 517, the directory where we request the project metadata + # gets stored. We need this to pass to build_wheel, so the backend + # can ensure that the wheel matches the metadata (see the PEP for + # details). + self.metadata_directory: Optional[str] = None + + # The static build requirements (from pyproject.toml) + self.pyproject_requires: Optional[List[str]] = None + + # Build requirements that we will check are available + self.requirements_to_check: List[str] = [] + + # The PEP 517 backend we should use to build the project + self.pep517_backend: Optional[BuildBackendHookCaller] = None + + # Are we using PEP 517 for this requirement? + # After pyproject.toml has been loaded, the only valid values are True + # and False. Before loading, None is valid (meaning "use the default"). + # Setting an explicit value before loading pyproject.toml is supported, + # but after loading this flag should be treated as read only. + self.use_pep517 = use_pep517 + + # If config settings are provided, enforce PEP 517. + if self.config_settings: + if self.use_pep517 is False: + logger.warning( + "--no-use-pep517 ignored for %s " + "because --config-settings are specified.", + self, + ) + self.use_pep517 = True + + # This requirement needs more preparation before it can be built + self.needs_more_preparation = False + + # This requirement needs to be unpacked before it can be installed. + self._archive_source: Optional[Path] = None + + def __str__(self) -> str: + if self.req: + s = redact_auth_from_requirement(self.req) + if self.link: + s += f" from {redact_auth_from_url(self.link.url)}" + elif self.link: + s = redact_auth_from_url(self.link.url) + else: + s = "" + if self.satisfied_by is not None: + if self.satisfied_by.location is not None: + location = display_path(self.satisfied_by.location) + else: + location = "" + s += f" in {location}" + if self.comes_from: + if isinstance(self.comes_from, str): + comes_from: Optional[str] = self.comes_from + else: + comes_from = self.comes_from.from_path() + if comes_from: + s += f" (from {comes_from})" + return s + + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__} object: " + f"{str(self)} editable={self.editable!r}>" + ) + + def format_debug(self) -> str: + """An un-tested helper for getting state, for debugging.""" + attributes = vars(self) + names = sorted(attributes) + + state = (f"{attr}={attributes[attr]!r}" for attr in sorted(names)) + return "<{name} object: {{{state}}}>".format( + name=self.__class__.__name__, + state=", ".join(state), + ) + + # Things that are valid for all kinds of requirements? + @property + def name(self) -> Optional[str]: + if self.req is None: + return None + return self.req.name + + @functools.cached_property + def supports_pyproject_editable(self) -> bool: + if not self.use_pep517: + return False + assert self.pep517_backend + with self.build_env: + runner = runner_with_spinner_message( + "Checking if build backend supports build_editable" + ) + with self.pep517_backend.subprocess_runner(runner): + return "build_editable" in self.pep517_backend._supported_features() + + @property + def specifier(self) -> SpecifierSet: + assert self.req is not None + return self.req.specifier + + @property + def is_direct(self) -> bool: + """Whether this requirement was specified as a direct URL.""" + return self.original_link is not None + + @property + def is_pinned(self) -> bool: + """Return whether I am pinned to an exact version. + + For example, some-package==1.2 is pinned; some-package>1.2 is not. + """ + assert self.req is not None + specifiers = self.req.specifier + return len(specifiers) == 1 and next(iter(specifiers)).operator in {"==", "==="} + + def match_markers(self, extras_requested: Optional[Iterable[str]] = None) -> bool: + if not extras_requested: + # Provide an extra to safely evaluate the markers + # without matching any extra + extras_requested = ("",) + if self.markers is not None: + return any( + self.markers.evaluate({"extra": extra}) for extra in extras_requested + ) + else: + return True + + @property + def has_hash_options(self) -> bool: + """Return whether any known-good hashes are specified as options. + + These activate --require-hashes mode; hashes specified as part of a + URL do not. + + """ + return bool(self.hash_options) + + def hashes(self, trust_internet: bool = True) -> Hashes: + """Return a hash-comparer that considers my option- and URL-based + hashes to be known-good. + + Hashes in URLs--ones embedded in the requirements file, not ones + downloaded from an index server--are almost peers with ones from + flags. They satisfy --require-hashes (whether it was implicitly or + explicitly activated) but do not activate it. md5 and sha224 are not + allowed in flags, which should nudge people toward good algos. We + always OR all hashes together, even ones from URLs. + + :param trust_internet: Whether to trust URL-based (#md5=...) hashes + downloaded from the internet, as by populate_link() + + """ + good_hashes = self.hash_options.copy() + if trust_internet: + link = self.link + elif self.is_direct and self.user_supplied: + link = self.original_link + else: + link = None + if link and link.hash: + assert link.hash_name is not None + good_hashes.setdefault(link.hash_name, []).append(link.hash) + return Hashes(good_hashes) + + def from_path(self) -> Optional[str]: + """Format a nice indicator to show where this "comes from" """ + if self.req is None: + return None + s = str(self.req) + if self.comes_from: + comes_from: Optional[str] + if isinstance(self.comes_from, str): + comes_from = self.comes_from + else: + comes_from = self.comes_from.from_path() + if comes_from: + s += "->" + comes_from + return s + + def ensure_build_location( + self, build_dir: str, autodelete: bool, parallel_builds: bool + ) -> str: + assert build_dir is not None + if self._temp_build_dir is not None: + assert self._temp_build_dir.path + return self._temp_build_dir.path + if self.req is None: + # Some systems have /tmp as a symlink which confuses custom + # builds (such as numpy). Thus, we ensure that the real path + # is returned. + self._temp_build_dir = TempDirectory( + kind=tempdir_kinds.REQ_BUILD, globally_managed=True + ) + + return self._temp_build_dir.path + + # This is the only remaining place where we manually determine the path + # for the temporary directory. It is only needed for editables where + # it is the value of the --src option. + + # When parallel builds are enabled, add a UUID to the build directory + # name so multiple builds do not interfere with each other. + dir_name: str = canonicalize_name(self.req.name) + if parallel_builds: + dir_name = f"{dir_name}_{uuid.uuid4().hex}" + + # FIXME: Is there a better place to create the build_dir? (hg and bzr + # need this) + if not os.path.exists(build_dir): + logger.debug("Creating directory %s", build_dir) + os.makedirs(build_dir) + actual_build_dir = os.path.join(build_dir, dir_name) + # `None` indicates that we respect the globally-configured deletion + # settings, which is what we actually want when auto-deleting. + delete_arg = None if autodelete else False + return TempDirectory( + path=actual_build_dir, + delete=delete_arg, + kind=tempdir_kinds.REQ_BUILD, + globally_managed=True, + ).path + + def _set_requirement(self) -> None: + """Set requirement after generating metadata.""" + assert self.req is None + assert self.metadata is not None + assert self.source_dir is not None + + # Construct a Requirement object from the generated metadata + if isinstance(parse_version(self.metadata["Version"]), Version): + op = "==" + else: + op = "===" + + self.req = get_requirement( + "".join( + [ + self.metadata["Name"], + op, + self.metadata["Version"], + ] + ) + ) + + def warn_on_mismatching_name(self) -> None: + assert self.req is not None + metadata_name = canonicalize_name(self.metadata["Name"]) + if canonicalize_name(self.req.name) == metadata_name: + # Everything is fine. + return + + # If we're here, there's a mismatch. Log a warning about it. + logger.warning( + "Generating metadata for package %s " + "produced metadata for project name %s. Fix your " + "#egg=%s fragments.", + self.name, + metadata_name, + self.name, + ) + self.req = get_requirement(metadata_name) + + def check_if_exists(self, use_user_site: bool) -> None: + """Find an installed distribution that satisfies or conflicts + with this requirement, and set self.satisfied_by or + self.should_reinstall appropriately. + """ + if self.req is None: + return + existing_dist = get_default_environment().get_distribution(self.req.name) + if not existing_dist: + return + + version_compatible = self.req.specifier.contains( + existing_dist.version, + prereleases=True, + ) + if not version_compatible: + self.satisfied_by = None + if use_user_site: + if existing_dist.in_usersite: + self.should_reinstall = True + elif running_under_virtualenv() and existing_dist.in_site_packages: + raise InstallationError( + f"Will not install to the user site because it will " + f"lack sys.path precedence to {existing_dist.raw_name} " + f"in {existing_dist.location}" + ) + else: + self.should_reinstall = True + else: + if self.editable: + self.should_reinstall = True + # when installing editables, nothing pre-existing should ever + # satisfy + self.satisfied_by = None + else: + self.satisfied_by = existing_dist + + # Things valid for wheels + @property + def is_wheel(self) -> bool: + if not self.link: + return False + return self.link.is_wheel + + @property + def is_wheel_from_cache(self) -> bool: + # When True, it means that this InstallRequirement is a local wheel file in the + # cache of locally built wheels. + return self.cached_wheel_source_link is not None + + # Things valid for sdists + @property + def unpacked_source_directory(self) -> str: + assert self.source_dir, f"No source dir for {self}" + return os.path.join( + self.source_dir, self.link and self.link.subdirectory_fragment or "" + ) + + @property + def setup_py_path(self) -> str: + assert self.source_dir, f"No source dir for {self}" + setup_py = os.path.join(self.unpacked_source_directory, "setup.py") + + return setup_py + + @property + def setup_cfg_path(self) -> str: + assert self.source_dir, f"No source dir for {self}" + setup_cfg = os.path.join(self.unpacked_source_directory, "setup.cfg") + + return setup_cfg + + @property + def pyproject_toml_path(self) -> str: + assert self.source_dir, f"No source dir for {self}" + return make_pyproject_path(self.unpacked_source_directory) + + def load_pyproject_toml(self) -> None: + """Load the pyproject.toml file. + + After calling this routine, all of the attributes related to PEP 517 + processing for this requirement have been set. In particular, the + use_pep517 attribute can be used to determine whether we should + follow the PEP 517 or legacy (setup.py) code path. + """ + pyproject_toml_data = load_pyproject_toml( + self.use_pep517, self.pyproject_toml_path, self.setup_py_path, str(self) + ) + + if pyproject_toml_data is None: + assert not self.config_settings + self.use_pep517 = False + return + + self.use_pep517 = True + requires, backend, check, backend_path = pyproject_toml_data + self.requirements_to_check = check + self.pyproject_requires = requires + self.pep517_backend = ConfiguredBuildBackendHookCaller( + self, + self.unpacked_source_directory, + backend, + backend_path=backend_path, + ) + + def isolated_editable_sanity_check(self) -> None: + """Check that an editable requirement if valid for use with PEP 517/518. + + This verifies that an editable that has a pyproject.toml either supports PEP 660 + or as a setup.py or a setup.cfg + """ + if ( + self.editable + and self.use_pep517 + and not self.supports_pyproject_editable + and not os.path.isfile(self.setup_py_path) + and not os.path.isfile(self.setup_cfg_path) + ): + raise InstallationError( + f"Project {self} has a 'pyproject.toml' and its build " + f"backend is missing the 'build_editable' hook. Since it does not " + f"have a 'setup.py' nor a 'setup.cfg', " + f"it cannot be installed in editable mode. " + f"Consider using a build backend that supports PEP 660." + ) + + def prepare_metadata(self) -> None: + """Ensure that project metadata is available. + + Under PEP 517 and PEP 660, call the backend hook to prepare the metadata. + Under legacy processing, call setup.py egg-info. + """ + assert self.source_dir, f"No source dir for {self}" + details = self.name or f"from {self.link}" + + if self.use_pep517: + assert self.pep517_backend is not None + if ( + self.editable + and self.permit_editable_wheels + and self.supports_pyproject_editable + ): + self.metadata_directory = generate_editable_metadata( + build_env=self.build_env, + backend=self.pep517_backend, + details=details, + ) + else: + self.metadata_directory = generate_metadata( + build_env=self.build_env, + backend=self.pep517_backend, + details=details, + ) + else: + self.metadata_directory = generate_metadata_legacy( + build_env=self.build_env, + setup_py_path=self.setup_py_path, + source_dir=self.unpacked_source_directory, + isolated=self.isolated, + details=details, + ) + + # Act on the newly generated metadata, based on the name and version. + if not self.name: + self._set_requirement() + else: + self.warn_on_mismatching_name() + + self.assert_source_matches_version() + + @property + def metadata(self) -> Any: + if not hasattr(self, "_metadata"): + self._metadata = self.get_dist().metadata + + return self._metadata + + def get_dist(self) -> BaseDistribution: + if self.metadata_directory: + return get_directory_distribution(self.metadata_directory) + elif self.local_file_path and self.is_wheel: + assert self.req is not None + return get_wheel_distribution( + FilesystemWheel(self.local_file_path), + canonicalize_name(self.req.name), + ) + raise AssertionError( + f"InstallRequirement {self} has no metadata directory and no wheel: " + f"can't make a distribution." + ) + + def assert_source_matches_version(self) -> None: + assert self.source_dir, f"No source dir for {self}" + version = self.metadata["version"] + if self.req and self.req.specifier and version not in self.req.specifier: + logger.warning( + "Requested %s, but installing version %s", + self, + version, + ) + else: + logger.debug( + "Source in %s has version %s, which satisfies requirement %s", + display_path(self.source_dir), + version, + self, + ) + + # For both source distributions and editables + def ensure_has_source_dir( + self, + parent_dir: str, + autodelete: bool = False, + parallel_builds: bool = False, + ) -> None: + """Ensure that a source_dir is set. + + This will create a temporary build dir if the name of the requirement + isn't known yet. + + :param parent_dir: The ideal pip parent_dir for the source_dir. + Generally src_dir for editables and build_dir for sdists. + :return: self.source_dir + """ + if self.source_dir is None: + self.source_dir = self.ensure_build_location( + parent_dir, + autodelete=autodelete, + parallel_builds=parallel_builds, + ) + + def needs_unpacked_archive(self, archive_source: Path) -> None: + assert self._archive_source is None + self._archive_source = archive_source + + def ensure_pristine_source_checkout(self) -> None: + """Ensure the source directory has not yet been built in.""" + assert self.source_dir is not None + if self._archive_source is not None: + unpack_file(str(self._archive_source), self.source_dir) + elif is_installable_dir(self.source_dir): + # If a checkout exists, it's unwise to keep going. + # version inconsistencies are logged later, but do not fail + # the installation. + raise PreviousBuildDirError( + f"pip can't proceed with requirements '{self}' due to a " + f"pre-existing build directory ({self.source_dir}). This is likely " + "due to a previous installation that failed . pip is " + "being responsible and not assuming it can delete this. " + "Please delete it and try again." + ) + + # For editable installations + def update_editable(self) -> None: + if not self.link: + logger.debug( + "Cannot update repository at %s; repository location is unknown", + self.source_dir, + ) + return + assert self.editable + assert self.source_dir + if self.link.scheme == "file": + # Static paths don't get updated + return + vcs_backend = vcs.get_backend_for_scheme(self.link.scheme) + # Editable requirements are validated in Requirement constructors. + # So here, if it's neither a path nor a valid VCS URL, it's a bug. + assert vcs_backend, f"Unsupported VCS URL {self.link.url}" + hidden_url = hide_url(self.link.url) + vcs_backend.obtain(self.source_dir, url=hidden_url, verbosity=0) + + # Top-level Actions + def uninstall( + self, auto_confirm: bool = False, verbose: bool = False + ) -> Optional[UninstallPathSet]: + """ + Uninstall the distribution currently satisfying this requirement. + + Prompts before removing or modifying files unless + ``auto_confirm`` is True. + + Refuses to delete or modify files outside of ``sys.prefix`` - + thus uninstallation within a virtual environment can only + modify that virtual environment, even if the virtualenv is + linked to global site-packages. + + """ + assert self.req + dist = get_default_environment().get_distribution(self.req.name) + if not dist: + logger.warning("Skipping %s as it is not installed.", self.name) + return None + logger.info("Found existing installation: %s", dist) + + uninstalled_pathset = UninstallPathSet.from_dist(dist) + uninstalled_pathset.remove(auto_confirm, verbose) + return uninstalled_pathset + + def _get_archive_name(self, path: str, parentdir: str, rootdir: str) -> str: + def _clean_zip_name(name: str, prefix: str) -> str: + assert name.startswith( + prefix + os.path.sep + ), f"name {name!r} doesn't start with prefix {prefix!r}" + name = name[len(prefix) + 1 :] + name = name.replace(os.path.sep, "/") + return name + + assert self.req is not None + path = os.path.join(parentdir, path) + name = _clean_zip_name(path, rootdir) + return self.req.name + "/" + name + + def archive(self, build_dir: Optional[str]) -> None: + """Saves archive to provided build_dir. + + Used for saving downloaded VCS requirements as part of `pip download`. + """ + assert self.source_dir + if build_dir is None: + return + + create_archive = True + archive_name = "{}-{}.zip".format(self.name, self.metadata["version"]) + archive_path = os.path.join(build_dir, archive_name) + + if os.path.exists(archive_path): + response = ask_path_exists( + f"The file {display_path(archive_path)} exists. (i)gnore, (w)ipe, " + "(b)ackup, (a)bort ", + ("i", "w", "b", "a"), + ) + if response == "i": + create_archive = False + elif response == "w": + logger.warning("Deleting %s", display_path(archive_path)) + os.remove(archive_path) + elif response == "b": + dest_file = backup_dir(archive_path) + logger.warning( + "Backing up %s to %s", + display_path(archive_path), + display_path(dest_file), + ) + shutil.move(archive_path, dest_file) + elif response == "a": + sys.exit(-1) + + if not create_archive: + return + + zip_output = zipfile.ZipFile( + archive_path, + "w", + zipfile.ZIP_DEFLATED, + allowZip64=True, + ) + with zip_output: + dir = os.path.normcase(os.path.abspath(self.unpacked_source_directory)) + for dirpath, dirnames, filenames in os.walk(dir): + for dirname in dirnames: + dir_arcname = self._get_archive_name( + dirname, + parentdir=dirpath, + rootdir=dir, + ) + zipdir = zipfile.ZipInfo(dir_arcname + "/") + zipdir.external_attr = 0x1ED << 16 # 0o755 + zip_output.writestr(zipdir, "") + for filename in filenames: + file_arcname = self._get_archive_name( + filename, + parentdir=dirpath, + rootdir=dir, + ) + filename = os.path.join(dirpath, filename) + zip_output.write(filename, file_arcname) + + logger.info("Saved %s", display_path(archive_path)) + + def install( + self, + global_options: Optional[Sequence[str]] = None, + root: Optional[str] = None, + home: Optional[str] = None, + prefix: Optional[str] = None, + warn_script_location: bool = True, + use_user_site: bool = False, + pycompile: bool = True, + ) -> None: + assert self.req is not None + scheme = get_scheme( + self.req.name, + user=use_user_site, + home=home, + root=root, + isolated=self.isolated, + prefix=prefix, + ) + + if self.editable and not self.is_wheel: + deprecated( + reason=( + f"Legacy editable install of {self} (setup.py develop) " + "is deprecated." + ), + replacement=( + "to add a pyproject.toml or enable --use-pep517, " + "and use setuptools >= 64. " + "If the resulting installation is not behaving as expected, " + "try using --config-settings editable_mode=compat. " + "Please consult the setuptools documentation for more information" + ), + gone_in="25.1", + issue=11457, + ) + if self.config_settings: + logger.warning( + "--config-settings ignored for legacy editable install of %s. " + "Consider upgrading to a version of setuptools " + "that supports PEP 660 (>= 64).", + self, + ) + install_editable_legacy( + global_options=global_options if global_options is not None else [], + prefix=prefix, + home=home, + use_user_site=use_user_site, + name=self.req.name, + setup_py_path=self.setup_py_path, + isolated=self.isolated, + build_env=self.build_env, + unpacked_source_directory=self.unpacked_source_directory, + ) + self.install_succeeded = True + return + + assert self.is_wheel + assert self.local_file_path + + install_wheel( + self.req.name, + self.local_file_path, + scheme=scheme, + req_description=str(self.req), + pycompile=pycompile, + warn_script_location=warn_script_location, + direct_url=self.download_info if self.is_direct else None, + requested=self.user_supplied, + ) + self.install_succeeded = True + + +def check_invalid_constraint_type(req: InstallRequirement) -> str: + # Check for unsupported forms + problem = "" + if not req.name: + problem = "Unnamed requirements are not allowed as constraints" + elif req.editable: + problem = "Editable requirements are not allowed as constraints" + elif req.extras: + problem = "Constraints cannot have extras" + + if problem: + deprecated( + reason=( + "Constraints are only allowed to take the form of a package " + "name and a version specifier. Other forms were originally " + "permitted as an accident of the implementation, but were " + "undocumented. The new implementation of the resolver no " + "longer supports these forms." + ), + replacement="replacing the constraint with a requirement", + # No plan yet for when the new resolver becomes default + gone_in=None, + issue=8210, + ) + + return problem + + +def _has_option(options: Values, reqs: List[InstallRequirement], option: str) -> bool: + if getattr(options, option, None): + return True + for req in reqs: + if getattr(req, option, None): + return True + return False + + +def check_legacy_setup_py_options( + options: Values, + reqs: List[InstallRequirement], +) -> None: + has_build_options = _has_option(options, reqs, "build_options") + has_global_options = _has_option(options, reqs, "global_options") + if has_build_options or has_global_options: + deprecated( + reason="--build-option and --global-option are deprecated.", + issue=11859, + replacement="to use --config-settings", + gone_in=None, + ) + logger.warning( + "Implying --no-binary=:all: due to the presence of " + "--build-option / --global-option. " + ) + options.format_control.disallow_binaries() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_set.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_set.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7a6e07a25acfa978030c65ae7c1d8609163249 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_set.py @@ -0,0 +1,82 @@ +import logging +from collections import OrderedDict +from typing import Dict, List + +from pip._vendor.packaging.utils import canonicalize_name + +from pip._internal.req.req_install import InstallRequirement + +logger = logging.getLogger(__name__) + + +class RequirementSet: + def __init__(self, check_supported_wheels: bool = True) -> None: + """Create a RequirementSet.""" + + self.requirements: Dict[str, InstallRequirement] = OrderedDict() + self.check_supported_wheels = check_supported_wheels + + self.unnamed_requirements: List[InstallRequirement] = [] + + def __str__(self) -> str: + requirements = sorted( + (req for req in self.requirements.values() if not req.comes_from), + key=lambda req: canonicalize_name(req.name or ""), + ) + return " ".join(str(req.req) for req in requirements) + + def __repr__(self) -> str: + requirements = sorted( + self.requirements.values(), + key=lambda req: canonicalize_name(req.name or ""), + ) + + format_string = "<{classname} object; {count} requirement(s): {reqs}>" + return format_string.format( + classname=self.__class__.__name__, + count=len(requirements), + reqs=", ".join(str(req.req) for req in requirements), + ) + + def add_unnamed_requirement(self, install_req: InstallRequirement) -> None: + assert not install_req.name + self.unnamed_requirements.append(install_req) + + def add_named_requirement(self, install_req: InstallRequirement) -> None: + assert install_req.name + + project_name = canonicalize_name(install_req.name) + self.requirements[project_name] = install_req + + def has_requirement(self, name: str) -> bool: + project_name = canonicalize_name(name) + + return ( + project_name in self.requirements + and not self.requirements[project_name].constraint + ) + + def get_requirement(self, name: str) -> InstallRequirement: + project_name = canonicalize_name(name) + + if project_name in self.requirements: + return self.requirements[project_name] + + raise KeyError(f"No project with the name {name!r}") + + @property + def all_requirements(self) -> List[InstallRequirement]: + return self.unnamed_requirements + list(self.requirements.values()) + + @property + def requirements_to_install(self) -> List[InstallRequirement]: + """Return the list of requirements that need to be installed. + + TODO remove this property together with the legacy resolver, since the new + resolver only returns requirements that need to be installed. + """ + return [ + install_req + for install_req in self.all_requirements + if not install_req.constraint and not install_req.satisfied_by + ] diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_uninstall.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_uninstall.py new file mode 100644 index 0000000000000000000000000000000000000000..26df20844b379bd7c06f3db7d75cddad5755d22e --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/req/req_uninstall.py @@ -0,0 +1,633 @@ +import functools +import os +import sys +import sysconfig +from importlib.util import cache_from_source +from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Set, Tuple + +from pip._internal.exceptions import LegacyDistutilsInstall, UninstallMissingRecord +from pip._internal.locations import get_bin_prefix, get_bin_user +from pip._internal.metadata import BaseDistribution +from pip._internal.utils.compat import WINDOWS +from pip._internal.utils.egg_link import egg_link_path_from_location +from pip._internal.utils.logging import getLogger, indent_log +from pip._internal.utils.misc import ask, normalize_path, renames, rmtree +from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory +from pip._internal.utils.virtualenv import running_under_virtualenv + +logger = getLogger(__name__) + + +def _script_names( + bin_dir: str, script_name: str, is_gui: bool +) -> Generator[str, None, None]: + """Create the fully qualified name of the files created by + {console,gui}_scripts for the given ``dist``. + Returns the list of file names + """ + exe_name = os.path.join(bin_dir, script_name) + yield exe_name + if not WINDOWS: + return + yield f"{exe_name}.exe" + yield f"{exe_name}.exe.manifest" + if is_gui: + yield f"{exe_name}-script.pyw" + else: + yield f"{exe_name}-script.py" + + +def _unique( + fn: Callable[..., Generator[Any, None, None]] +) -> Callable[..., Generator[Any, None, None]]: + @functools.wraps(fn) + def unique(*args: Any, **kw: Any) -> Generator[Any, None, None]: + seen: Set[Any] = set() + for item in fn(*args, **kw): + if item not in seen: + seen.add(item) + yield item + + return unique + + +@_unique +def uninstallation_paths(dist: BaseDistribution) -> Generator[str, None, None]: + """ + Yield all the uninstallation paths for dist based on RECORD-without-.py[co] + + Yield paths to all the files in RECORD. For each .py file in RECORD, add + the .pyc and .pyo in the same directory. + + UninstallPathSet.add() takes care of the __pycache__ .py[co]. + + If RECORD is not found, raises an error, + with possible information from the INSTALLER file. + + https://packaging.python.org/specifications/recording-installed-packages/ + """ + location = dist.location + assert location is not None, "not installed" + + entries = dist.iter_declared_entries() + if entries is None: + raise UninstallMissingRecord(distribution=dist) + + for entry in entries: + path = os.path.join(location, entry) + yield path + if path.endswith(".py"): + dn, fn = os.path.split(path) + base = fn[:-3] + path = os.path.join(dn, base + ".pyc") + yield path + path = os.path.join(dn, base + ".pyo") + yield path + + +def compact(paths: Iterable[str]) -> Set[str]: + """Compact a path set to contain the minimal number of paths + necessary to contain all paths in the set. If /a/path/ and + /a/path/to/a/file.txt are both in the set, leave only the + shorter path.""" + + sep = os.path.sep + short_paths: Set[str] = set() + for path in sorted(paths, key=len): + should_skip = any( + path.startswith(shortpath.rstrip("*")) + and path[len(shortpath.rstrip("*").rstrip(sep))] == sep + for shortpath in short_paths + ) + if not should_skip: + short_paths.add(path) + return short_paths + + +def compress_for_rename(paths: Iterable[str]) -> Set[str]: + """Returns a set containing the paths that need to be renamed. + + This set may include directories when the original sequence of paths + included every file on disk. + """ + case_map = {os.path.normcase(p): p for p in paths} + remaining = set(case_map) + unchecked = sorted({os.path.split(p)[0] for p in case_map.values()}, key=len) + wildcards: Set[str] = set() + + def norm_join(*a: str) -> str: + return os.path.normcase(os.path.join(*a)) + + for root in unchecked: + if any(os.path.normcase(root).startswith(w) for w in wildcards): + # This directory has already been handled. + continue + + all_files: Set[str] = set() + all_subdirs: Set[str] = set() + for dirname, subdirs, files in os.walk(root): + all_subdirs.update(norm_join(root, dirname, d) for d in subdirs) + all_files.update(norm_join(root, dirname, f) for f in files) + # If all the files we found are in our remaining set of files to + # remove, then remove them from the latter set and add a wildcard + # for the directory. + if not (all_files - remaining): + remaining.difference_update(all_files) + wildcards.add(root + os.sep) + + return set(map(case_map.__getitem__, remaining)) | wildcards + + +def compress_for_output_listing(paths: Iterable[str]) -> Tuple[Set[str], Set[str]]: + """Returns a tuple of 2 sets of which paths to display to user + + The first set contains paths that would be deleted. Files of a package + are not added and the top-level directory of the package has a '*' added + at the end - to signify that all it's contents are removed. + + The second set contains files that would have been skipped in the above + folders. + """ + + will_remove = set(paths) + will_skip = set() + + # Determine folders and files + folders = set() + files = set() + for path in will_remove: + if path.endswith(".pyc"): + continue + if path.endswith("__init__.py") or ".dist-info" in path: + folders.add(os.path.dirname(path)) + files.add(path) + + _normcased_files = set(map(os.path.normcase, files)) + + folders = compact(folders) + + # This walks the tree using os.walk to not miss extra folders + # that might get added. + for folder in folders: + for dirpath, _, dirfiles in os.walk(folder): + for fname in dirfiles: + if fname.endswith(".pyc"): + continue + + file_ = os.path.join(dirpath, fname) + if ( + os.path.isfile(file_) + and os.path.normcase(file_) not in _normcased_files + ): + # We are skipping this file. Add it to the set. + will_skip.add(file_) + + will_remove = files | {os.path.join(folder, "*") for folder in folders} + + return will_remove, will_skip + + +class StashedUninstallPathSet: + """A set of file rename operations to stash files while + tentatively uninstalling them.""" + + def __init__(self) -> None: + # Mapping from source file root to [Adjacent]TempDirectory + # for files under that directory. + self._save_dirs: Dict[str, TempDirectory] = {} + # (old path, new path) tuples for each move that may need + # to be undone. + self._moves: List[Tuple[str, str]] = [] + + def _get_directory_stash(self, path: str) -> str: + """Stashes a directory. + + Directories are stashed adjacent to their original location if + possible, or else moved/copied into the user's temp dir.""" + + try: + save_dir: TempDirectory = AdjacentTempDirectory(path) + except OSError: + save_dir = TempDirectory(kind="uninstall") + self._save_dirs[os.path.normcase(path)] = save_dir + + return save_dir.path + + def _get_file_stash(self, path: str) -> str: + """Stashes a file. + + If no root has been provided, one will be created for the directory + in the user's temp directory.""" + path = os.path.normcase(path) + head, old_head = os.path.dirname(path), None + save_dir = None + + while head != old_head: + try: + save_dir = self._save_dirs[head] + break + except KeyError: + pass + head, old_head = os.path.dirname(head), head + else: + # Did not find any suitable root + head = os.path.dirname(path) + save_dir = TempDirectory(kind="uninstall") + self._save_dirs[head] = save_dir + + relpath = os.path.relpath(path, head) + if relpath and relpath != os.path.curdir: + return os.path.join(save_dir.path, relpath) + return save_dir.path + + def stash(self, path: str) -> str: + """Stashes the directory or file and returns its new location. + Handle symlinks as files to avoid modifying the symlink targets. + """ + path_is_dir = os.path.isdir(path) and not os.path.islink(path) + if path_is_dir: + new_path = self._get_directory_stash(path) + else: + new_path = self._get_file_stash(path) + + self._moves.append((path, new_path)) + if path_is_dir and os.path.isdir(new_path): + # If we're moving a directory, we need to + # remove the destination first or else it will be + # moved to inside the existing directory. + # We just created new_path ourselves, so it will + # be removable. + os.rmdir(new_path) + renames(path, new_path) + return new_path + + def commit(self) -> None: + """Commits the uninstall by removing stashed files.""" + for save_dir in self._save_dirs.values(): + save_dir.cleanup() + self._moves = [] + self._save_dirs = {} + + def rollback(self) -> None: + """Undoes the uninstall by moving stashed files back.""" + for p in self._moves: + logger.info("Moving to %s\n from %s", *p) + + for new_path, path in self._moves: + try: + logger.debug("Replacing %s from %s", new_path, path) + if os.path.isfile(new_path) or os.path.islink(new_path): + os.unlink(new_path) + elif os.path.isdir(new_path): + rmtree(new_path) + renames(path, new_path) + except OSError as ex: + logger.error("Failed to restore %s", new_path) + logger.debug("Exception: %s", ex) + + self.commit() + + @property + def can_rollback(self) -> bool: + return bool(self._moves) + + +class UninstallPathSet: + """A set of file paths to be removed in the uninstallation of a + requirement.""" + + def __init__(self, dist: BaseDistribution) -> None: + self._paths: Set[str] = set() + self._refuse: Set[str] = set() + self._pth: Dict[str, UninstallPthEntries] = {} + self._dist = dist + self._moved_paths = StashedUninstallPathSet() + # Create local cache of normalize_path results. Creating an UninstallPathSet + # can result in hundreds/thousands of redundant calls to normalize_path with + # the same args, which hurts performance. + self._normalize_path_cached = functools.lru_cache(normalize_path) + + def _permitted(self, path: str) -> bool: + """ + Return True if the given path is one we are permitted to + remove/modify, False otherwise. + + """ + # aka is_local, but caching normalized sys.prefix + if not running_under_virtualenv(): + return True + return path.startswith(self._normalize_path_cached(sys.prefix)) + + def add(self, path: str) -> None: + head, tail = os.path.split(path) + + # we normalize the head to resolve parent directory symlinks, but not + # the tail, since we only want to uninstall symlinks, not their targets + path = os.path.join(self._normalize_path_cached(head), os.path.normcase(tail)) + + if not os.path.exists(path): + return + if self._permitted(path): + self._paths.add(path) + else: + self._refuse.add(path) + + # __pycache__ files can show up after 'installed-files.txt' is created, + # due to imports + if os.path.splitext(path)[1] == ".py": + self.add(cache_from_source(path)) + + def add_pth(self, pth_file: str, entry: str) -> None: + pth_file = self._normalize_path_cached(pth_file) + if self._permitted(pth_file): + if pth_file not in self._pth: + self._pth[pth_file] = UninstallPthEntries(pth_file) + self._pth[pth_file].add(entry) + else: + self._refuse.add(pth_file) + + def remove(self, auto_confirm: bool = False, verbose: bool = False) -> None: + """Remove paths in ``self._paths`` with confirmation (unless + ``auto_confirm`` is True).""" + + if not self._paths: + logger.info( + "Can't uninstall '%s'. No files were found to uninstall.", + self._dist.raw_name, + ) + return + + dist_name_version = f"{self._dist.raw_name}-{self._dist.raw_version}" + logger.info("Uninstalling %s:", dist_name_version) + + with indent_log(): + if auto_confirm or self._allowed_to_proceed(verbose): + moved = self._moved_paths + + for_rename = compress_for_rename(self._paths) + + for path in sorted(compact(for_rename)): + moved.stash(path) + logger.verbose("Removing file or directory %s", path) + + for pth in self._pth.values(): + pth.remove() + + logger.info("Successfully uninstalled %s", dist_name_version) + + def _allowed_to_proceed(self, verbose: bool) -> bool: + """Display which files would be deleted and prompt for confirmation""" + + def _display(msg: str, paths: Iterable[str]) -> None: + if not paths: + return + + logger.info(msg) + with indent_log(): + for path in sorted(compact(paths)): + logger.info(path) + + if not verbose: + will_remove, will_skip = compress_for_output_listing(self._paths) + else: + # In verbose mode, display all the files that are going to be + # deleted. + will_remove = set(self._paths) + will_skip = set() + + _display("Would remove:", will_remove) + _display("Would not remove (might be manually added):", will_skip) + _display("Would not remove (outside of prefix):", self._refuse) + if verbose: + _display("Will actually move:", compress_for_rename(self._paths)) + + return ask("Proceed (Y/n)? ", ("y", "n", "")) != "n" + + def rollback(self) -> None: + """Rollback the changes previously made by remove().""" + if not self._moved_paths.can_rollback: + logger.error( + "Can't roll back %s; was not uninstalled", + self._dist.raw_name, + ) + return + logger.info("Rolling back uninstall of %s", self._dist.raw_name) + self._moved_paths.rollback() + for pth in self._pth.values(): + pth.rollback() + + def commit(self) -> None: + """Remove temporary save dir: rollback will no longer be possible.""" + self._moved_paths.commit() + + @classmethod + def from_dist(cls, dist: BaseDistribution) -> "UninstallPathSet": + dist_location = dist.location + info_location = dist.info_location + if dist_location is None: + logger.info( + "Not uninstalling %s since it is not installed", + dist.canonical_name, + ) + return cls(dist) + + normalized_dist_location = normalize_path(dist_location) + if not dist.local: + logger.info( + "Not uninstalling %s at %s, outside environment %s", + dist.canonical_name, + normalized_dist_location, + sys.prefix, + ) + return cls(dist) + + if normalized_dist_location in { + p + for p in {sysconfig.get_path("stdlib"), sysconfig.get_path("platstdlib")} + if p + }: + logger.info( + "Not uninstalling %s at %s, as it is in the standard library.", + dist.canonical_name, + normalized_dist_location, + ) + return cls(dist) + + paths_to_remove = cls(dist) + develop_egg_link = egg_link_path_from_location(dist.raw_name) + + # Distribution is installed with metadata in a "flat" .egg-info + # directory. This means it is not a modern .dist-info installation, an + # egg, or legacy editable. + setuptools_flat_installation = ( + dist.installed_with_setuptools_egg_info + and info_location is not None + and os.path.exists(info_location) + # If dist is editable and the location points to a ``.egg-info``, + # we are in fact in the legacy editable case. + and not info_location.endswith(f"{dist.setuptools_filename}.egg-info") + ) + + # Uninstall cases order do matter as in the case of 2 installs of the + # same package, pip needs to uninstall the currently detected version + if setuptools_flat_installation: + if info_location is not None: + paths_to_remove.add(info_location) + installed_files = dist.iter_declared_entries() + if installed_files is not None: + for installed_file in installed_files: + paths_to_remove.add(os.path.join(dist_location, installed_file)) + # FIXME: need a test for this elif block + # occurs with --single-version-externally-managed/--record outside + # of pip + elif dist.is_file("top_level.txt"): + try: + namespace_packages = dist.read_text("namespace_packages.txt") + except FileNotFoundError: + namespaces = [] + else: + namespaces = namespace_packages.splitlines(keepends=False) + for top_level_pkg in [ + p + for p in dist.read_text("top_level.txt").splitlines() + if p and p not in namespaces + ]: + path = os.path.join(dist_location, top_level_pkg) + paths_to_remove.add(path) + paths_to_remove.add(f"{path}.py") + paths_to_remove.add(f"{path}.pyc") + paths_to_remove.add(f"{path}.pyo") + + elif dist.installed_by_distutils: + raise LegacyDistutilsInstall(distribution=dist) + + elif dist.installed_as_egg: + # package installed by easy_install + # We cannot match on dist.egg_name because it can slightly vary + # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg + paths_to_remove.add(dist_location) + easy_install_egg = os.path.split(dist_location)[1] + easy_install_pth = os.path.join( + os.path.dirname(dist_location), + "easy-install.pth", + ) + paths_to_remove.add_pth(easy_install_pth, "./" + easy_install_egg) + + elif dist.installed_with_dist_info: + for path in uninstallation_paths(dist): + paths_to_remove.add(path) + + elif develop_egg_link: + # PEP 660 modern editable is handled in the ``.dist-info`` case + # above, so this only covers the setuptools-style editable. + with open(develop_egg_link) as fh: + link_pointer = os.path.normcase(fh.readline().strip()) + normalized_link_pointer = paths_to_remove._normalize_path_cached( + link_pointer + ) + assert os.path.samefile( + normalized_link_pointer, normalized_dist_location + ), ( + f"Egg-link {develop_egg_link} (to {link_pointer}) does not match " + f"installed location of {dist.raw_name} (at {dist_location})" + ) + paths_to_remove.add(develop_egg_link) + easy_install_pth = os.path.join( + os.path.dirname(develop_egg_link), "easy-install.pth" + ) + paths_to_remove.add_pth(easy_install_pth, dist_location) + + else: + logger.debug( + "Not sure how to uninstall: %s - Check: %s", + dist, + dist_location, + ) + + if dist.in_usersite: + bin_dir = get_bin_user() + else: + bin_dir = get_bin_prefix() + + # find distutils scripts= scripts + try: + for script in dist.iter_distutils_script_names(): + paths_to_remove.add(os.path.join(bin_dir, script)) + if WINDOWS: + paths_to_remove.add(os.path.join(bin_dir, f"{script}.bat")) + except (FileNotFoundError, NotADirectoryError): + pass + + # find console_scripts and gui_scripts + def iter_scripts_to_remove( + dist: BaseDistribution, + bin_dir: str, + ) -> Generator[str, None, None]: + for entry_point in dist.iter_entry_points(): + if entry_point.group == "console_scripts": + yield from _script_names(bin_dir, entry_point.name, False) + elif entry_point.group == "gui_scripts": + yield from _script_names(bin_dir, entry_point.name, True) + + for s in iter_scripts_to_remove(dist, bin_dir): + paths_to_remove.add(s) + + return paths_to_remove + + +class UninstallPthEntries: + def __init__(self, pth_file: str) -> None: + self.file = pth_file + self.entries: Set[str] = set() + self._saved_lines: Optional[List[bytes]] = None + + def add(self, entry: str) -> None: + entry = os.path.normcase(entry) + # On Windows, os.path.normcase converts the entry to use + # backslashes. This is correct for entries that describe absolute + # paths outside of site-packages, but all the others use forward + # slashes. + # os.path.splitdrive is used instead of os.path.isabs because isabs + # treats non-absolute paths with drive letter markings like c:foo\bar + # as absolute paths. It also does not recognize UNC paths if they don't + # have more than "\\sever\share". Valid examples: "\\server\share\" or + # "\\server\share\folder". + if WINDOWS and not os.path.splitdrive(entry)[0]: + entry = entry.replace("\\", "/") + self.entries.add(entry) + + def remove(self) -> None: + logger.verbose("Removing pth entries from %s:", self.file) + + # If the file doesn't exist, log a warning and return + if not os.path.isfile(self.file): + logger.warning("Cannot remove entries from nonexistent file %s", self.file) + return + with open(self.file, "rb") as fh: + # windows uses '\r\n' with py3k, but uses '\n' with py2.x + lines = fh.readlines() + self._saved_lines = lines + if any(b"\r\n" in line for line in lines): + endline = "\r\n" + else: + endline = "\n" + # handle missing trailing newline + if lines and not lines[-1].endswith(endline.encode("utf-8")): + lines[-1] = lines[-1] + endline.encode("utf-8") + for entry in self.entries: + try: + logger.verbose("Removing entry: %s", entry) + lines.remove((entry + endline).encode("utf-8")) + except ValueError: + pass + with open(self.file, "wb") as fh: + fh.writelines(lines) + + def rollback(self) -> bool: + if self._saved_lines is None: + logger.error("Cannot roll back changes to %s, none were made", self.file) + return False + logger.debug("Rolling %s back to previous state", self.file) + with open(self.file, "wb") as fh: + fh.writelines(self._saved_lines) + return True diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36120194871308a5b8843dd86f001107fe5b4207 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/__pycache__/base.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..588d04fba05dba9f95a3a941756f06ec2c6dfca8 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/__pycache__/base.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/base.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/base.py new file mode 100644 index 0000000000000000000000000000000000000000..42dade18c1ec2b825f756dad4aaa89f2d9e6ce21 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/base.py @@ -0,0 +1,20 @@ +from typing import Callable, List, Optional + +from pip._internal.req.req_install import InstallRequirement +from pip._internal.req.req_set import RequirementSet + +InstallRequirementProvider = Callable[ + [str, Optional[InstallRequirement]], InstallRequirement +] + + +class BaseResolver: + def resolve( + self, root_reqs: List[InstallRequirement], check_supported_wheels: bool + ) -> RequirementSet: + raise NotImplementedError() + + def get_installation_order( + self, req_set: RequirementSet + ) -> List[InstallRequirement]: + raise NotImplementedError() diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72a9296f0959bded446decc54073d310fe170ea6 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/__pycache__/resolver.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/__pycache__/resolver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d82f706c360c3566a33b56cf43b8d169801087f3 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/__pycache__/resolver.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd0d7041bb7a0a32bdf22f825c52f87276e5e07 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/legacy/resolver.py @@ -0,0 +1,597 @@ +"""Dependency Resolution + +The dependency resolution in pip is performed as follows: + +for top-level requirements: + a. only one spec allowed per project, regardless of conflicts or not. + otherwise a "double requirement" exception is raised + b. they override sub-dependency requirements. +for sub-dependencies + a. "first found, wins" (where the order is breadth first) +""" + +import logging +import sys +from collections import defaultdict +from itertools import chain +from typing import DefaultDict, Iterable, List, Optional, Set, Tuple + +from pip._vendor.packaging import specifiers +from pip._vendor.packaging.requirements import Requirement + +from pip._internal.cache import WheelCache +from pip._internal.exceptions import ( + BestVersionAlreadyInstalled, + DistributionNotFound, + HashError, + HashErrors, + InstallationError, + NoneMetadataError, + UnsupportedPythonVersion, +) +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata import BaseDistribution +from pip._internal.models.link import Link +from pip._internal.models.wheel import Wheel +from pip._internal.operations.prepare import RequirementPreparer +from pip._internal.req.req_install import ( + InstallRequirement, + check_invalid_constraint_type, +) +from pip._internal.req.req_set import RequirementSet +from pip._internal.resolution.base import BaseResolver, InstallRequirementProvider +from pip._internal.utils import compatibility_tags +from pip._internal.utils.compatibility_tags import get_supported +from pip._internal.utils.direct_url_helpers import direct_url_from_link +from pip._internal.utils.logging import indent_log +from pip._internal.utils.misc import normalize_version_info +from pip._internal.utils.packaging import check_requires_python + +logger = logging.getLogger(__name__) + +DiscoveredDependencies = DefaultDict[Optional[str], List[InstallRequirement]] + + +def _check_dist_requires_python( + dist: BaseDistribution, + version_info: Tuple[int, int, int], + ignore_requires_python: bool = False, +) -> None: + """ + Check whether the given Python version is compatible with a distribution's + "Requires-Python" value. + + :param version_info: A 3-tuple of ints representing the Python + major-minor-micro version to check. + :param ignore_requires_python: Whether to ignore the "Requires-Python" + value if the given Python version isn't compatible. + + :raises UnsupportedPythonVersion: When the given Python version isn't + compatible. + """ + # This idiosyncratically converts the SpecifierSet to str and let + # check_requires_python then parse it again into SpecifierSet. But this + # is the legacy resolver so I'm just not going to bother refactoring. + try: + requires_python = str(dist.requires_python) + except FileNotFoundError as e: + raise NoneMetadataError(dist, str(e)) + try: + is_compatible = check_requires_python( + requires_python, + version_info=version_info, + ) + except specifiers.InvalidSpecifier as exc: + logger.warning( + "Package %r has an invalid Requires-Python: %s", dist.raw_name, exc + ) + return + + if is_compatible: + return + + version = ".".join(map(str, version_info)) + if ignore_requires_python: + logger.debug( + "Ignoring failed Requires-Python check for package %r: %s not in %r", + dist.raw_name, + version, + requires_python, + ) + return + + raise UnsupportedPythonVersion( + f"Package {dist.raw_name!r} requires a different Python: " + f"{version} not in {requires_python!r}" + ) + + +class Resolver(BaseResolver): + """Resolves which packages need to be installed/uninstalled to perform \ + the requested operation without breaking the requirements of any package. + """ + + _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"} + + def __init__( + self, + preparer: RequirementPreparer, + finder: PackageFinder, + wheel_cache: Optional[WheelCache], + make_install_req: InstallRequirementProvider, + use_user_site: bool, + ignore_dependencies: bool, + ignore_installed: bool, + ignore_requires_python: bool, + force_reinstall: bool, + upgrade_strategy: str, + py_version_info: Optional[Tuple[int, ...]] = None, + ) -> None: + super().__init__() + assert upgrade_strategy in self._allowed_strategies + + if py_version_info is None: + py_version_info = sys.version_info[:3] + else: + py_version_info = normalize_version_info(py_version_info) + + self._py_version_info = py_version_info + + self.preparer = preparer + self.finder = finder + self.wheel_cache = wheel_cache + + self.upgrade_strategy = upgrade_strategy + self.force_reinstall = force_reinstall + self.ignore_dependencies = ignore_dependencies + self.ignore_installed = ignore_installed + self.ignore_requires_python = ignore_requires_python + self.use_user_site = use_user_site + self._make_install_req = make_install_req + + self._discovered_dependencies: DiscoveredDependencies = defaultdict(list) + + def resolve( + self, root_reqs: List[InstallRequirement], check_supported_wheels: bool + ) -> RequirementSet: + """Resolve what operations need to be done + + As a side-effect of this method, the packages (and their dependencies) + are downloaded, unpacked and prepared for installation. This + preparation is done by ``pip.operations.prepare``. + + Once PyPI has static dependency metadata available, it would be + possible to move the preparation to become a step separated from + dependency resolution. + """ + requirement_set = RequirementSet(check_supported_wheels=check_supported_wheels) + for req in root_reqs: + if req.constraint: + check_invalid_constraint_type(req) + self._add_requirement_to_set(requirement_set, req) + + # Actually prepare the files, and collect any exceptions. Most hash + # exceptions cannot be checked ahead of time, because + # _populate_link() needs to be called before we can make decisions + # based on link type. + discovered_reqs: List[InstallRequirement] = [] + hash_errors = HashErrors() + for req in chain(requirement_set.all_requirements, discovered_reqs): + try: + discovered_reqs.extend(self._resolve_one(requirement_set, req)) + except HashError as exc: + exc.req = req + hash_errors.append(exc) + + if hash_errors: + raise hash_errors + + return requirement_set + + def _add_requirement_to_set( + self, + requirement_set: RequirementSet, + install_req: InstallRequirement, + parent_req_name: Optional[str] = None, + extras_requested: Optional[Iterable[str]] = None, + ) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]]: + """Add install_req as a requirement to install. + + :param parent_req_name: The name of the requirement that needed this + added. The name is used because when multiple unnamed requirements + resolve to the same name, we could otherwise end up with dependency + links that point outside the Requirements set. parent_req must + already be added. Note that None implies that this is a user + supplied requirement, vs an inferred one. + :param extras_requested: an iterable of extras used to evaluate the + environment markers. + :return: Additional requirements to scan. That is either [] if + the requirement is not applicable, or [install_req] if the + requirement is applicable and has just been added. + """ + # If the markers do not match, ignore this requirement. + if not install_req.match_markers(extras_requested): + logger.info( + "Ignoring %s: markers '%s' don't match your environment", + install_req.name, + install_req.markers, + ) + return [], None + + # If the wheel is not supported, raise an error. + # Should check this after filtering out based on environment markers to + # allow specifying different wheels based on the environment/OS, in a + # single requirements file. + if install_req.link and install_req.link.is_wheel: + wheel = Wheel(install_req.link.filename) + tags = compatibility_tags.get_supported() + if requirement_set.check_supported_wheels and not wheel.supported(tags): + raise InstallationError( + f"{wheel.filename} is not a supported wheel on this platform." + ) + + # This next bit is really a sanity check. + assert ( + not install_req.user_supplied or parent_req_name is None + ), "a user supplied req shouldn't have a parent" + + # Unnamed requirements are scanned again and the requirement won't be + # added as a dependency until after scanning. + if not install_req.name: + requirement_set.add_unnamed_requirement(install_req) + return [install_req], None + + try: + existing_req: Optional[InstallRequirement] = ( + requirement_set.get_requirement(install_req.name) + ) + except KeyError: + existing_req = None + + has_conflicting_requirement = ( + parent_req_name is None + and existing_req + and not existing_req.constraint + and existing_req.extras == install_req.extras + and existing_req.req + and install_req.req + and existing_req.req.specifier != install_req.req.specifier + ) + if has_conflicting_requirement: + raise InstallationError( + f"Double requirement given: {install_req} " + f"(already in {existing_req}, name={install_req.name!r})" + ) + + # When no existing requirement exists, add the requirement as a + # dependency and it will be scanned again after. + if not existing_req: + requirement_set.add_named_requirement(install_req) + # We'd want to rescan this requirement later + return [install_req], install_req + + # Assume there's no need to scan, and that we've already + # encountered this for scanning. + if install_req.constraint or not existing_req.constraint: + return [], existing_req + + does_not_satisfy_constraint = install_req.link and not ( + existing_req.link and install_req.link.path == existing_req.link.path + ) + if does_not_satisfy_constraint: + raise InstallationError( + f"Could not satisfy constraints for '{install_req.name}': " + "installation from path or url cannot be " + "constrained to a version" + ) + # If we're now installing a constraint, mark the existing + # object for real installation. + existing_req.constraint = False + # If we're now installing a user supplied requirement, + # mark the existing object as such. + if install_req.user_supplied: + existing_req.user_supplied = True + existing_req.extras = tuple( + sorted(set(existing_req.extras) | set(install_req.extras)) + ) + logger.debug( + "Setting %s extras to: %s", + existing_req, + existing_req.extras, + ) + # Return the existing requirement for addition to the parent and + # scanning again. + return [existing_req], existing_req + + def _is_upgrade_allowed(self, req: InstallRequirement) -> bool: + if self.upgrade_strategy == "to-satisfy-only": + return False + elif self.upgrade_strategy == "eager": + return True + else: + assert self.upgrade_strategy == "only-if-needed" + return req.user_supplied or req.constraint + + def _set_req_to_reinstall(self, req: InstallRequirement) -> None: + """ + Set a requirement to be installed. + """ + # Don't uninstall the conflict if doing a user install and the + # conflict is not a user install. + assert req.satisfied_by is not None + if not self.use_user_site or req.satisfied_by.in_usersite: + req.should_reinstall = True + req.satisfied_by = None + + def _check_skip_installed( + self, req_to_install: InstallRequirement + ) -> Optional[str]: + """Check if req_to_install should be skipped. + + This will check if the req is installed, and whether we should upgrade + or reinstall it, taking into account all the relevant user options. + + After calling this req_to_install will only have satisfied_by set to + None if the req_to_install is to be upgraded/reinstalled etc. Any + other value will be a dist recording the current thing installed that + satisfies the requirement. + + Note that for vcs urls and the like we can't assess skipping in this + routine - we simply identify that we need to pull the thing down, + then later on it is pulled down and introspected to assess upgrade/ + reinstalls etc. + + :return: A text reason for why it was skipped, or None. + """ + if self.ignore_installed: + return None + + req_to_install.check_if_exists(self.use_user_site) + if not req_to_install.satisfied_by: + return None + + if self.force_reinstall: + self._set_req_to_reinstall(req_to_install) + return None + + if not self._is_upgrade_allowed(req_to_install): + if self.upgrade_strategy == "only-if-needed": + return "already satisfied, skipping upgrade" + return "already satisfied" + + # Check for the possibility of an upgrade. For link-based + # requirements we have to pull the tree down and inspect to assess + # the version #, so it's handled way down. + if not req_to_install.link: + try: + self.finder.find_requirement(req_to_install, upgrade=True) + except BestVersionAlreadyInstalled: + # Then the best version is installed. + return "already up-to-date" + except DistributionNotFound: + # No distribution found, so we squash the error. It will + # be raised later when we re-try later to do the install. + # Why don't we just raise here? + pass + + self._set_req_to_reinstall(req_to_install) + return None + + def _find_requirement_link(self, req: InstallRequirement) -> Optional[Link]: + upgrade = self._is_upgrade_allowed(req) + best_candidate = self.finder.find_requirement(req, upgrade) + if not best_candidate: + return None + + # Log a warning per PEP 592 if necessary before returning. + link = best_candidate.link + if link.is_yanked: + reason = link.yanked_reason or "" + msg = ( + # Mark this as a unicode string to prevent + # "UnicodeEncodeError: 'ascii' codec can't encode character" + # in Python 2 when the reason contains non-ascii characters. + "The candidate selected for download or install is a " + f"yanked version: {best_candidate}\n" + f"Reason for being yanked: {reason}" + ) + logger.warning(msg) + + return link + + def _populate_link(self, req: InstallRequirement) -> None: + """Ensure that if a link can be found for this, that it is found. + + Note that req.link may still be None - if the requirement is already + installed and not needed to be upgraded based on the return value of + _is_upgrade_allowed(). + + If preparer.require_hashes is True, don't use the wheel cache, because + cached wheels, always built locally, have different hashes than the + files downloaded from the index server and thus throw false hash + mismatches. Furthermore, cached wheels at present have undeterministic + contents due to file modification times. + """ + if req.link is None: + req.link = self._find_requirement_link(req) + + if self.wheel_cache is None or self.preparer.require_hashes: + return + + assert req.link is not None, "_find_requirement_link unexpectedly returned None" + cache_entry = self.wheel_cache.get_cache_entry( + link=req.link, + package_name=req.name, + supported_tags=get_supported(), + ) + if cache_entry is not None: + logger.debug("Using cached wheel link: %s", cache_entry.link) + if req.link is req.original_link and cache_entry.persistent: + req.cached_wheel_source_link = req.link + if cache_entry.origin is not None: + req.download_info = cache_entry.origin + else: + # Legacy cache entry that does not have origin.json. + # download_info may miss the archive_info.hashes field. + req.download_info = direct_url_from_link( + req.link, link_is_in_wheel_cache=cache_entry.persistent + ) + req.link = cache_entry.link + + def _get_dist_for(self, req: InstallRequirement) -> BaseDistribution: + """Takes a InstallRequirement and returns a single AbstractDist \ + representing a prepared variant of the same. + """ + if req.editable: + return self.preparer.prepare_editable_requirement(req) + + # satisfied_by is only evaluated by calling _check_skip_installed, + # so it must be None here. + assert req.satisfied_by is None + skip_reason = self._check_skip_installed(req) + + if req.satisfied_by: + return self.preparer.prepare_installed_requirement(req, skip_reason) + + # We eagerly populate the link, since that's our "legacy" behavior. + self._populate_link(req) + dist = self.preparer.prepare_linked_requirement(req) + + # NOTE + # The following portion is for determining if a certain package is + # going to be re-installed/upgraded or not and reporting to the user. + # This should probably get cleaned up in a future refactor. + + # req.req is only avail after unpack for URL + # pkgs repeat check_if_exists to uninstall-on-upgrade + # (#14) + if not self.ignore_installed: + req.check_if_exists(self.use_user_site) + + if req.satisfied_by: + should_modify = ( + self.upgrade_strategy != "to-satisfy-only" + or self.force_reinstall + or self.ignore_installed + or req.link.scheme == "file" + ) + if should_modify: + self._set_req_to_reinstall(req) + else: + logger.info( + "Requirement already satisfied (use --upgrade to upgrade): %s", + req, + ) + return dist + + def _resolve_one( + self, + requirement_set: RequirementSet, + req_to_install: InstallRequirement, + ) -> List[InstallRequirement]: + """Prepare a single requirements file. + + :return: A list of additional InstallRequirements to also install. + """ + # Tell user what we are doing for this requirement: + # obtain (editable), skipping, processing (local url), collecting + # (remote url or package name) + if req_to_install.constraint or req_to_install.prepared: + return [] + + req_to_install.prepared = True + + # Parse and return dependencies + dist = self._get_dist_for(req_to_install) + # This will raise UnsupportedPythonVersion if the given Python + # version isn't compatible with the distribution's Requires-Python. + _check_dist_requires_python( + dist, + version_info=self._py_version_info, + ignore_requires_python=self.ignore_requires_python, + ) + + more_reqs: List[InstallRequirement] = [] + + def add_req(subreq: Requirement, extras_requested: Iterable[str]) -> None: + # This idiosyncratically converts the Requirement to str and let + # make_install_req then parse it again into Requirement. But this is + # the legacy resolver so I'm just not going to bother refactoring. + sub_install_req = self._make_install_req(str(subreq), req_to_install) + parent_req_name = req_to_install.name + to_scan_again, add_to_parent = self._add_requirement_to_set( + requirement_set, + sub_install_req, + parent_req_name=parent_req_name, + extras_requested=extras_requested, + ) + if parent_req_name and add_to_parent: + self._discovered_dependencies[parent_req_name].append(add_to_parent) + more_reqs.extend(to_scan_again) + + with indent_log(): + # We add req_to_install before its dependencies, so that we + # can refer to it when adding dependencies. + assert req_to_install.name is not None + if not requirement_set.has_requirement(req_to_install.name): + # 'unnamed' requirements will get added here + # 'unnamed' requirements can only come from being directly + # provided by the user. + assert req_to_install.user_supplied + self._add_requirement_to_set( + requirement_set, req_to_install, parent_req_name=None + ) + + if not self.ignore_dependencies: + if req_to_install.extras: + logger.debug( + "Installing extra requirements: %r", + ",".join(req_to_install.extras), + ) + missing_requested = sorted( + set(req_to_install.extras) - set(dist.iter_provided_extras()) + ) + for missing in missing_requested: + logger.warning( + "%s %s does not provide the extra '%s'", + dist.raw_name, + dist.version, + missing, + ) + + available_requested = sorted( + set(dist.iter_provided_extras()) & set(req_to_install.extras) + ) + for subreq in dist.iter_dependencies(available_requested): + add_req(subreq, extras_requested=available_requested) + + return more_reqs + + def get_installation_order( + self, req_set: RequirementSet + ) -> List[InstallRequirement]: + """Create the installation order. + + The installation order is topological - requirements are installed + before the requiring thing. We break cycles at an arbitrary point, + and make no other guarantees. + """ + # The current implementation, which we may change at any point + # installs the user specified things in the order given, except when + # dependencies must come earlier to achieve topological order. + order = [] + ordered_reqs: Set[InstallRequirement] = set() + + def schedule(req: InstallRequirement) -> None: + if req.satisfied_by or req in ordered_reqs: + return + if req.constraint: + return + ordered_reqs.add(req) + for dep in self._discovered_dependencies[req.name]: + schedule(dep) + order.append(req) + + for install_req in req_set.requirements.values(): + schedule(install_req) + return order diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdc6507792e13f87127bc226d2b3be2d7daa48d0 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/base.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89aa13c0590d3db857cd4b24aa4d11df13965999 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/base.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ce64f045f7b884891dc4e8433228075bfb5ca7b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27a106155b8d40cb1c829a0268e7df66541d5344 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d926a378d303d7d191a666a93a220eecfd43a801 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f286c11dd290b117e3a0379722630a26d42e253a Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae46d95e34048008bab0cc6780ea2103add3aaa5 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..076cebeef4fe0c934ecb04a38de3b1d002c0b554 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..514e99fff3ba94312289d18d30cc20826914eb63 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/base.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/base.py new file mode 100644 index 0000000000000000000000000000000000000000..0f31dc9b3073ecf2a9ae234b752e33c8caf5798a --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/base.py @@ -0,0 +1,139 @@ +from dataclasses import dataclass +from typing import FrozenSet, Iterable, Optional, Tuple + +from pip._vendor.packaging.specifiers import SpecifierSet +from pip._vendor.packaging.utils import NormalizedName +from pip._vendor.packaging.version import Version + +from pip._internal.models.link import Link, links_equivalent +from pip._internal.req.req_install import InstallRequirement +from pip._internal.utils.hashes import Hashes + +CandidateLookup = Tuple[Optional["Candidate"], Optional[InstallRequirement]] + + +def format_name(project: NormalizedName, extras: FrozenSet[NormalizedName]) -> str: + if not extras: + return project + extras_expr = ",".join(sorted(extras)) + return f"{project}[{extras_expr}]" + + +@dataclass(frozen=True) +class Constraint: + specifier: SpecifierSet + hashes: Hashes + links: FrozenSet[Link] + + @classmethod + def empty(cls) -> "Constraint": + return Constraint(SpecifierSet(), Hashes(), frozenset()) + + @classmethod + def from_ireq(cls, ireq: InstallRequirement) -> "Constraint": + links = frozenset([ireq.link]) if ireq.link else frozenset() + return Constraint(ireq.specifier, ireq.hashes(trust_internet=False), links) + + def __bool__(self) -> bool: + return bool(self.specifier) or bool(self.hashes) or bool(self.links) + + def __and__(self, other: InstallRequirement) -> "Constraint": + if not isinstance(other, InstallRequirement): + return NotImplemented + specifier = self.specifier & other.specifier + hashes = self.hashes & other.hashes(trust_internet=False) + links = self.links + if other.link: + links = links.union([other.link]) + return Constraint(specifier, hashes, links) + + def is_satisfied_by(self, candidate: "Candidate") -> bool: + # Reject if there are any mismatched URL constraints on this package. + if self.links and not all(_match_link(link, candidate) for link in self.links): + return False + # We can safely always allow prereleases here since PackageFinder + # already implements the prerelease logic, and would have filtered out + # prerelease candidates if the user does not expect them. + return self.specifier.contains(candidate.version, prereleases=True) + + +class Requirement: + @property + def project_name(self) -> NormalizedName: + """The "project name" of a requirement. + + This is different from ``name`` if this requirement contains extras, + in which case ``name`` would contain the ``[...]`` part, while this + refers to the name of the project. + """ + raise NotImplementedError("Subclass should override") + + @property + def name(self) -> str: + """The name identifying this requirement in the resolver. + + This is different from ``project_name`` if this requirement contains + extras, where ``project_name`` would not contain the ``[...]`` part. + """ + raise NotImplementedError("Subclass should override") + + def is_satisfied_by(self, candidate: "Candidate") -> bool: + return False + + def get_candidate_lookup(self) -> CandidateLookup: + raise NotImplementedError("Subclass should override") + + def format_for_error(self) -> str: + raise NotImplementedError("Subclass should override") + + +def _match_link(link: Link, candidate: "Candidate") -> bool: + if candidate.source_link: + return links_equivalent(link, candidate.source_link) + return False + + +class Candidate: + @property + def project_name(self) -> NormalizedName: + """The "project name" of the candidate. + + This is different from ``name`` if this candidate contains extras, + in which case ``name`` would contain the ``[...]`` part, while this + refers to the name of the project. + """ + raise NotImplementedError("Override in subclass") + + @property + def name(self) -> str: + """The name identifying this candidate in the resolver. + + This is different from ``project_name`` if this candidate contains + extras, where ``project_name`` would not contain the ``[...]`` part. + """ + raise NotImplementedError("Override in subclass") + + @property + def version(self) -> Version: + raise NotImplementedError("Override in subclass") + + @property + def is_installed(self) -> bool: + raise NotImplementedError("Override in subclass") + + @property + def is_editable(self) -> bool: + raise NotImplementedError("Override in subclass") + + @property + def source_link(self) -> Optional[Link]: + raise NotImplementedError("Override in subclass") + + def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]: + raise NotImplementedError("Override in subclass") + + def get_install_requirement(self) -> Optional[InstallRequirement]: + raise NotImplementedError("Override in subclass") + + def format_for_error(self) -> str: + raise NotImplementedError("Subclass should override") diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py new file mode 100644 index 0000000000000000000000000000000000000000..6617644fe5316cb739050cc2266a5c015f9279e3 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/candidates.py @@ -0,0 +1,574 @@ +import logging +import sys +from typing import TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Tuple, Union, cast + +from pip._vendor.packaging.requirements import InvalidRequirement +from pip._vendor.packaging.utils import NormalizedName, canonicalize_name +from pip._vendor.packaging.version import Version + +from pip._internal.exceptions import ( + HashError, + InstallationSubprocessError, + InvalidInstalledPackage, + MetadataInconsistent, + MetadataInvalid, +) +from pip._internal.metadata import BaseDistribution +from pip._internal.models.link import Link, links_equivalent +from pip._internal.models.wheel import Wheel +from pip._internal.req.constructors import ( + install_req_from_editable, + install_req_from_line, +) +from pip._internal.req.req_install import InstallRequirement +from pip._internal.utils.direct_url_helpers import direct_url_from_link +from pip._internal.utils.misc import normalize_version_info + +from .base import Candidate, Requirement, format_name + +if TYPE_CHECKING: + from .factory import Factory + +logger = logging.getLogger(__name__) + +BaseCandidate = Union[ + "AlreadyInstalledCandidate", + "EditableCandidate", + "LinkCandidate", +] + +# Avoid conflicting with the PyPI package "Python". +REQUIRES_PYTHON_IDENTIFIER = cast(NormalizedName, "") + + +def as_base_candidate(candidate: Candidate) -> Optional[BaseCandidate]: + """The runtime version of BaseCandidate.""" + base_candidate_classes = ( + AlreadyInstalledCandidate, + EditableCandidate, + LinkCandidate, + ) + if isinstance(candidate, base_candidate_classes): + return candidate + return None + + +def make_install_req_from_link( + link: Link, template: InstallRequirement +) -> InstallRequirement: + assert not template.editable, "template is editable" + if template.req: + line = str(template.req) + else: + line = link.url + ireq = install_req_from_line( + line, + user_supplied=template.user_supplied, + comes_from=template.comes_from, + use_pep517=template.use_pep517, + isolated=template.isolated, + constraint=template.constraint, + global_options=template.global_options, + hash_options=template.hash_options, + config_settings=template.config_settings, + ) + ireq.original_link = template.original_link + ireq.link = link + ireq.extras = template.extras + return ireq + + +def make_install_req_from_editable( + link: Link, template: InstallRequirement +) -> InstallRequirement: + assert template.editable, "template not editable" + ireq = install_req_from_editable( + link.url, + user_supplied=template.user_supplied, + comes_from=template.comes_from, + use_pep517=template.use_pep517, + isolated=template.isolated, + constraint=template.constraint, + permit_editable_wheels=template.permit_editable_wheels, + global_options=template.global_options, + hash_options=template.hash_options, + config_settings=template.config_settings, + ) + ireq.extras = template.extras + return ireq + + +def _make_install_req_from_dist( + dist: BaseDistribution, template: InstallRequirement +) -> InstallRequirement: + if template.req: + line = str(template.req) + elif template.link: + line = f"{dist.canonical_name} @ {template.link.url}" + else: + line = f"{dist.canonical_name}=={dist.version}" + ireq = install_req_from_line( + line, + user_supplied=template.user_supplied, + comes_from=template.comes_from, + use_pep517=template.use_pep517, + isolated=template.isolated, + constraint=template.constraint, + global_options=template.global_options, + hash_options=template.hash_options, + config_settings=template.config_settings, + ) + ireq.satisfied_by = dist + return ireq + + +class _InstallRequirementBackedCandidate(Candidate): + """A candidate backed by an ``InstallRequirement``. + + This represents a package request with the target not being already + in the environment, and needs to be fetched and installed. The backing + ``InstallRequirement`` is responsible for most of the leg work; this + class exposes appropriate information to the resolver. + + :param link: The link passed to the ``InstallRequirement``. The backing + ``InstallRequirement`` will use this link to fetch the distribution. + :param source_link: The link this candidate "originates" from. This is + different from ``link`` when the link is found in the wheel cache. + ``link`` would point to the wheel cache, while this points to the + found remote link (e.g. from pypi.org). + """ + + dist: BaseDistribution + is_installed = False + + def __init__( + self, + link: Link, + source_link: Link, + ireq: InstallRequirement, + factory: "Factory", + name: Optional[NormalizedName] = None, + version: Optional[Version] = None, + ) -> None: + self._link = link + self._source_link = source_link + self._factory = factory + self._ireq = ireq + self._name = name + self._version = version + self.dist = self._prepare() + self._hash: Optional[int] = None + + def __str__(self) -> str: + return f"{self.name} {self.version}" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({str(self._link)!r})" + + def __hash__(self) -> int: + if self._hash is not None: + return self._hash + + self._hash = hash((self.__class__, self._link)) + return self._hash + + def __eq__(self, other: Any) -> bool: + if isinstance(other, self.__class__): + return links_equivalent(self._link, other._link) + return False + + @property + def source_link(self) -> Optional[Link]: + return self._source_link + + @property + def project_name(self) -> NormalizedName: + """The normalised name of the project the candidate refers to""" + if self._name is None: + self._name = self.dist.canonical_name + return self._name + + @property + def name(self) -> str: + return self.project_name + + @property + def version(self) -> Version: + if self._version is None: + self._version = self.dist.version + return self._version + + def format_for_error(self) -> str: + return ( + f"{self.name} {self.version} " + f"(from {self._link.file_path if self._link.is_file else self._link})" + ) + + def _prepare_distribution(self) -> BaseDistribution: + raise NotImplementedError("Override in subclass") + + def _check_metadata_consistency(self, dist: BaseDistribution) -> None: + """Check for consistency of project name and version of dist.""" + if self._name is not None and self._name != dist.canonical_name: + raise MetadataInconsistent( + self._ireq, + "name", + self._name, + dist.canonical_name, + ) + if self._version is not None and self._version != dist.version: + raise MetadataInconsistent( + self._ireq, + "version", + str(self._version), + str(dist.version), + ) + # check dependencies are valid + # TODO performance: this means we iterate the dependencies at least twice, + # we may want to cache parsed Requires-Dist + try: + list(dist.iter_dependencies(list(dist.iter_provided_extras()))) + except InvalidRequirement as e: + raise MetadataInvalid(self._ireq, str(e)) + + def _prepare(self) -> BaseDistribution: + try: + dist = self._prepare_distribution() + except HashError as e: + # Provide HashError the underlying ireq that caused it. This + # provides context for the resulting error message to show the + # offending line to the user. + e.req = self._ireq + raise + except InstallationSubprocessError as exc: + # The output has been presented already, so don't duplicate it. + exc.context = "See above for output." + raise + + self._check_metadata_consistency(dist) + return dist + + def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]: + requires = self.dist.iter_dependencies() if with_requires else () + for r in requires: + yield from self._factory.make_requirements_from_spec(str(r), self._ireq) + yield self._factory.make_requires_python_requirement(self.dist.requires_python) + + def get_install_requirement(self) -> Optional[InstallRequirement]: + return self._ireq + + +class LinkCandidate(_InstallRequirementBackedCandidate): + is_editable = False + + def __init__( + self, + link: Link, + template: InstallRequirement, + factory: "Factory", + name: Optional[NormalizedName] = None, + version: Optional[Version] = None, + ) -> None: + source_link = link + cache_entry = factory.get_wheel_cache_entry(source_link, name) + if cache_entry is not None: + logger.debug("Using cached wheel link: %s", cache_entry.link) + link = cache_entry.link + ireq = make_install_req_from_link(link, template) + assert ireq.link == link + if ireq.link.is_wheel and not ireq.link.is_file: + wheel = Wheel(ireq.link.filename) + wheel_name = canonicalize_name(wheel.name) + assert name == wheel_name, f"{name!r} != {wheel_name!r} for wheel" + # Version may not be present for PEP 508 direct URLs + if version is not None: + wheel_version = Version(wheel.version) + assert ( + version == wheel_version + ), f"{version!r} != {wheel_version!r} for wheel {name}" + + if cache_entry is not None: + assert ireq.link.is_wheel + assert ireq.link.is_file + if cache_entry.persistent and template.link is template.original_link: + ireq.cached_wheel_source_link = source_link + if cache_entry.origin is not None: + ireq.download_info = cache_entry.origin + else: + # Legacy cache entry that does not have origin.json. + # download_info may miss the archive_info.hashes field. + ireq.download_info = direct_url_from_link( + source_link, link_is_in_wheel_cache=cache_entry.persistent + ) + + super().__init__( + link=link, + source_link=source_link, + ireq=ireq, + factory=factory, + name=name, + version=version, + ) + + def _prepare_distribution(self) -> BaseDistribution: + preparer = self._factory.preparer + return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True) + + +class EditableCandidate(_InstallRequirementBackedCandidate): + is_editable = True + + def __init__( + self, + link: Link, + template: InstallRequirement, + factory: "Factory", + name: Optional[NormalizedName] = None, + version: Optional[Version] = None, + ) -> None: + super().__init__( + link=link, + source_link=link, + ireq=make_install_req_from_editable(link, template), + factory=factory, + name=name, + version=version, + ) + + def _prepare_distribution(self) -> BaseDistribution: + return self._factory.preparer.prepare_editable_requirement(self._ireq) + + +class AlreadyInstalledCandidate(Candidate): + is_installed = True + source_link = None + + def __init__( + self, + dist: BaseDistribution, + template: InstallRequirement, + factory: "Factory", + ) -> None: + self.dist = dist + self._ireq = _make_install_req_from_dist(dist, template) + self._factory = factory + self._version = None + + # This is just logging some messages, so we can do it eagerly. + # The returned dist would be exactly the same as self.dist because we + # set satisfied_by in _make_install_req_from_dist. + # TODO: Supply reason based on force_reinstall and upgrade_strategy. + skip_reason = "already satisfied" + factory.preparer.prepare_installed_requirement(self._ireq, skip_reason) + + def __str__(self) -> str: + return str(self.dist) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.dist!r})" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, AlreadyInstalledCandidate): + return NotImplemented + return self.name == other.name and self.version == other.version + + def __hash__(self) -> int: + return hash((self.name, self.version)) + + @property + def project_name(self) -> NormalizedName: + return self.dist.canonical_name + + @property + def name(self) -> str: + return self.project_name + + @property + def version(self) -> Version: + if self._version is None: + self._version = self.dist.version + return self._version + + @property + def is_editable(self) -> bool: + return self.dist.editable + + def format_for_error(self) -> str: + return f"{self.name} {self.version} (Installed)" + + def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]: + if not with_requires: + return + + try: + for r in self.dist.iter_dependencies(): + yield from self._factory.make_requirements_from_spec(str(r), self._ireq) + except InvalidRequirement as exc: + raise InvalidInstalledPackage(dist=self.dist, invalid_exc=exc) from None + + def get_install_requirement(self) -> Optional[InstallRequirement]: + return None + + +class ExtrasCandidate(Candidate): + """A candidate that has 'extras', indicating additional dependencies. + + Requirements can be for a project with dependencies, something like + foo[extra]. The extras don't affect the project/version being installed + directly, but indicate that we need additional dependencies. We model that + by having an artificial ExtrasCandidate that wraps the "base" candidate. + + The ExtrasCandidate differs from the base in the following ways: + + 1. It has a unique name, of the form foo[extra]. This causes the resolver + to treat it as a separate node in the dependency graph. + 2. When we're getting the candidate's dependencies, + a) We specify that we want the extra dependencies as well. + b) We add a dependency on the base candidate. + See below for why this is needed. + 3. We return None for the underlying InstallRequirement, as the base + candidate will provide it, and we don't want to end up with duplicates. + + The dependency on the base candidate is needed so that the resolver can't + decide that it should recommend foo[extra1] version 1.0 and foo[extra2] + version 2.0. Having those candidates depend on foo=1.0 and foo=2.0 + respectively forces the resolver to recognise that this is a conflict. + """ + + def __init__( + self, + base: BaseCandidate, + extras: FrozenSet[str], + *, + comes_from: Optional[InstallRequirement] = None, + ) -> None: + """ + :param comes_from: the InstallRequirement that led to this candidate if it + differs from the base's InstallRequirement. This will often be the + case in the sense that this candidate's requirement has the extras + while the base's does not. Unlike the InstallRequirement backed + candidates, this requirement is used solely for reporting purposes, + it does not do any leg work. + """ + self.base = base + self.extras = frozenset(canonicalize_name(e) for e in extras) + self._comes_from = comes_from if comes_from is not None else self.base._ireq + + def __str__(self) -> str: + name, rest = str(self.base).split(" ", 1) + return "{}[{}] {}".format(name, ",".join(self.extras), rest) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(base={self.base!r}, extras={self.extras!r})" + + def __hash__(self) -> int: + return hash((self.base, self.extras)) + + def __eq__(self, other: Any) -> bool: + if isinstance(other, self.__class__): + return self.base == other.base and self.extras == other.extras + return False + + @property + def project_name(self) -> NormalizedName: + return self.base.project_name + + @property + def name(self) -> str: + """The normalised name of the project the candidate refers to""" + return format_name(self.base.project_name, self.extras) + + @property + def version(self) -> Version: + return self.base.version + + def format_for_error(self) -> str: + return "{} [{}]".format( + self.base.format_for_error(), ", ".join(sorted(self.extras)) + ) + + @property + def is_installed(self) -> bool: + return self.base.is_installed + + @property + def is_editable(self) -> bool: + return self.base.is_editable + + @property + def source_link(self) -> Optional[Link]: + return self.base.source_link + + def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]: + factory = self.base._factory + + # Add a dependency on the exact base + # (See note 2b in the class docstring) + yield factory.make_requirement_from_candidate(self.base) + if not with_requires: + return + + # The user may have specified extras that the candidate doesn't + # support. We ignore any unsupported extras here. + valid_extras = self.extras.intersection(self.base.dist.iter_provided_extras()) + invalid_extras = self.extras.difference(self.base.dist.iter_provided_extras()) + for extra in sorted(invalid_extras): + logger.warning( + "%s %s does not provide the extra '%s'", + self.base.name, + self.version, + extra, + ) + + for r in self.base.dist.iter_dependencies(valid_extras): + yield from factory.make_requirements_from_spec( + str(r), + self._comes_from, + valid_extras, + ) + + def get_install_requirement(self) -> Optional[InstallRequirement]: + # We don't return anything here, because we always + # depend on the base candidate, and we'll get the + # install requirement from that. + return None + + +class RequiresPythonCandidate(Candidate): + is_installed = False + source_link = None + + def __init__(self, py_version_info: Optional[Tuple[int, ...]]) -> None: + if py_version_info is not None: + version_info = normalize_version_info(py_version_info) + else: + version_info = sys.version_info[:3] + self._version = Version(".".join(str(c) for c in version_info)) + + # We don't need to implement __eq__() and __ne__() since there is always + # only one RequiresPythonCandidate in a resolution, i.e. the host Python. + # The built-in object.__eq__() and object.__ne__() do exactly what we want. + + def __str__(self) -> str: + return f"Python {self._version}" + + @property + def project_name(self) -> NormalizedName: + return REQUIRES_PYTHON_IDENTIFIER + + @property + def name(self) -> str: + return REQUIRES_PYTHON_IDENTIFIER + + @property + def version(self) -> Version: + return self._version + + def format_for_error(self) -> str: + return f"Python {self.version}" + + def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]: + return () + + def get_install_requirement(self) -> Optional[InstallRequirement]: + return None diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..6c273eb88dbc6b2de39b6f444991f3781834854b --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/factory.py @@ -0,0 +1,823 @@ +import contextlib +import functools +import logging +from typing import ( + TYPE_CHECKING, + Callable, + Dict, + FrozenSet, + Iterable, + Iterator, + List, + Mapping, + NamedTuple, + Optional, + Protocol, + Sequence, + Set, + Tuple, + TypeVar, + cast, +) + +from pip._vendor.packaging.requirements import InvalidRequirement +from pip._vendor.packaging.specifiers import SpecifierSet +from pip._vendor.packaging.utils import NormalizedName, canonicalize_name +from pip._vendor.packaging.version import InvalidVersion, Version +from pip._vendor.resolvelib import ResolutionImpossible + +from pip._internal.cache import CacheEntry, WheelCache +from pip._internal.exceptions import ( + DistributionNotFound, + InstallationError, + InvalidInstalledPackage, + MetadataInconsistent, + MetadataInvalid, + UnsupportedPythonVersion, + UnsupportedWheel, +) +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata import BaseDistribution, get_default_environment +from pip._internal.models.link import Link +from pip._internal.models.wheel import Wheel +from pip._internal.operations.prepare import RequirementPreparer +from pip._internal.req.constructors import ( + install_req_drop_extras, + install_req_from_link_and_ireq, +) +from pip._internal.req.req_install import ( + InstallRequirement, + check_invalid_constraint_type, +) +from pip._internal.resolution.base import InstallRequirementProvider +from pip._internal.utils.compatibility_tags import get_supported +from pip._internal.utils.hashes import Hashes +from pip._internal.utils.packaging import get_requirement +from pip._internal.utils.virtualenv import running_under_virtualenv + +from .base import Candidate, Constraint, Requirement +from .candidates import ( + AlreadyInstalledCandidate, + BaseCandidate, + EditableCandidate, + ExtrasCandidate, + LinkCandidate, + RequiresPythonCandidate, + as_base_candidate, +) +from .found_candidates import FoundCandidates, IndexCandidateInfo +from .requirements import ( + ExplicitRequirement, + RequiresPythonRequirement, + SpecifierRequirement, + SpecifierWithoutExtrasRequirement, + UnsatisfiableRequirement, +) + +if TYPE_CHECKING: + + class ConflictCause(Protocol): + requirement: RequiresPythonRequirement + parent: Candidate + + +logger = logging.getLogger(__name__) + +C = TypeVar("C") +Cache = Dict[Link, C] + + +class CollectedRootRequirements(NamedTuple): + requirements: List[Requirement] + constraints: Dict[str, Constraint] + user_requested: Dict[str, int] + + +class Factory: + def __init__( + self, + finder: PackageFinder, + preparer: RequirementPreparer, + make_install_req: InstallRequirementProvider, + wheel_cache: Optional[WheelCache], + use_user_site: bool, + force_reinstall: bool, + ignore_installed: bool, + ignore_requires_python: bool, + py_version_info: Optional[Tuple[int, ...]] = None, + ) -> None: + self._finder = finder + self.preparer = preparer + self._wheel_cache = wheel_cache + self._python_candidate = RequiresPythonCandidate(py_version_info) + self._make_install_req_from_spec = make_install_req + self._use_user_site = use_user_site + self._force_reinstall = force_reinstall + self._ignore_requires_python = ignore_requires_python + + self._build_failures: Cache[InstallationError] = {} + self._link_candidate_cache: Cache[LinkCandidate] = {} + self._editable_candidate_cache: Cache[EditableCandidate] = {} + self._installed_candidate_cache: Dict[str, AlreadyInstalledCandidate] = {} + self._extras_candidate_cache: Dict[ + Tuple[int, FrozenSet[NormalizedName]], ExtrasCandidate + ] = {} + self._supported_tags_cache = get_supported() + + if not ignore_installed: + env = get_default_environment() + self._installed_dists = { + dist.canonical_name: dist + for dist in env.iter_installed_distributions(local_only=False) + } + else: + self._installed_dists = {} + + @property + def force_reinstall(self) -> bool: + return self._force_reinstall + + def _fail_if_link_is_unsupported_wheel(self, link: Link) -> None: + if not link.is_wheel: + return + wheel = Wheel(link.filename) + if wheel.supported(self._finder.target_python.get_unsorted_tags()): + return + msg = f"{link.filename} is not a supported wheel on this platform." + raise UnsupportedWheel(msg) + + def _make_extras_candidate( + self, + base: BaseCandidate, + extras: FrozenSet[str], + *, + comes_from: Optional[InstallRequirement] = None, + ) -> ExtrasCandidate: + cache_key = (id(base), frozenset(canonicalize_name(e) for e in extras)) + try: + candidate = self._extras_candidate_cache[cache_key] + except KeyError: + candidate = ExtrasCandidate(base, extras, comes_from=comes_from) + self._extras_candidate_cache[cache_key] = candidate + return candidate + + def _make_candidate_from_dist( + self, + dist: BaseDistribution, + extras: FrozenSet[str], + template: InstallRequirement, + ) -> Candidate: + try: + base = self._installed_candidate_cache[dist.canonical_name] + except KeyError: + base = AlreadyInstalledCandidate(dist, template, factory=self) + self._installed_candidate_cache[dist.canonical_name] = base + if not extras: + return base + return self._make_extras_candidate(base, extras, comes_from=template) + + def _make_candidate_from_link( + self, + link: Link, + extras: FrozenSet[str], + template: InstallRequirement, + name: Optional[NormalizedName], + version: Optional[Version], + ) -> Optional[Candidate]: + base: Optional[BaseCandidate] = self._make_base_candidate_from_link( + link, template, name, version + ) + if not extras or base is None: + return base + return self._make_extras_candidate(base, extras, comes_from=template) + + def _make_base_candidate_from_link( + self, + link: Link, + template: InstallRequirement, + name: Optional[NormalizedName], + version: Optional[Version], + ) -> Optional[BaseCandidate]: + # TODO: Check already installed candidate, and use it if the link and + # editable flag match. + + if link in self._build_failures: + # We already tried this candidate before, and it does not build. + # Don't bother trying again. + return None + + if template.editable: + if link not in self._editable_candidate_cache: + try: + self._editable_candidate_cache[link] = EditableCandidate( + link, + template, + factory=self, + name=name, + version=version, + ) + except (MetadataInconsistent, MetadataInvalid) as e: + logger.info( + "Discarding [blue underline]%s[/]: [yellow]%s[reset]", + link, + e, + extra={"markup": True}, + ) + self._build_failures[link] = e + return None + + return self._editable_candidate_cache[link] + else: + if link not in self._link_candidate_cache: + try: + self._link_candidate_cache[link] = LinkCandidate( + link, + template, + factory=self, + name=name, + version=version, + ) + except MetadataInconsistent as e: + logger.info( + "Discarding [blue underline]%s[/]: [yellow]%s[reset]", + link, + e, + extra={"markup": True}, + ) + self._build_failures[link] = e + return None + return self._link_candidate_cache[link] + + def _iter_found_candidates( + self, + ireqs: Sequence[InstallRequirement], + specifier: SpecifierSet, + hashes: Hashes, + prefers_installed: bool, + incompatible_ids: Set[int], + ) -> Iterable[Candidate]: + if not ireqs: + return () + + # The InstallRequirement implementation requires us to give it a + # "template". Here we just choose the first requirement to represent + # all of them. + # Hopefully the Project model can correct this mismatch in the future. + template = ireqs[0] + assert template.req, "Candidates found on index must be PEP 508" + name = canonicalize_name(template.req.name) + + extras: FrozenSet[str] = frozenset() + for ireq in ireqs: + assert ireq.req, "Candidates found on index must be PEP 508" + specifier &= ireq.req.specifier + hashes &= ireq.hashes(trust_internet=False) + extras |= frozenset(ireq.extras) + + def _get_installed_candidate() -> Optional[Candidate]: + """Get the candidate for the currently-installed version.""" + # If --force-reinstall is set, we want the version from the index + # instead, so we "pretend" there is nothing installed. + if self._force_reinstall: + return None + try: + installed_dist = self._installed_dists[name] + except KeyError: + return None + + try: + # Don't use the installed distribution if its version + # does not fit the current dependency graph. + if not specifier.contains(installed_dist.version, prereleases=True): + return None + except InvalidVersion as e: + raise InvalidInstalledPackage(dist=installed_dist, invalid_exc=e) + + candidate = self._make_candidate_from_dist( + dist=installed_dist, + extras=extras, + template=template, + ) + # The candidate is a known incompatibility. Don't use it. + if id(candidate) in incompatible_ids: + return None + return candidate + + def iter_index_candidate_infos() -> Iterator[IndexCandidateInfo]: + result = self._finder.find_best_candidate( + project_name=name, + specifier=specifier, + hashes=hashes, + ) + icans = result.applicable_candidates + + # PEP 592: Yanked releases are ignored unless the specifier + # explicitly pins a version (via '==' or '===') that can be + # solely satisfied by a yanked release. + all_yanked = all(ican.link.is_yanked for ican in icans) + + def is_pinned(specifier: SpecifierSet) -> bool: + for sp in specifier: + if sp.operator == "===": + return True + if sp.operator != "==": + continue + if sp.version.endswith(".*"): + continue + return True + return False + + pinned = is_pinned(specifier) + + # PackageFinder returns earlier versions first, so we reverse. + for ican in reversed(icans): + if not (all_yanked and pinned) and ican.link.is_yanked: + continue + func = functools.partial( + self._make_candidate_from_link, + link=ican.link, + extras=extras, + template=template, + name=name, + version=ican.version, + ) + yield ican.version, func + + return FoundCandidates( + iter_index_candidate_infos, + _get_installed_candidate(), + prefers_installed, + incompatible_ids, + ) + + def _iter_explicit_candidates_from_base( + self, + base_requirements: Iterable[Requirement], + extras: FrozenSet[str], + ) -> Iterator[Candidate]: + """Produce explicit candidates from the base given an extra-ed package. + + :param base_requirements: Requirements known to the resolver. The + requirements are guaranteed to not have extras. + :param extras: The extras to inject into the explicit requirements' + candidates. + """ + for req in base_requirements: + lookup_cand, _ = req.get_candidate_lookup() + if lookup_cand is None: # Not explicit. + continue + # We've stripped extras from the identifier, and should always + # get a BaseCandidate here, unless there's a bug elsewhere. + base_cand = as_base_candidate(lookup_cand) + assert base_cand is not None, "no extras here" + yield self._make_extras_candidate(base_cand, extras) + + def _iter_candidates_from_constraints( + self, + identifier: str, + constraint: Constraint, + template: InstallRequirement, + ) -> Iterator[Candidate]: + """Produce explicit candidates from constraints. + + This creates "fake" InstallRequirement objects that are basically clones + of what "should" be the template, but with original_link set to link. + """ + for link in constraint.links: + self._fail_if_link_is_unsupported_wheel(link) + candidate = self._make_base_candidate_from_link( + link, + template=install_req_from_link_and_ireq(link, template), + name=canonicalize_name(identifier), + version=None, + ) + if candidate: + yield candidate + + def find_candidates( + self, + identifier: str, + requirements: Mapping[str, Iterable[Requirement]], + incompatibilities: Mapping[str, Iterator[Candidate]], + constraint: Constraint, + prefers_installed: bool, + is_satisfied_by: Callable[[Requirement, Candidate], bool], + ) -> Iterable[Candidate]: + # Collect basic lookup information from the requirements. + explicit_candidates: Set[Candidate] = set() + ireqs: List[InstallRequirement] = [] + for req in requirements[identifier]: + cand, ireq = req.get_candidate_lookup() + if cand is not None: + explicit_candidates.add(cand) + if ireq is not None: + ireqs.append(ireq) + + # If the current identifier contains extras, add requires and explicit + # candidates from entries from extra-less identifier. + with contextlib.suppress(InvalidRequirement): + parsed_requirement = get_requirement(identifier) + if parsed_requirement.name != identifier: + explicit_candidates.update( + self._iter_explicit_candidates_from_base( + requirements.get(parsed_requirement.name, ()), + frozenset(parsed_requirement.extras), + ), + ) + for req in requirements.get(parsed_requirement.name, []): + _, ireq = req.get_candidate_lookup() + if ireq is not None: + ireqs.append(ireq) + + # Add explicit candidates from constraints. We only do this if there are + # known ireqs, which represent requirements not already explicit. If + # there are no ireqs, we're constraining already-explicit requirements, + # which is handled later when we return the explicit candidates. + if ireqs: + try: + explicit_candidates.update( + self._iter_candidates_from_constraints( + identifier, + constraint, + template=ireqs[0], + ), + ) + except UnsupportedWheel: + # If we're constrained to install a wheel incompatible with the + # target architecture, no candidates will ever be valid. + return () + + # Since we cache all the candidates, incompatibility identification + # can be made quicker by comparing only the id() values. + incompat_ids = {id(c) for c in incompatibilities.get(identifier, ())} + + # If none of the requirements want an explicit candidate, we can ask + # the finder for candidates. + if not explicit_candidates: + return self._iter_found_candidates( + ireqs, + constraint.specifier, + constraint.hashes, + prefers_installed, + incompat_ids, + ) + + return ( + c + for c in explicit_candidates + if id(c) not in incompat_ids + and constraint.is_satisfied_by(c) + and all(is_satisfied_by(req, c) for req in requirements[identifier]) + ) + + def _make_requirements_from_install_req( + self, ireq: InstallRequirement, requested_extras: Iterable[str] + ) -> Iterator[Requirement]: + """ + Returns requirement objects associated with the given InstallRequirement. In + most cases this will be a single object but the following special cases exist: + - the InstallRequirement has markers that do not apply -> result is empty + - the InstallRequirement has both a constraint (or link) and extras + -> result is split in two requirement objects: one with the constraint + (or link) and one with the extra. This allows centralized constraint + handling for the base, resulting in fewer candidate rejections. + """ + if not ireq.match_markers(requested_extras): + logger.info( + "Ignoring %s: markers '%s' don't match your environment", + ireq.name, + ireq.markers, + ) + elif not ireq.link: + if ireq.extras and ireq.req is not None and ireq.req.specifier: + yield SpecifierWithoutExtrasRequirement(ireq) + yield SpecifierRequirement(ireq) + else: + self._fail_if_link_is_unsupported_wheel(ireq.link) + # Always make the link candidate for the base requirement to make it + # available to `find_candidates` for explicit candidate lookup for any + # set of extras. + # The extras are required separately via a second requirement. + cand = self._make_base_candidate_from_link( + ireq.link, + template=install_req_drop_extras(ireq) if ireq.extras else ireq, + name=canonicalize_name(ireq.name) if ireq.name else None, + version=None, + ) + if cand is None: + # There's no way we can satisfy a URL requirement if the underlying + # candidate fails to build. An unnamed URL must be user-supplied, so + # we fail eagerly. If the URL is named, an unsatisfiable requirement + # can make the resolver do the right thing, either backtrack (and + # maybe find some other requirement that's buildable) or raise a + # ResolutionImpossible eventually. + if not ireq.name: + raise self._build_failures[ireq.link] + yield UnsatisfiableRequirement(canonicalize_name(ireq.name)) + else: + # require the base from the link + yield self.make_requirement_from_candidate(cand) + if ireq.extras: + # require the extras on top of the base candidate + yield self.make_requirement_from_candidate( + self._make_extras_candidate(cand, frozenset(ireq.extras)) + ) + + def collect_root_requirements( + self, root_ireqs: List[InstallRequirement] + ) -> CollectedRootRequirements: + collected = CollectedRootRequirements([], {}, {}) + for i, ireq in enumerate(root_ireqs): + if ireq.constraint: + # Ensure we only accept valid constraints + problem = check_invalid_constraint_type(ireq) + if problem: + raise InstallationError(problem) + if not ireq.match_markers(): + continue + assert ireq.name, "Constraint must be named" + name = canonicalize_name(ireq.name) + if name in collected.constraints: + collected.constraints[name] &= ireq + else: + collected.constraints[name] = Constraint.from_ireq(ireq) + else: + reqs = list( + self._make_requirements_from_install_req( + ireq, + requested_extras=(), + ) + ) + if not reqs: + continue + template = reqs[0] + if ireq.user_supplied and template.name not in collected.user_requested: + collected.user_requested[template.name] = i + collected.requirements.extend(reqs) + # Put requirements with extras at the end of the root requires. This does not + # affect resolvelib's picking preference but it does affect its initial criteria + # population: by putting extras at the end we enable the candidate finder to + # present resolvelib with a smaller set of candidates to resolvelib, already + # taking into account any non-transient constraints on the associated base. This + # means resolvelib will have fewer candidates to visit and reject. + # Python's list sort is stable, meaning relative order is kept for objects with + # the same key. + collected.requirements.sort(key=lambda r: r.name != r.project_name) + return collected + + def make_requirement_from_candidate( + self, candidate: Candidate + ) -> ExplicitRequirement: + return ExplicitRequirement(candidate) + + def make_requirements_from_spec( + self, + specifier: str, + comes_from: Optional[InstallRequirement], + requested_extras: Iterable[str] = (), + ) -> Iterator[Requirement]: + """ + Returns requirement objects associated with the given specifier. In most cases + this will be a single object but the following special cases exist: + - the specifier has markers that do not apply -> result is empty + - the specifier has both a constraint and extras -> result is split + in two requirement objects: one with the constraint and one with the + extra. This allows centralized constraint handling for the base, + resulting in fewer candidate rejections. + """ + ireq = self._make_install_req_from_spec(specifier, comes_from) + return self._make_requirements_from_install_req(ireq, requested_extras) + + def make_requires_python_requirement( + self, + specifier: SpecifierSet, + ) -> Optional[Requirement]: + if self._ignore_requires_python: + return None + # Don't bother creating a dependency for an empty Requires-Python. + if not str(specifier): + return None + return RequiresPythonRequirement(specifier, self._python_candidate) + + def get_wheel_cache_entry( + self, link: Link, name: Optional[str] + ) -> Optional[CacheEntry]: + """Look up the link in the wheel cache. + + If ``preparer.require_hashes`` is True, don't use the wheel cache, + because cached wheels, always built locally, have different hashes + than the files downloaded from the index server and thus throw false + hash mismatches. Furthermore, cached wheels at present have + nondeterministic contents due to file modification times. + """ + if self._wheel_cache is None: + return None + return self._wheel_cache.get_cache_entry( + link=link, + package_name=name, + supported_tags=self._supported_tags_cache, + ) + + def get_dist_to_uninstall(self, candidate: Candidate) -> Optional[BaseDistribution]: + # TODO: Are there more cases this needs to return True? Editable? + dist = self._installed_dists.get(candidate.project_name) + if dist is None: # Not installed, no uninstallation required. + return None + + # We're installing into global site. The current installation must + # be uninstalled, no matter it's in global or user site, because the + # user site installation has precedence over global. + if not self._use_user_site: + return dist + + # We're installing into user site. Remove the user site installation. + if dist.in_usersite: + return dist + + # We're installing into user site, but the installed incompatible + # package is in global site. We can't uninstall that, and would let + # the new user installation to "shadow" it. But shadowing won't work + # in virtual environments, so we error out. + if running_under_virtualenv() and dist.in_site_packages: + message = ( + f"Will not install to the user site because it will lack " + f"sys.path precedence to {dist.raw_name} in {dist.location}" + ) + raise InstallationError(message) + return None + + def _report_requires_python_error( + self, causes: Sequence["ConflictCause"] + ) -> UnsupportedPythonVersion: + assert causes, "Requires-Python error reported with no cause" + + version = self._python_candidate.version + + if len(causes) == 1: + specifier = str(causes[0].requirement.specifier) + message = ( + f"Package {causes[0].parent.name!r} requires a different " + f"Python: {version} not in {specifier!r}" + ) + return UnsupportedPythonVersion(message) + + message = f"Packages require a different Python. {version} not in:" + for cause in causes: + package = cause.parent.format_for_error() + specifier = str(cause.requirement.specifier) + message += f"\n{specifier!r} (required by {package})" + return UnsupportedPythonVersion(message) + + def _report_single_requirement_conflict( + self, req: Requirement, parent: Optional[Candidate] + ) -> DistributionNotFound: + if parent is None: + req_disp = str(req) + else: + req_disp = f"{req} (from {parent.name})" + + cands = self._finder.find_all_candidates(req.project_name) + skipped_by_requires_python = self._finder.requires_python_skipped_reasons() + + versions_set: Set[Version] = set() + yanked_versions_set: Set[Version] = set() + for c in cands: + is_yanked = c.link.is_yanked if c.link else False + if is_yanked: + yanked_versions_set.add(c.version) + else: + versions_set.add(c.version) + + versions = [str(v) for v in sorted(versions_set)] + yanked_versions = [str(v) for v in sorted(yanked_versions_set)] + + if yanked_versions: + # Saying "version X is yanked" isn't entirely accurate. + # https://github.com/pypa/pip/issues/11745#issuecomment-1402805842 + logger.critical( + "Ignored the following yanked versions: %s", + ", ".join(yanked_versions) or "none", + ) + if skipped_by_requires_python: + logger.critical( + "Ignored the following versions that require a different python " + "version: %s", + "; ".join(skipped_by_requires_python) or "none", + ) + logger.critical( + "Could not find a version that satisfies the requirement %s " + "(from versions: %s)", + req_disp, + ", ".join(versions) or "none", + ) + if str(req) == "requirements.txt": + logger.info( + "HINT: You are attempting to install a package literally " + 'named "requirements.txt" (which cannot exist). Consider ' + "using the '-r' flag to install the packages listed in " + "requirements.txt" + ) + + return DistributionNotFound(f"No matching distribution found for {req}") + + def get_installation_error( + self, + e: "ResolutionImpossible[Requirement, Candidate]", + constraints: Dict[str, Constraint], + ) -> InstallationError: + assert e.causes, "Installation error reported with no cause" + + # If one of the things we can't solve is "we need Python X.Y", + # that is what we report. + requires_python_causes = [ + cause + for cause in e.causes + if isinstance(cause.requirement, RequiresPythonRequirement) + and not cause.requirement.is_satisfied_by(self._python_candidate) + ] + if requires_python_causes: + # The comprehension above makes sure all Requirement instances are + # RequiresPythonRequirement, so let's cast for convenience. + return self._report_requires_python_error( + cast("Sequence[ConflictCause]", requires_python_causes), + ) + + # Otherwise, we have a set of causes which can't all be satisfied + # at once. + + # The simplest case is when we have *one* cause that can't be + # satisfied. We just report that case. + if len(e.causes) == 1: + req, parent = e.causes[0] + if req.name not in constraints: + return self._report_single_requirement_conflict(req, parent) + + # OK, we now have a list of requirements that can't all be + # satisfied at once. + + # A couple of formatting helpers + def text_join(parts: List[str]) -> str: + if len(parts) == 1: + return parts[0] + + return ", ".join(parts[:-1]) + " and " + parts[-1] + + def describe_trigger(parent: Candidate) -> str: + ireq = parent.get_install_requirement() + if not ireq or not ireq.comes_from: + return f"{parent.name}=={parent.version}" + if isinstance(ireq.comes_from, InstallRequirement): + return str(ireq.comes_from.name) + return str(ireq.comes_from) + + triggers = set() + for req, parent in e.causes: + if parent is None: + # This is a root requirement, so we can report it directly + trigger = req.format_for_error() + else: + trigger = describe_trigger(parent) + triggers.add(trigger) + + if triggers: + info = text_join(sorted(triggers)) + else: + info = "the requested packages" + + msg = ( + f"Cannot install {info} because these package versions " + "have conflicting dependencies." + ) + logger.critical(msg) + msg = "\nThe conflict is caused by:" + + relevant_constraints = set() + for req, parent in e.causes: + if req.name in constraints: + relevant_constraints.add(req.name) + msg = msg + "\n " + if parent: + msg = msg + f"{parent.name} {parent.version} depends on " + else: + msg = msg + "The user requested " + msg = msg + req.format_for_error() + for key in relevant_constraints: + spec = constraints[key].specifier + msg += f"\n The user requested (constraint) {key}{spec}" + + msg = ( + msg + + "\n\n" + + "To fix this you could try to:\n" + + "1. loosen the range of package versions you've specified\n" + + "2. remove package versions to allow pip to attempt to solve " + + "the dependency conflict\n" + ) + + logger.info(msg) + + return DistributionNotFound( + "ResolutionImpossible: for help visit " + "https://pip.pypa.io/en/latest/topics/dependency-resolution/" + "#dealing-with-dependency-conflicts" + ) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py new file mode 100644 index 0000000000000000000000000000000000000000..a1d57e0f4b275cd5783c950381ddfff0184da138 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py @@ -0,0 +1,174 @@ +"""Utilities to lazily create and visit candidates found. + +Creating and visiting a candidate is a *very* costly operation. It involves +fetching, extracting, potentially building modules from source, and verifying +distribution metadata. It is therefore crucial for performance to keep +everything here lazy all the way down, so we only touch candidates that we +absolutely need, and not "download the world" when we only need one version of +something. +""" + +import functools +import logging +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, Set, Tuple + +from pip._vendor.packaging.version import _BaseVersion + +from pip._internal.exceptions import MetadataInvalid + +from .base import Candidate + +logger = logging.getLogger(__name__) + +IndexCandidateInfo = Tuple[_BaseVersion, Callable[[], Optional[Candidate]]] + +if TYPE_CHECKING: + SequenceCandidate = Sequence[Candidate] +else: + # For compatibility: Python before 3.9 does not support using [] on the + # Sequence class. + # + # >>> from collections.abc import Sequence + # >>> Sequence[str] + # Traceback (most recent call last): + # File "", line 1, in + # TypeError: 'ABCMeta' object is not subscriptable + # + # TODO: Remove this block after dropping Python 3.8 support. + SequenceCandidate = Sequence + + +def _iter_built(infos: Iterator[IndexCandidateInfo]) -> Iterator[Candidate]: + """Iterator for ``FoundCandidates``. + + This iterator is used when the package is not already installed. Candidates + from index come later in their normal ordering. + """ + versions_found: Set[_BaseVersion] = set() + for version, func in infos: + if version in versions_found: + continue + try: + candidate = func() + except MetadataInvalid as e: + logger.warning( + "Ignoring version %s of %s since it has invalid metadata:\n" + "%s\n" + "Please use pip<24.1 if you need to use this version.", + version, + e.ireq.name, + e, + ) + # Mark version as found to avoid trying other candidates with the same + # version, since they most likely have invalid metadata as well. + versions_found.add(version) + else: + if candidate is None: + continue + yield candidate + versions_found.add(version) + + +def _iter_built_with_prepended( + installed: Candidate, infos: Iterator[IndexCandidateInfo] +) -> Iterator[Candidate]: + """Iterator for ``FoundCandidates``. + + This iterator is used when the resolver prefers the already-installed + candidate and NOT to upgrade. The installed candidate is therefore + always yielded first, and candidates from index come later in their + normal ordering, except skipped when the version is already installed. + """ + yield installed + versions_found: Set[_BaseVersion] = {installed.version} + for version, func in infos: + if version in versions_found: + continue + candidate = func() + if candidate is None: + continue + yield candidate + versions_found.add(version) + + +def _iter_built_with_inserted( + installed: Candidate, infos: Iterator[IndexCandidateInfo] +) -> Iterator[Candidate]: + """Iterator for ``FoundCandidates``. + + This iterator is used when the resolver prefers to upgrade an + already-installed package. Candidates from index are returned in their + normal ordering, except replaced when the version is already installed. + + The implementation iterates through and yields other candidates, inserting + the installed candidate exactly once before we start yielding older or + equivalent candidates, or after all other candidates if they are all newer. + """ + versions_found: Set[_BaseVersion] = set() + for version, func in infos: + if version in versions_found: + continue + # If the installed candidate is better, yield it first. + if installed.version >= version: + yield installed + versions_found.add(installed.version) + candidate = func() + if candidate is None: + continue + yield candidate + versions_found.add(version) + + # If the installed candidate is older than all other candidates. + if installed.version not in versions_found: + yield installed + + +class FoundCandidates(SequenceCandidate): + """A lazy sequence to provide candidates to the resolver. + + The intended usage is to return this from `find_matches()` so the resolver + can iterate through the sequence multiple times, but only access the index + page when remote packages are actually needed. This improve performances + when suitable candidates are already installed on disk. + """ + + def __init__( + self, + get_infos: Callable[[], Iterator[IndexCandidateInfo]], + installed: Optional[Candidate], + prefers_installed: bool, + incompatible_ids: Set[int], + ): + self._get_infos = get_infos + self._installed = installed + self._prefers_installed = prefers_installed + self._incompatible_ids = incompatible_ids + + def __getitem__(self, index: Any) -> Any: + # Implemented to satisfy the ABC check. This is not needed by the + # resolver, and should not be used by the provider either (for + # performance reasons). + raise NotImplementedError("don't do this") + + def __iter__(self) -> Iterator[Candidate]: + infos = self._get_infos() + if not self._installed: + iterator = _iter_built(infos) + elif self._prefers_installed: + iterator = _iter_built_with_prepended(self._installed, infos) + else: + iterator = _iter_built_with_inserted(self._installed, infos) + return (c for c in iterator if id(c) not in self._incompatible_ids) + + def __len__(self) -> int: + # Implemented to satisfy the ABC check. This is not needed by the + # resolver, and should not be used by the provider either (for + # performance reasons). + raise NotImplementedError("don't do this") + + @functools.lru_cache(maxsize=1) + def __bool__(self) -> bool: + if self._prefers_installed and self._installed: + return True + return any(self) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/provider.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/provider.py new file mode 100644 index 0000000000000000000000000000000000000000..fb0dd85f1124bed20da9402ada714af3f3584e07 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/provider.py @@ -0,0 +1,258 @@ +import collections +import math +from functools import lru_cache +from typing import ( + TYPE_CHECKING, + Dict, + Iterable, + Iterator, + Mapping, + Sequence, + TypeVar, + Union, +) + +from pip._vendor.resolvelib.providers import AbstractProvider + +from .base import Candidate, Constraint, Requirement +from .candidates import REQUIRES_PYTHON_IDENTIFIER +from .factory import Factory + +if TYPE_CHECKING: + from pip._vendor.resolvelib.providers import Preference + from pip._vendor.resolvelib.resolvers import RequirementInformation + + PreferenceInformation = RequirementInformation[Requirement, Candidate] + + _ProviderBase = AbstractProvider[Requirement, Candidate, str] +else: + _ProviderBase = AbstractProvider + +# Notes on the relationship between the provider, the factory, and the +# candidate and requirement classes. +# +# The provider is a direct implementation of the resolvelib class. Its role +# is to deliver the API that resolvelib expects. +# +# Rather than work with completely abstract "requirement" and "candidate" +# concepts as resolvelib does, pip has concrete classes implementing these two +# ideas. The API of Requirement and Candidate objects are defined in the base +# classes, but essentially map fairly directly to the equivalent provider +# methods. In particular, `find_matches` and `is_satisfied_by` are +# requirement methods, and `get_dependencies` is a candidate method. +# +# The factory is the interface to pip's internal mechanisms. It is stateless, +# and is created by the resolver and held as a property of the provider. It is +# responsible for creating Requirement and Candidate objects, and provides +# services to those objects (access to pip's finder and preparer). + + +D = TypeVar("D") +V = TypeVar("V") + + +def _get_with_identifier( + mapping: Mapping[str, V], + identifier: str, + default: D, +) -> Union[D, V]: + """Get item from a package name lookup mapping with a resolver identifier. + + This extra logic is needed when the target mapping is keyed by package + name, which cannot be directly looked up with an identifier (which may + contain requested extras). Additional logic is added to also look up a value + by "cleaning up" the extras from the identifier. + """ + if identifier in mapping: + return mapping[identifier] + # HACK: Theoretically we should check whether this identifier is a valid + # "NAME[EXTRAS]" format, and parse out the name part with packaging or + # some regular expression. But since pip's resolver only spits out three + # kinds of identifiers: normalized PEP 503 names, normalized names plus + # extras, and Requires-Python, we can cheat a bit here. + name, open_bracket, _ = identifier.partition("[") + if open_bracket and name in mapping: + return mapping[name] + return default + + +class PipProvider(_ProviderBase): + """Pip's provider implementation for resolvelib. + + :params constraints: A mapping of constraints specified by the user. Keys + are canonicalized project names. + :params ignore_dependencies: Whether the user specified ``--no-deps``. + :params upgrade_strategy: The user-specified upgrade strategy. + :params user_requested: A set of canonicalized package names that the user + supplied for pip to install/upgrade. + """ + + def __init__( + self, + factory: Factory, + constraints: Dict[str, Constraint], + ignore_dependencies: bool, + upgrade_strategy: str, + user_requested: Dict[str, int], + ) -> None: + self._factory = factory + self._constraints = constraints + self._ignore_dependencies = ignore_dependencies + self._upgrade_strategy = upgrade_strategy + self._user_requested = user_requested + self._known_depths: Dict[str, float] = collections.defaultdict(lambda: math.inf) + + def identify(self, requirement_or_candidate: Union[Requirement, Candidate]) -> str: + return requirement_or_candidate.name + + def get_preference( + self, + identifier: str, + resolutions: Mapping[str, Candidate], + candidates: Mapping[str, Iterator[Candidate]], + information: Mapping[str, Iterable["PreferenceInformation"]], + backtrack_causes: Sequence["PreferenceInformation"], + ) -> "Preference": + """Produce a sort key for given requirement based on preference. + + The lower the return value is, the more preferred this group of + arguments is. + + Currently pip considers the following in order: + + * Prefer if any of the known requirements is "direct", e.g. points to an + explicit URL. + * If equal, prefer if any requirement is "pinned", i.e. contains + operator ``===`` or ``==``. + * If equal, calculate an approximate "depth" and resolve requirements + closer to the user-specified requirements first. If the depth cannot + by determined (eg: due to no matching parents), it is considered + infinite. + * Order user-specified requirements by the order they are specified. + * If equal, prefers "non-free" requirements, i.e. contains at least one + operator, such as ``>=`` or ``<``. + * If equal, order alphabetically for consistency (helps debuggability). + """ + try: + next(iter(information[identifier])) + except StopIteration: + # There is no information for this identifier, so there's no known + # candidates. + has_information = False + else: + has_information = True + + if has_information: + lookups = (r.get_candidate_lookup() for r, _ in information[identifier]) + candidate, ireqs = zip(*lookups) + else: + candidate, ireqs = None, () + + operators = [ + specifier.operator + for specifier_set in (ireq.specifier for ireq in ireqs if ireq) + for specifier in specifier_set + ] + + direct = candidate is not None + pinned = any(op[:2] == "==" for op in operators) + unfree = bool(operators) + + try: + requested_order: Union[int, float] = self._user_requested[identifier] + except KeyError: + requested_order = math.inf + if has_information: + parent_depths = ( + self._known_depths[parent.name] if parent is not None else 0.0 + for _, parent in information[identifier] + ) + inferred_depth = min(d for d in parent_depths) + 1.0 + else: + inferred_depth = math.inf + else: + inferred_depth = 1.0 + self._known_depths[identifier] = inferred_depth + + requested_order = self._user_requested.get(identifier, math.inf) + + # Requires-Python has only one candidate and the check is basically + # free, so we always do it first to avoid needless work if it fails. + requires_python = identifier == REQUIRES_PYTHON_IDENTIFIER + + # Prefer the causes of backtracking on the assumption that the problem + # resolving the dependency tree is related to the failures that caused + # the backtracking + backtrack_cause = self.is_backtrack_cause(identifier, backtrack_causes) + + return ( + not requires_python, + not direct, + not pinned, + not backtrack_cause, + inferred_depth, + requested_order, + not unfree, + identifier, + ) + + def find_matches( + self, + identifier: str, + requirements: Mapping[str, Iterator[Requirement]], + incompatibilities: Mapping[str, Iterator[Candidate]], + ) -> Iterable[Candidate]: + def _eligible_for_upgrade(identifier: str) -> bool: + """Are upgrades allowed for this project? + + This checks the upgrade strategy, and whether the project was one + that the user specified in the command line, in order to decide + whether we should upgrade if there's a newer version available. + + (Note that we don't need access to the `--upgrade` flag, because + an upgrade strategy of "to-satisfy-only" means that `--upgrade` + was not specified). + """ + if self._upgrade_strategy == "eager": + return True + elif self._upgrade_strategy == "only-if-needed": + user_order = _get_with_identifier( + self._user_requested, + identifier, + default=None, + ) + return user_order is not None + return False + + constraint = _get_with_identifier( + self._constraints, + identifier, + default=Constraint.empty(), + ) + return self._factory.find_candidates( + identifier=identifier, + requirements=requirements, + constraint=constraint, + prefers_installed=(not _eligible_for_upgrade(identifier)), + incompatibilities=incompatibilities, + is_satisfied_by=self.is_satisfied_by, + ) + + @lru_cache(maxsize=None) + def is_satisfied_by(self, requirement: Requirement, candidate: Candidate) -> bool: + return requirement.is_satisfied_by(candidate) + + def get_dependencies(self, candidate: Candidate) -> Sequence[Requirement]: + with_requires = not self._ignore_dependencies + return [r for r in candidate.iter_dependencies(with_requires) if r is not None] + + @staticmethod + def is_backtrack_cause( + identifier: str, backtrack_causes: Sequence["PreferenceInformation"] + ) -> bool: + for backtrack_cause in backtrack_causes: + if identifier == backtrack_cause.requirement.name: + return True + if backtrack_cause.parent and identifier == backtrack_cause.parent.name: + return True + return False diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/reporter.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/reporter.py new file mode 100644 index 0000000000000000000000000000000000000000..0594569d85010d23cc03b178c56cb472908ed59c --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/reporter.py @@ -0,0 +1,81 @@ +from collections import defaultdict +from logging import getLogger +from typing import Any, DefaultDict + +from pip._vendor.resolvelib.reporters import BaseReporter + +from .base import Candidate, Requirement + +logger = getLogger(__name__) + + +class PipReporter(BaseReporter): + def __init__(self) -> None: + self.reject_count_by_package: DefaultDict[str, int] = defaultdict(int) + + self._messages_at_reject_count = { + 1: ( + "pip is looking at multiple versions of {package_name} to " + "determine which version is compatible with other " + "requirements. This could take a while." + ), + 8: ( + "pip is still looking at multiple versions of {package_name} to " + "determine which version is compatible with other " + "requirements. This could take a while." + ), + 13: ( + "This is taking longer than usual. You might need to provide " + "the dependency resolver with stricter constraints to reduce " + "runtime. See https://pip.pypa.io/warnings/backtracking for " + "guidance. If you want to abort this run, press Ctrl + C." + ), + } + + def rejecting_candidate(self, criterion: Any, candidate: Candidate) -> None: + self.reject_count_by_package[candidate.name] += 1 + + count = self.reject_count_by_package[candidate.name] + if count not in self._messages_at_reject_count: + return + + message = self._messages_at_reject_count[count] + logger.info("INFO: %s", message.format(package_name=candidate.name)) + + msg = "Will try a different candidate, due to conflict:" + for req_info in criterion.information: + req, parent = req_info.requirement, req_info.parent + # Inspired by Factory.get_installation_error + msg += "\n " + if parent: + msg += f"{parent.name} {parent.version} depends on " + else: + msg += "The user requested " + msg += req.format_for_error() + logger.debug(msg) + + +class PipDebuggingReporter(BaseReporter): + """A reporter that does an info log for every event it sees.""" + + def starting(self) -> None: + logger.info("Reporter.starting()") + + def starting_round(self, index: int) -> None: + logger.info("Reporter.starting_round(%r)", index) + + def ending_round(self, index: int, state: Any) -> None: + logger.info("Reporter.ending_round(%r, state)", index) + logger.debug("Reporter.ending_round(%r, %r)", index, state) + + def ending(self, state: Any) -> None: + logger.info("Reporter.ending(%r)", state) + + def adding_requirement(self, requirement: Requirement, parent: Candidate) -> None: + logger.info("Reporter.adding_requirement(%r, %r)", requirement, parent) + + def rejecting_candidate(self, criterion: Any, candidate: Candidate) -> None: + logger.info("Reporter.rejecting_candidate(%r, %r)", criterion, candidate) + + def pinning(self, candidate: Candidate) -> None: + logger.info("Reporter.pinning(%r)", candidate) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..b04f41b2191840865307be5dd9cec4271f19bcd2 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/requirements.py @@ -0,0 +1,245 @@ +from typing import Any, Optional + +from pip._vendor.packaging.specifiers import SpecifierSet +from pip._vendor.packaging.utils import NormalizedName, canonicalize_name + +from pip._internal.req.constructors import install_req_drop_extras +from pip._internal.req.req_install import InstallRequirement + +from .base import Candidate, CandidateLookup, Requirement, format_name + + +class ExplicitRequirement(Requirement): + def __init__(self, candidate: Candidate) -> None: + self.candidate = candidate + + def __str__(self) -> str: + return str(self.candidate) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.candidate!r})" + + def __hash__(self) -> int: + return hash(self.candidate) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ExplicitRequirement): + return False + return self.candidate == other.candidate + + @property + def project_name(self) -> NormalizedName: + # No need to canonicalize - the candidate did this + return self.candidate.project_name + + @property + def name(self) -> str: + # No need to canonicalize - the candidate did this + return self.candidate.name + + def format_for_error(self) -> str: + return self.candidate.format_for_error() + + def get_candidate_lookup(self) -> CandidateLookup: + return self.candidate, None + + def is_satisfied_by(self, candidate: Candidate) -> bool: + return candidate == self.candidate + + +class SpecifierRequirement(Requirement): + def __init__(self, ireq: InstallRequirement) -> None: + assert ireq.link is None, "This is a link, not a specifier" + self._ireq = ireq + self._equal_cache: Optional[str] = None + self._hash: Optional[int] = None + self._extras = frozenset(canonicalize_name(e) for e in self._ireq.extras) + + @property + def _equal(self) -> str: + if self._equal_cache is not None: + return self._equal_cache + + self._equal_cache = str(self._ireq) + return self._equal_cache + + def __str__(self) -> str: + return str(self._ireq.req) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({str(self._ireq.req)!r})" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SpecifierRequirement): + return NotImplemented + return self._equal == other._equal + + def __hash__(self) -> int: + if self._hash is not None: + return self._hash + + self._hash = hash(self._equal) + return self._hash + + @property + def project_name(self) -> NormalizedName: + assert self._ireq.req, "Specifier-backed ireq is always PEP 508" + return canonicalize_name(self._ireq.req.name) + + @property + def name(self) -> str: + return format_name(self.project_name, self._extras) + + def format_for_error(self) -> str: + # Convert comma-separated specifiers into "A, B, ..., F and G" + # This makes the specifier a bit more "human readable", without + # risking a change in meaning. (Hopefully! Not all edge cases have + # been checked) + parts = [s.strip() for s in str(self).split(",")] + if len(parts) == 0: + return "" + elif len(parts) == 1: + return parts[0] + + return ", ".join(parts[:-1]) + " and " + parts[-1] + + def get_candidate_lookup(self) -> CandidateLookup: + return None, self._ireq + + def is_satisfied_by(self, candidate: Candidate) -> bool: + assert candidate.name == self.name, ( + f"Internal issue: Candidate is not for this requirement " + f"{candidate.name} vs {self.name}" + ) + # We can safely always allow prereleases here since PackageFinder + # already implements the prerelease logic, and would have filtered out + # prerelease candidates if the user does not expect them. + assert self._ireq.req, "Specifier-backed ireq is always PEP 508" + spec = self._ireq.req.specifier + return spec.contains(candidate.version, prereleases=True) + + +class SpecifierWithoutExtrasRequirement(SpecifierRequirement): + """ + Requirement backed by an install requirement on a base package. + Trims extras from its install requirement if there are any. + """ + + def __init__(self, ireq: InstallRequirement) -> None: + assert ireq.link is None, "This is a link, not a specifier" + self._ireq = install_req_drop_extras(ireq) + self._equal_cache: Optional[str] = None + self._hash: Optional[int] = None + self._extras = frozenset(canonicalize_name(e) for e in self._ireq.extras) + + @property + def _equal(self) -> str: + if self._equal_cache is not None: + return self._equal_cache + + self._equal_cache = str(self._ireq) + return self._equal_cache + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SpecifierWithoutExtrasRequirement): + return NotImplemented + return self._equal == other._equal + + def __hash__(self) -> int: + if self._hash is not None: + return self._hash + + self._hash = hash(self._equal) + return self._hash + + +class RequiresPythonRequirement(Requirement): + """A requirement representing Requires-Python metadata.""" + + def __init__(self, specifier: SpecifierSet, match: Candidate) -> None: + self.specifier = specifier + self._specifier_string = str(specifier) # for faster __eq__ + self._hash: Optional[int] = None + self._candidate = match + + def __str__(self) -> str: + return f"Python {self.specifier}" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({str(self.specifier)!r})" + + def __hash__(self) -> int: + if self._hash is not None: + return self._hash + + self._hash = hash((self._specifier_string, self._candidate)) + return self._hash + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RequiresPythonRequirement): + return False + return ( + self._specifier_string == other._specifier_string + and self._candidate == other._candidate + ) + + @property + def project_name(self) -> NormalizedName: + return self._candidate.project_name + + @property + def name(self) -> str: + return self._candidate.name + + def format_for_error(self) -> str: + return str(self) + + def get_candidate_lookup(self) -> CandidateLookup: + if self.specifier.contains(self._candidate.version, prereleases=True): + return self._candidate, None + return None, None + + def is_satisfied_by(self, candidate: Candidate) -> bool: + assert candidate.name == self._candidate.name, "Not Python candidate" + # We can safely always allow prereleases here since PackageFinder + # already implements the prerelease logic, and would have filtered out + # prerelease candidates if the user does not expect them. + return self.specifier.contains(candidate.version, prereleases=True) + + +class UnsatisfiableRequirement(Requirement): + """A requirement that cannot be satisfied.""" + + def __init__(self, name: NormalizedName) -> None: + self._name = name + + def __str__(self) -> str: + return f"{self._name} (unavailable)" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({str(self._name)!r})" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UnsatisfiableRequirement): + return NotImplemented + return self._name == other._name + + def __hash__(self) -> int: + return hash(self._name) + + @property + def project_name(self) -> NormalizedName: + return self._name + + @property + def name(self) -> str: + return self._name + + def format_for_error(self) -> str: + return str(self) + + def get_candidate_lookup(self) -> CandidateLookup: + return None, None + + def is_satisfied_by(self, candidate: Candidate) -> bool: + return False diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/resolver.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..c12beef0b2a4344a4e0daca2540bbfd0c58ce777 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/resolution/resolvelib/resolver.py @@ -0,0 +1,317 @@ +import contextlib +import functools +import logging +import os +from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, cast + +from pip._vendor.packaging.utils import canonicalize_name +from pip._vendor.resolvelib import BaseReporter, ResolutionImpossible +from pip._vendor.resolvelib import Resolver as RLResolver +from pip._vendor.resolvelib.structs import DirectedGraph + +from pip._internal.cache import WheelCache +from pip._internal.index.package_finder import PackageFinder +from pip._internal.operations.prepare import RequirementPreparer +from pip._internal.req.constructors import install_req_extend_extras +from pip._internal.req.req_install import InstallRequirement +from pip._internal.req.req_set import RequirementSet +from pip._internal.resolution.base import BaseResolver, InstallRequirementProvider +from pip._internal.resolution.resolvelib.provider import PipProvider +from pip._internal.resolution.resolvelib.reporter import ( + PipDebuggingReporter, + PipReporter, +) +from pip._internal.utils.packaging import get_requirement + +from .base import Candidate, Requirement +from .factory import Factory + +if TYPE_CHECKING: + from pip._vendor.resolvelib.resolvers import Result as RLResult + + Result = RLResult[Requirement, Candidate, str] + + +logger = logging.getLogger(__name__) + + +class Resolver(BaseResolver): + _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"} + + def __init__( + self, + preparer: RequirementPreparer, + finder: PackageFinder, + wheel_cache: Optional[WheelCache], + make_install_req: InstallRequirementProvider, + use_user_site: bool, + ignore_dependencies: bool, + ignore_installed: bool, + ignore_requires_python: bool, + force_reinstall: bool, + upgrade_strategy: str, + py_version_info: Optional[Tuple[int, ...]] = None, + ): + super().__init__() + assert upgrade_strategy in self._allowed_strategies + + self.factory = Factory( + finder=finder, + preparer=preparer, + make_install_req=make_install_req, + wheel_cache=wheel_cache, + use_user_site=use_user_site, + force_reinstall=force_reinstall, + ignore_installed=ignore_installed, + ignore_requires_python=ignore_requires_python, + py_version_info=py_version_info, + ) + self.ignore_dependencies = ignore_dependencies + self.upgrade_strategy = upgrade_strategy + self._result: Optional[Result] = None + + def resolve( + self, root_reqs: List[InstallRequirement], check_supported_wheels: bool + ) -> RequirementSet: + collected = self.factory.collect_root_requirements(root_reqs) + provider = PipProvider( + factory=self.factory, + constraints=collected.constraints, + ignore_dependencies=self.ignore_dependencies, + upgrade_strategy=self.upgrade_strategy, + user_requested=collected.user_requested, + ) + if "PIP_RESOLVER_DEBUG" in os.environ: + reporter: BaseReporter = PipDebuggingReporter() + else: + reporter = PipReporter() + resolver: RLResolver[Requirement, Candidate, str] = RLResolver( + provider, + reporter, + ) + + try: + limit_how_complex_resolution_can_be = 200000 + result = self._result = resolver.resolve( + collected.requirements, max_rounds=limit_how_complex_resolution_can_be + ) + + except ResolutionImpossible as e: + error = self.factory.get_installation_error( + cast("ResolutionImpossible[Requirement, Candidate]", e), + collected.constraints, + ) + raise error from e + + req_set = RequirementSet(check_supported_wheels=check_supported_wheels) + # process candidates with extras last to ensure their base equivalent is + # already in the req_set if appropriate. + # Python's sort is stable so using a binary key function keeps relative order + # within both subsets. + for candidate in sorted( + result.mapping.values(), key=lambda c: c.name != c.project_name + ): + ireq = candidate.get_install_requirement() + if ireq is None: + if candidate.name != candidate.project_name: + # extend existing req's extras + with contextlib.suppress(KeyError): + req = req_set.get_requirement(candidate.project_name) + req_set.add_named_requirement( + install_req_extend_extras( + req, get_requirement(candidate.name).extras + ) + ) + continue + + # Check if there is already an installation under the same name, + # and set a flag for later stages to uninstall it, if needed. + installed_dist = self.factory.get_dist_to_uninstall(candidate) + if installed_dist is None: + # There is no existing installation -- nothing to uninstall. + ireq.should_reinstall = False + elif self.factory.force_reinstall: + # The --force-reinstall flag is set -- reinstall. + ireq.should_reinstall = True + elif installed_dist.version != candidate.version: + # The installation is different in version -- reinstall. + ireq.should_reinstall = True + elif candidate.is_editable or installed_dist.editable: + # The incoming distribution is editable, or different in + # editable-ness to installation -- reinstall. + ireq.should_reinstall = True + elif candidate.source_link and candidate.source_link.is_file: + # The incoming distribution is under file:// + if candidate.source_link.is_wheel: + # is a local wheel -- do nothing. + logger.info( + "%s is already installed with the same version as the " + "provided wheel. Use --force-reinstall to force an " + "installation of the wheel.", + ireq.name, + ) + continue + + # is a local sdist or path -- reinstall + ireq.should_reinstall = True + else: + continue + + link = candidate.source_link + if link and link.is_yanked: + # The reason can contain non-ASCII characters, Unicode + # is required for Python 2. + msg = ( + "The candidate selected for download or install is a " + "yanked version: {name!r} candidate (version {version} " + "at {link})\nReason for being yanked: {reason}" + ).format( + name=candidate.name, + version=candidate.version, + link=link, + reason=link.yanked_reason or "", + ) + logger.warning(msg) + + req_set.add_named_requirement(ireq) + + reqs = req_set.all_requirements + self.factory.preparer.prepare_linked_requirements_more(reqs) + for req in reqs: + req.prepared = True + req.needs_more_preparation = False + return req_set + + def get_installation_order( + self, req_set: RequirementSet + ) -> List[InstallRequirement]: + """Get order for installation of requirements in RequirementSet. + + The returned list contains a requirement before another that depends on + it. This helps ensure that the environment is kept consistent as they + get installed one-by-one. + + The current implementation creates a topological ordering of the + dependency graph, giving more weight to packages with less + or no dependencies, while breaking any cycles in the graph at + arbitrary points. We make no guarantees about where the cycle + would be broken, other than it *would* be broken. + """ + assert self._result is not None, "must call resolve() first" + + if not req_set.requirements: + # Nothing is left to install, so we do not need an order. + return [] + + graph = self._result.graph + weights = get_topological_weights(graph, set(req_set.requirements.keys())) + + sorted_items = sorted( + req_set.requirements.items(), + key=functools.partial(_req_set_item_sorter, weights=weights), + reverse=True, + ) + return [ireq for _, ireq in sorted_items] + + +def get_topological_weights( + graph: "DirectedGraph[Optional[str]]", requirement_keys: Set[str] +) -> Dict[Optional[str], int]: + """Assign weights to each node based on how "deep" they are. + + This implementation may change at any point in the future without prior + notice. + + We first simplify the dependency graph by pruning any leaves and giving them + the highest weight: a package without any dependencies should be installed + first. This is done again and again in the same way, giving ever less weight + to the newly found leaves. The loop stops when no leaves are left: all + remaining packages have at least one dependency left in the graph. + + Then we continue with the remaining graph, by taking the length for the + longest path to any node from root, ignoring any paths that contain a single + node twice (i.e. cycles). This is done through a depth-first search through + the graph, while keeping track of the path to the node. + + Cycles in the graph result would result in node being revisited while also + being on its own path. In this case, take no action. This helps ensure we + don't get stuck in a cycle. + + When assigning weight, the longer path (i.e. larger length) is preferred. + + We are only interested in the weights of packages that are in the + requirement_keys. + """ + path: Set[Optional[str]] = set() + weights: Dict[Optional[str], int] = {} + + def visit(node: Optional[str]) -> None: + if node in path: + # We hit a cycle, so we'll break it here. + return + + # Time to visit the children! + path.add(node) + for child in graph.iter_children(node): + visit(child) + path.remove(node) + + if node not in requirement_keys: + return + + last_known_parent_count = weights.get(node, 0) + weights[node] = max(last_known_parent_count, len(path)) + + # Simplify the graph, pruning leaves that have no dependencies. + # This is needed for large graphs (say over 200 packages) because the + # `visit` function is exponentially slower then, taking minutes. + # See https://github.com/pypa/pip/issues/10557 + # We will loop until we explicitly break the loop. + while True: + leaves = set() + for key in graph: + if key is None: + continue + for _child in graph.iter_children(key): + # This means we have at least one child + break + else: + # No child. + leaves.add(key) + if not leaves: + # We are done simplifying. + break + # Calculate the weight for the leaves. + weight = len(graph) - 1 + for leaf in leaves: + if leaf not in requirement_keys: + continue + weights[leaf] = weight + # Remove the leaves from the graph, making it simpler. + for leaf in leaves: + graph.remove(leaf) + + # Visit the remaining graph. + # `None` is guaranteed to be the root node by resolvelib. + visit(None) + + # Sanity check: all requirement keys should be in the weights, + # and no other keys should be in the weights. + difference = set(weights.keys()).difference(requirement_keys) + assert not difference, difference + + return weights + + +def _req_set_item_sorter( + item: Tuple[str, InstallRequirement], + weights: Dict[Optional[str], int], +) -> Tuple[int, str]: + """Key function used to sort install requirements for installation. + + Based on the "weight" mapping calculated in ``get_installation_order()``. + The canonical package name is returned as the second member as a tie- + breaker to ensure the result is predictable, which is useful in tests. + """ + name = canonicalize_name(item[0]) + return weights[name], name diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/self_outdated_check.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/self_outdated_check.py new file mode 100644 index 0000000000000000000000000000000000000000..2e0e3df3542b54701a0c7117608511ad0db42848 --- /dev/null +++ b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/self_outdated_check.py @@ -0,0 +1,252 @@ +import datetime +import functools +import hashlib +import json +import logging +import optparse +import os.path +import sys +from dataclasses import dataclass +from typing import Any, Callable, Dict, Optional + +from pip._vendor.packaging.version import Version +from pip._vendor.packaging.version import parse as parse_version +from pip._vendor.rich.console import Group +from pip._vendor.rich.markup import escape +from pip._vendor.rich.text import Text + +from pip._internal.index.collector import LinkCollector +from pip._internal.index.package_finder import PackageFinder +from pip._internal.metadata import get_default_environment +from pip._internal.models.selection_prefs import SelectionPreferences +from pip._internal.network.session import PipSession +from pip._internal.utils.compat import WINDOWS +from pip._internal.utils.entrypoints import ( + get_best_invocation_for_this_pip, + get_best_invocation_for_this_python, +) +from pip._internal.utils.filesystem import adjacent_tmp_file, check_path_owner, replace +from pip._internal.utils.misc import ( + ExternallyManagedEnvironment, + check_externally_managed, + ensure_dir, +) + +_WEEK = datetime.timedelta(days=7) + +logger = logging.getLogger(__name__) + + +def _get_statefile_name(key: str) -> str: + key_bytes = key.encode() + name = hashlib.sha224(key_bytes).hexdigest() + return name + + +def _convert_date(isodate: str) -> datetime.datetime: + """Convert an ISO format string to a date. + + Handles the format 2020-01-22T14:24:01Z (trailing Z) + which is not supported by older versions of fromisoformat. + """ + return datetime.datetime.fromisoformat(isodate.replace("Z", "+00:00")) + + +class SelfCheckState: + def __init__(self, cache_dir: str) -> None: + self._state: Dict[str, Any] = {} + self._statefile_path = None + + # Try to load the existing state + if cache_dir: + self._statefile_path = os.path.join( + cache_dir, "selfcheck", _get_statefile_name(self.key) + ) + try: + with open(self._statefile_path, encoding="utf-8") as statefile: + self._state = json.load(statefile) + except (OSError, ValueError, KeyError): + # Explicitly suppressing exceptions, since we don't want to + # error out if the cache file is invalid. + pass + + @property + def key(self) -> str: + return sys.prefix + + def get(self, current_time: datetime.datetime) -> Optional[str]: + """Check if we have a not-outdated version loaded already.""" + if not self._state: + return None + + if "last_check" not in self._state: + return None + + if "pypi_version" not in self._state: + return None + + # Determine if we need to refresh the state + last_check = _convert_date(self._state["last_check"]) + time_since_last_check = current_time - last_check + if time_since_last_check > _WEEK: + return None + + return self._state["pypi_version"] + + def set(self, pypi_version: str, current_time: datetime.datetime) -> None: + # If we do not have a path to cache in, don't bother saving. + if not self._statefile_path: + return + + # Check to make sure that we own the directory + if not check_path_owner(os.path.dirname(self._statefile_path)): + return + + # Now that we've ensured the directory is owned by this user, we'll go + # ahead and make sure that all our directories are created. + ensure_dir(os.path.dirname(self._statefile_path)) + + state = { + # Include the key so it's easy to tell which pip wrote the + # file. + "key": self.key, + "last_check": current_time.isoformat(), + "pypi_version": pypi_version, + } + + text = json.dumps(state, sort_keys=True, separators=(",", ":")) + + with adjacent_tmp_file(self._statefile_path) as f: + f.write(text.encode()) + + try: + # Since we have a prefix-specific state file, we can just + # overwrite whatever is there, no need to check. + replace(f.name, self._statefile_path) + except OSError: + # Best effort. + pass + + +@dataclass +class UpgradePrompt: + old: str + new: str + + def __rich__(self) -> Group: + if WINDOWS: + pip_cmd = f"{get_best_invocation_for_this_python()} -m pip" + else: + pip_cmd = get_best_invocation_for_this_pip() + + notice = "[bold][[reset][blue]notice[reset][bold]][reset]" + return Group( + Text(), + Text.from_markup( + f"{notice} A new release of pip is available: " + f"[red]{self.old}[reset] -> [green]{self.new}[reset]" + ), + Text.from_markup( + f"{notice} To update, run: " + f"[green]{escape(pip_cmd)} install --upgrade pip" + ), + ) + + +def was_installed_by_pip(pkg: str) -> bool: + """Checks whether pkg was installed by pip + + This is used not to display the upgrade message when pip is in fact + installed by system package manager, such as dnf on Fedora. + """ + dist = get_default_environment().get_distribution(pkg) + return dist is not None and "pip" == dist.installer + + +def _get_current_remote_pip_version( + session: PipSession, options: optparse.Values +) -> Optional[str]: + # Lets use PackageFinder to see what the latest pip version is + link_collector = LinkCollector.create( + session, + options=options, + suppress_no_index=True, + ) + + # Pass allow_yanked=False so we don't suggest upgrading to a + # yanked version. + selection_prefs = SelectionPreferences( + allow_yanked=False, + allow_all_prereleases=False, # Explicitly set to False + ) + + finder = PackageFinder.create( + link_collector=link_collector, + selection_prefs=selection_prefs, + ) + best_candidate = finder.find_best_candidate("pip").best_candidate + if best_candidate is None: + return None + + return str(best_candidate.version) + + +def _self_version_check_logic( + *, + state: SelfCheckState, + current_time: datetime.datetime, + local_version: Version, + get_remote_version: Callable[[], Optional[str]], +) -> Optional[UpgradePrompt]: + remote_version_str = state.get(current_time) + if remote_version_str is None: + remote_version_str = get_remote_version() + if remote_version_str is None: + logger.debug("No remote pip version found") + return None + state.set(remote_version_str, current_time) + + remote_version = parse_version(remote_version_str) + logger.debug("Remote version of pip: %s", remote_version) + logger.debug("Local version of pip: %s", local_version) + + pip_installed_by_pip = was_installed_by_pip("pip") + logger.debug("Was pip installed by pip? %s", pip_installed_by_pip) + if not pip_installed_by_pip: + return None # Only suggest upgrade if pip is installed by pip. + + local_version_is_older = ( + local_version < remote_version + and local_version.base_version != remote_version.base_version + ) + if local_version_is_older: + return UpgradePrompt(old=str(local_version), new=remote_version_str) + + return None + + +def pip_self_version_check(session: PipSession, options: optparse.Values) -> None: + """Check for an update for pip. + + Limit the frequency of checks to once per week. State is stored either in + the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix + of the pip script path. + """ + installed_dist = get_default_environment().get_distribution("pip") + if not installed_dist: + return + try: + check_externally_managed() + except ExternallyManagedEnvironment: + return + + upgrade_prompt = _self_version_check_logic( + state=SelfCheckState(cache_dir=options.cache_dir), + current_time=datetime.datetime.now(datetime.timezone.utc), + local_version=installed_dist.version, + get_remote_version=functools.partial( + _get_current_remote_pip_version, session, options + ), + ) + if upgrade_prompt is not None: + logger.warning("%s", upgrade_prompt, extra={"rich": True}) diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__init__.py b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/__init__.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32e0391b6c900f3faf73ccfbd2450254d08c5ca9 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fb5de70280a23b07f46ad1c1c9a275b8ce54840 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_log.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_log.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52cbd550743338d1bfb3c8dd24e354b1a50dcf06 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/_log.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc4e3b4dc1695ac3bb57315fbaff5e4927e36b5b Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/compat.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..812d3edec08c12fe6b76368707243025f1264323 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/compat.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/compatibility_tags.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/compatibility_tags.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e709f09e5de573e107e40b7aab0de6f28875b6e1 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/compatibility_tags.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/datetime.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/datetime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1575a3a3b96299e79b9dbbc400ea521ba8d79216 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/datetime.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3328903bf4560638fdb249dea2a3dc220ecea295 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d87f546e588071d15c28fe42a9277d51ffa3389 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fe2c0b9fa5e1a7e609011c71570182dff5fda55 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76383645750f82c9cf66585bc22ca1c8e89913a4 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bbb0caeff3fa0117e3bf8584008968e008ebbdd Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc differ diff --git a/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..141ff9bc98495fda093ac2d74e01d8a0a8740825 Binary files /dev/null and b/simulation/.venv-planner/lib/python3.12/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc differ