diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0018--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0018--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..2bbffaf5d76080fafc7e88000a687bd85b433e0e --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0018--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07ccafa8f12d4a79130635b0a5a5d60070bd5fd624e1abf9b082bd7ac6e29f20 +size 8923 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0045--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0045--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..ce18a8be5b6a535977cd8b8e954b8033ff9a1c53 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0045--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7964d46169e07ac30102121470bdbdf44e97bc881bb13b1c9f50abfde978f418 +size 8741 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0047--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0047--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..694e88a884b710b4084e744fe157b2e0e09593c3 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0047--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:67b911b8f2ce3c27dc3a0accec11ed18a5d5f44e6ded4e2cf1a31756f1bf6005 +size 9392 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0083--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0083--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..3f92ae7f55b4968e86f40fcde45b3449f1c04146 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0083--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e4c65ea5bcaef6669778fdf3b0253cd70ab2fab8e29ba75e6f1363620725cda +size 9134 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0105--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0105--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..91b3a601da2e393de24f4588a5425649341924f7 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0105--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:559acffb3211f8240ab8461ec203349651e52782798b7a8811729833fd849496 +size 9271 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0106--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0106--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..80764ca1c4aa3f8e6f0550de1bb9237fa7ec8dcb --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0106--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3004737bf2451e26c6e78643ae5ddd3f8aa1dad9666b564ccac2bdd74177860 +size 9013 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0135--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0135--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..0a67d921278bcfc983db42050879676a68a9a00f --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--N0135--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d34411e8720f1322906eaeb3e6788e50ac108d7b24a2ae87bff8106033f047ee +size 9140 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0002--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0002--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..13865e709eb3a59c2fb1f6ebb21ad20f4867e1a4 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0002--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b771ba9eca2cc934d2df64d8e68feaf96a18fb2a3dd275ac800c7451206cf55 +size 9616 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0020--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0020--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..466d4a267ff4d6644934ce425263e0d6b4b44701 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0020--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73e542e0334243d117428807d775d6f7b87d541222b93356d74168dcb0df76e9 +size 9235 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0051--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0051--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..280419b723042740424e3882ae3c76fe84dc5ddb --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0051--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bd32c1c168e736cf736e5c98c63d553bc34916c935f6a99b1444a1be29b1f331 +size 9256 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0089--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0089--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..f1f449ac3014a93f608e0dfcf41570b03cf64a1e --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0089--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9f7aaa88688bdcdc88af49c8f8506636c00d1113c54182a54a09d60ddcdeb2a +size 5933 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0121--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0121--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..6803e34642915c03eb4a1bfef6301ae1bf020b90 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0121--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1900c9f7d74469a560de1c451580fda175737cb374cb00fe8c7656f4feece73 +size 6012 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0172--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0172--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..5b415b18d0c16b8e710a1a4197e730845d35bed7 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0172--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ba68e312c7982b34b72117d05ffe2d9e9871a72b91197d298b079d777a036b2 +size 9380 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0193--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0193--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..f1dc541e032401aaa66866c087d388b8b1ce3fd1 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--P0193--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07396c6b93ef26e269c1d7d9d2270929e1f30272c8162b8add27056e45493479 +size 9105 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0101--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0101--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..c7eee0984b46c83c00726b8e0e570adfa767faab --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0101--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:446af99ea78da124023014613ee92e7c95eba16d3d33a1ce760285209f4278d5 +size 9093 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0111--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0111--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..ba39daef21083b03e7edb63a3bfb4a24f3b3aa2d --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0111--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15f3701a0f3eeb92189ccd1bd23c862c19903c1d8742577ad54c6a5e0ff1b86e +size 9084 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0134--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0134--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..1eec3565ce4d78f5f83070e096edb953d3703a57 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0134--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5cc63a83e8bb3533ce30b0af4ecf90679346046a1fafa3613a69490739da9c2 +size 9172 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0136--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0136--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..b014c3b43f329adb328567767690a5f1866dbd56 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0136--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e8a03fc846161dd1e0e1eacc39752948dcfcf9b2aa6b0a3469d657fe4272e66 +size 9270 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0171--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0171--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..d9d96f13387b286f2563850d1e726bbb39843759 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0171--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:180a996c35fdd115a9f44180daaa9bc7ae3327016b33b444db02a3e9a60c8db5 +size 9090 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0193--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0193--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..35d265ded07d1dd96326c6820be9ff32702919e2 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0193--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:176124ee1e0afa99996308e78428bc9176800c698c894e6c4350caf52bdfd2e5 +size 9074 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0257--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0257--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..90e7794030634a38d55583e1126f70d0b3f3649c --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0257--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4340d97643dc3f59aea89123b0ba495158b6e74f4d0689409b544affa48accee +size 9000 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0275--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0275--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..ef72dc163028d1c0adef4b999fed527b8a968efa --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0275--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2433920641b8deb62294b004b8b3fdf95e80f777b3d27d6f499612710ef8c7d0 +size 9470 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0326--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0326--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..c7ff0ff4b3bfd7b1441045c269533fd3159a6bbd --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0326--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d47f7ccfb8226ee21b27f251c189b5f406a6030cc7d1bcc50a66ae452f82ff7 +size 9159 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0330--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0330--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..e3765f461c6b7368cb4aad8a0bb65e69d39122f8 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0330--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4c80e1ca25c75da850f62ec64fefe33df83a351465b4d8ac02a8fc18ea531a2 +size 9171 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0352--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0352--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..ffa664ae1364a3db94b44d32361f4c4f263a88a7 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0352--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c54e21efdf63ed084d087177dfb739c81920ff053fe38d10a50765be362b1ff1 +size 9393 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0364--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0364--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..280a6873924ed5c6e437a3783420e2de84b05bce --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0364--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a5dab93cd240ff00e0943963d6b14589678b2c05db44b2a1c236ef00209cd12 +size 6296 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0367--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0367--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..4c4a6469e9c8b3a2848a42450955c15a64c30917 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0367--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48985621327a37bc3a3a2daf2a08ddf5f57dac0393d46ff8ac77abb32cc65073 +size 9159 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0380--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0380--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..b36c90ad01801c010c39fed4f8d4bc4c8cff6228 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--T0380--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e541671f14869095e4ea4584a51e42099dde0b9cd96a56dd5402f666773c2887 +size 9562 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0006--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0006--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..1ccb440ed88c573bef6cc7a03637316c9defd75e --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0006--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c0d8ea62bb12cfbda8ae251e76722090b41ff52278bb3169873add142964fce +size 8977 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0026--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0026--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..8bc8603cbed44bc6106529de9313e4d8612a0025 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0026--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:199389fd84490ded082935419db0c19cb1d5104a98b567a9254227966cf83d22 +size 10173 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0033--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0033--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..a749a0ff12cec8e0ca343a901074fc45229a8a68 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0033--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e450b04f5ff4f5eeb81203d63136c2c5e0388446b32e39b7be671a4ada7e7dbc +size 9471 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0131--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0131--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..9d7fae4a01e98ca8e1f5ebdd7ecfde3dc2e230e4 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0131--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e19de7c9ae0b29d5e794172c9b3802bcfbdfdbe8a874a07ec74b583b851e0c1 +size 9118 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0141--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0141--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..281f2eceff1acbc56ba15176b59b2d5690f1c856 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0141--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:528eb91b3d5c79a00bf2e3c3ee94024b5f3d6cc77dbb7e46d600ad9d8ce5a9b9 +size 9465 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0144--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0144--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..f452232eb7a315409ba8b937994255949912257f --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0144--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc2bcdd7c35aa90059dbdff886c2bf8590301728e7f16db47ed38425474197d6 +size 9224 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0145--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0145--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..d8a15a23affa5a797608d0d1c437c5e13acb3bf6 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0145--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06573cf23448fd4de119751e2f6fbf4c34a4a6d6228ef69038917afa4d296154 +size 9036 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0199--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0199--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..5f6adcbf3175086293d6a730f9c1196167fbdc4d --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0199--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02f941716f3faf6a5dbcb0f092414aaee4f5ed8a99ca3b424d84a23de0730646 +size 9038 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0200--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0200--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..4fa2629da453faf6a74188253388a3a4b7f73923 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0200--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a352f33fd37c54a7b564d4c917d664064fd98624a52e0a085c2f941861da0073 +size 9317 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0250--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0250--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..5f5e5dc1ee12598ac023f2c2d82e02ea14c29ee8 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0250--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa87f059a729b5da61f63750c66307dd163be894932f1a50faad7c0754edc82b +size 6570 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0335--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0335--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..2f36677dfc59f4f8d94bd2cdef9120334d8170ba --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0335--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e038c00c3c42bb1b890336ddfa7cea12626ec4337aa8b746d5862c3ec81d7050 +size 9078 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0377--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0377--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..c20a23e78fc901882ef54c7f4c9bec9099a200c9 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0377--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4141db35cd60247c2894c7e870497825590273dcf9d867645b9f9642002b78fe +size 8876 diff --git a/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0395--2d_none--0000_000.png b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0395--2d_none--0000_000.png new file mode 100644 index 0000000000000000000000000000000000000000..a587f1c668fc557ac3a00e19f465e47914724a03 --- /dev/null +++ b/benchmarks/VGMED/image_folder/SAMed2D_v1/fundus_photography/masks/fundus_photography--PALM19--V0395--2d_none--0000_000.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f99c0b8064091e9d01f802c555d0fbd7f633001e9c5787af0d83caa3705dfa5 +size 9216 diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/Makefile" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/Makefile" new file mode 100644 index 0000000000000000000000000000000000000000..39c5b5b79f16a3109b98b29c26c1c102bc2c7854 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/Makefile" @@ -0,0 +1,18 @@ +.PHONY: build commit quality style + +check_dirs := examples scripts verl setup.py + +build: + python3 setup.py sdist bdist_wheel + +commit: + pre-commit install + pre-commit run --all-files + +quality: + ruff check $(check_dirs) + ruff format --check $(check_dirs) + +style: + ruff check $(check_dirs) --fix + ruff format $(check_dirs) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/README.md" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/README.md" new file mode 100644 index 0000000000000000000000000000000000000000..a7f41f6adb85929ea8e57852f4781d069aafb667 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/README.md" @@ -0,0 +1,33 @@ +# EasyR1 for LLaVA-Critic-R1 + +This codebase is a customized extension of [EasyR1](https://github.com/hiyouga/EasyR1), specifically modified to support RL training using LLaMA-3.2-Vision-11B-Instruct as the base model. For RL training using Qwen-2.5-VL and Mimo-VL as base models, please use the original EasyR1 codebase. We will integrate support for all models into a unified codebase in the future. + +## Training based on Qwen-2.5-VL + +``` +bash ./examples/qwen2_5_vl_7b_llava_critic_grpo.sh +``` + +## Training based on ThinkLite-VL + +``` +bash ./examples/thinklite_vl_7b_llava_critic_grpo.sh +``` + +## Training based on Mimo-VL + +### SFT checkpoint +``` +bash ./examples/mimo_vl_7b_llava_critic_grpo.sh +``` + +### RL checkpoint +``` +bash ./examples/mimo_vl_rl_7b_llava_critic_grpo.sh +``` + +## Training based on LLaMA-3.2-Vision + +``` +bash ./examples/llama3.2v_critic_grpo.sh +``` diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/baselines/qwen2_5_vl_3b_clevr.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/baselines/qwen2_5_vl_3b_clevr.sh" new file mode 100644 index 0000000000000000000000000000000000000000..b3730ebd20b5dfd8c485f8e9aa1085d3e3df8ecc --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/baselines/qwen2_5_vl_3b_clevr.sh" @@ -0,0 +1,19 @@ +#!/bin/bash + +set -x + +export PYTHONUNBUFFERED=1 + +MODEL_PATH=Qwen/Qwen2.5-VL-3B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=BUAADreamer/clevr_count_70k@train \ + data.val_files=BUAADreamer/clevr_count_70k@test \ + data.format_prompt=./examples/format_prompt/r1v_format.jinja \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.rollout.tensor_parallel_size=1 \ + worker.reward.reward_type=sequential \ + worker.reward.reward_function=./examples/reward_function/r1v.py:compute_score \ + trainer.experiment_name=qwen2_5_vl_3b_clevr \ + trainer.n_gpus_per_node=2 diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/baselines/qwen2_5_vl_3b_geoqa8k.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/baselines/qwen2_5_vl_3b_geoqa8k.sh" new file mode 100644 index 0000000000000000000000000000000000000000..c19c4fc477dbcf4faaa441c6ae9630bc59a0bcf8 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/baselines/qwen2_5_vl_3b_geoqa8k.sh" @@ -0,0 +1,19 @@ +#!/bin/bash + +set -x + +export PYTHONUNBUFFERED=1 + +MODEL_PATH=Qwen/Qwen2.5-VL-3B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=leonardPKU/GEOQA_8K_R1V@train \ + data.val_files=leonardPKU/GEOQA_8K_R1V@test \ + data.format_prompt=./examples/format_prompt/r1v_format.jinja \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.rollout.tensor_parallel_size=1 \ + worker.reward.reward_type=sequential \ + worker.reward.reward_function=./examples/reward_function/r1v.py:compute_score \ + trainer.experiment_name=qwen2_5_vl_3b_geoqa8k \ + trainer.n_gpus_per_node=8 diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/config.yaml" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/config.yaml" new file mode 100644 index 0000000000000000000000000000000000000000..b3914d7b38f0161c9e9d8e5644fd64ad0ccde9f8 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/config.yaml" @@ -0,0 +1,96 @@ +data: + train_files: hiyouga/math12k@train + val_files: hiyouga/math12k@test + prompt_key: problem + answer_key: answer + image_key: image + max_prompt_length: 4096 + max_response_length: 2048 + rollout_batch_size: 256 + val_batch_size: 1024 + format_prompt: ./examples/format_prompt/math_format.jinja + override_chat_template: null + shuffle: true + seed: 1 + max_pixels: 4194304 + min_pixels: 262144 + filter_overlong_prompts: true + +algorithm: + adv_estimator: grpo + disable_kl: false + use_kl_loss: true + kl_penalty: low_var_kl + kl_coef: 1.0e-2 + +worker: + actor: + global_batch_size: 128 + micro_batch_size_per_device_for_update: 4 + micro_batch_size_per_device_for_experience: 8 + max_grad_norm: 1.0 + padding_free: true + ulysses_sequence_parallel_size: 1 + is_entropy_reg: False + entropy_coef: 0.001 + model: + model_path: Qwen/Qwen2.5-7B-Instruct + enable_gradient_checkpointing: true + trust_remote_code: true + freeze_vision_tower: false + optim: + lr: 1.0e-6 + weight_decay: 1.0e-2 + strategy: adamw # {adamw, adamw_bf16} + lr_warmup_ratio: 0.0 + fsdp: + enable_full_shard: true + enable_cpu_offload: false + enable_rank0_init: true + offload: + offload_params: true # true: more CPU memory; false: more GPU memory + offload_optimizer: true # true: more CPU memory; false: more GPU memory + + rollout: + n: 8 + temperature: 1.0 + top_p: 0.99 + gpu_memory_utilization: 0.6 + max_num_batched_tokens: 8192 + max_model_len: 8192 + enforce_eager: false + enable_chunked_prefill: false + tensor_parallel_size: 2 + limit_images: 10 + val_override_config: + temperature: 0.5 + n: 1 + + ref: + fsdp: + enable_full_shard: true + enable_cpu_offload: true # true: more CPU memory; false: more GPU memory + enable_rank0_init: true + offload: + offload_params: false + + reward: + reward_type: batch + reward_function: ./examples/reward_function/math.py:compute_score + +trainer: + total_epochs: 15 + max_steps: null + project_name: easy_r1 + experiment_name: qwen2_5_7b_math_grpo + logger: ["console", "wandb"] + nnodes: 1 + n_gpus_per_node: 8 + val_freq: -1 # -1 to disable + val_before_train: false + val_only: false + val_generations_to_log: 3 + save_freq: 10 # -1 to disable + save_limit: -1 # -1 to disable + save_checkpoint_path: null + load_checkpoint_path: null diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/format_prompt/caption_format.jinja" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/format_prompt/caption_format.jinja" new file mode 100644 index 0000000000000000000000000000000000000000..fefc131160f8c1908e227967359768a11fb0c381 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/format_prompt/caption_format.jinja" @@ -0,0 +1 @@ +{{ content | trim }} You FIRST describe the given image in a detailed manner, THEN think about the reasoning process as an internal monologue based on the generated description and given question and then provide the final answer. The description MUST BE enclosed within tags. The reasoning process MUST BE enclosed within tags. The final answer MUST BE put in \boxed{}. diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/llama3.2v_critic_grpo.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/llama3.2v_critic_grpo.sh" new file mode 100644 index 0000000000000000000000000000000000000000..2010311223c8a5ec03bf27c9e3cd94a4f2e9f884 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/llama3.2v_critic_grpo.sh" @@ -0,0 +1,29 @@ +#!/bin/bash + +set -x + +export PYTHONUNBUFFERED=1 + +MODEL_PATH=meta-llama/Llama-3.2-11B-Vision-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=lmms-lab/LLaVA-Critic-GRPO-dataset@train \ + data.val_files=lmms-lab/LLaVA-Critic-GRPO-dataset@train \ + data.shuffle=True \ + data.format_prompt=./examples/format_prompt/math_format.jinja \ + data.rollout_batch_size=256 \ + data.max_prompt_length=4096 \ + data.prompt_key=question \ + worker.actor.is_entropy_reg=False \ + worker.actor.global_batch_size=128 \ + worker.actor.optim.lr=5.0e-7 \ + worker.actor.micro_batch_size_per_device_for_update=4 \ + worker.actor.micro_batch_size_per_device_for_experience=8 \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.rollout.tensor_parallel_size=8 \ + worker.rollout.limit_images=1 \ + worker.rollout.gpu_memory_utilization=0.6 \ + worker.reward.reward_function=./examples/reward_function/math.py:compute_score \ + trainer.experiment_name=llama3.2v_critic_grpo \ + trainer.n_gpus_per_node=8 diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/mimo_vl_7b_llava_critic_grpo.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/mimo_vl_7b_llava_critic_grpo.sh" new file mode 100644 index 0000000000000000000000000000000000000000..5823978189aeb09238635f7b9c32f5140f8e1ba3 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/mimo_vl_7b_llava_critic_grpo.sh" @@ -0,0 +1,19 @@ +#!/bin/bash + +MODEL_PATH=XiaomiMiMo/MiMo-VL-7B-SFT-2508 + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=lmms-lab/LLaVA-Critic-GRPO-dataset@train \ + data.val_files=lmms-lab/LLaVA-Critic-GRPO-dataset@train \ + data.filter_overlong_prompts=True \ + data.prompt_key=question \ + data.max_prompt_length=6142 \ + worker.actor.is_entropy_reg=False \ + worker.actor.global_batch_size=128 \ + worker.actor.micro_batch_size_per_device_for_update=4 \ + worker.actor.micro_batch_size_per_device_for_experience=8 \ + worker.actor.model.model_path=${MODEL_PATH} \ + trainer.experiment_name=mimo_vl_7b_llava_critic_grpo \ + trainer.n_gpus_per_node=8 + diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/mimo_vl_rl_7b_llava_critic_grpo.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/mimo_vl_rl_7b_llava_critic_grpo.sh" new file mode 100644 index 0000000000000000000000000000000000000000..c5d8bc37c0e8285ff08accabd6ba8676cb15f7e1 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/mimo_vl_rl_7b_llava_critic_grpo.sh" @@ -0,0 +1,19 @@ +#!/bin/bash + +MODEL_PATH=XiaomiMiMo/MiMo-VL-7B-RL-2508 + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=lmms-lab/LLaVA-Critic-GRPO-dataset@train \ + data.val_files=lmms-lab/LLaVA-Critic-GRPO-dataset@train \ + data.filter_overlong_prompts=True \ + data.prompt_key=question \ + data.max_prompt_length=6142 \ + worker.actor.is_entropy_reg=False \ + worker.actor.global_batch_size=128 \ + worker.actor.micro_batch_size_per_device_for_update=4 \ + worker.actor.micro_batch_size_per_device_for_experience=8 \ + worker.actor.model.model_path=${MODEL_PATH} \ + trainer.experiment_name=mimo_vl_rl_7b_llava_critic_grpo \ + trainer.n_gpus_per_node=8 + diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/qwen2_5_vl_7b_llava_critic_grpo.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/qwen2_5_vl_7b_llava_critic_grpo.sh" new file mode 100644 index 0000000000000000000000000000000000000000..d91040467565c5cd542840e626451acba46942d4 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/qwen2_5_vl_7b_llava_critic_grpo.sh" @@ -0,0 +1,19 @@ +#!/bin/bash + +MODEL_PATH=Qwen/Qwen2.5-VL-7B-Instruct + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=lmms-lab/LLaVA-Critic-GRPO-dataset@train \ + data.val_files=lmms-lab/LLaVA-Critic-GRPO-dataset@train \ + data.filter_overlong_prompts=True \ + data.prompt_key=question \ + data.max_prompt_length=6142 \ + worker.actor.is_entropy_reg=False \ + worker.actor.global_batch_size=128 \ + worker.actor.micro_batch_size_per_device_for_update=4 \ + worker.actor.micro_batch_size_per_device_for_experience=8 \ + worker.actor.model.model_path=${MODEL_PATH} \ + trainer.experiment_name=qwen2_5_vl_7b_llava_critic_grpo \ + trainer.n_gpus_per_node=8 + diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/__pycache__/caption.cpython-310.pyc" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/__pycache__/caption.cpython-310.pyc" new file mode 100644 index 0000000000000000000000000000000000000000..dda33e388162a6902c2c8b19c72a32f0d935b978 Binary files /dev/null and "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/__pycache__/caption.cpython-310.pyc" differ diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/__pycache__/math.cpython-310.pyc" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/__pycache__/math.cpython-310.pyc" new file mode 100644 index 0000000000000000000000000000000000000000..da95e84dce6ce6f772b4b73188a1309e793a07c0 Binary files /dev/null and "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/__pycache__/math.cpython-310.pyc" differ diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/caption.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/caption.py" new file mode 100644 index 0000000000000000000000000000000000000000..3c38f113afe2b1efe76118f5f4e4ce22c55253db --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/caption.py" @@ -0,0 +1,46 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# 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 re +from typing import Dict, List + +from mathruler.grader import extract_boxed_content, grade_answer + + +def format_reward(predict: str) -> float: + pattern = re.compile(r".*.*.*.*\\boxed\{.*\}.*", re.DOTALL) + format_match = re.fullmatch(pattern, predict) + return 1.0 if format_match else 0.0 + + +def accuracy_reward(predict: str, ground_truth: str) -> float: + answer = extract_boxed_content(predict) + return 1.0 if grade_answer(answer, ground_truth) else 0.0 + + +def compute_score(predicts: List[str], ground_truths: List[str], format_weight: float = 0.1) -> List[Dict[str, float]]: + scores = [] + for predict, ground_truth in zip(predicts, ground_truths): + predict = re.sub(r"\s*(<|>|/)\s*", r"\1", predict) # handle qwen2.5vl-32b format + format_score = format_reward(predict) + accuracy_score = accuracy_reward(predict, ground_truth) + scores.append( + { + "overall": (1 - format_weight) * accuracy_score + format_weight * format_score, + "format": format_score, + "accuracy": accuracy_score, + } + ) + + return scores diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/math.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/math.py" new file mode 100644 index 0000000000000000000000000000000000000000..f8887532df8cd0f86967c54e355839cb969066d6 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/math.py" @@ -0,0 +1,46 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# 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 re +from typing import Dict, List + +from mathruler.grader import extract_boxed_content, grade_answer + + +def format_reward(predict: str) -> float: + pattern = re.compile(r".*.*\\boxed\{.*\}.*", re.DOTALL) + format_match = re.fullmatch(pattern, predict) + return 1.0 if format_match else 0.0 + + +def accuracy_reward(predict: str, ground_truth: str) -> float: + answer = extract_boxed_content(predict) + return 1.0 if grade_answer(answer, ground_truth) else 0.0 + + +def compute_score(predicts: List[str], ground_truths: List[str], format_weight: float = 0.1) -> List[Dict[str, float]]: + scores = [] + for predict, ground_truth in zip(predicts, ground_truths): + predict = re.sub(r"\s*(<|>|/)\s*", r"\1", predict) # handle qwen2.5vl-32b format + format_score = format_reward(predict) + accuracy_score = accuracy_reward(predict, ground_truth) + scores.append( + { + "overall": (1 - format_weight) * accuracy_score + format_weight * format_score, + "format": format_score, + "accuracy": accuracy_score, + } + ) + + return scores diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/r1v.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/r1v.py" new file mode 100644 index 0000000000000000000000000000000000000000..204762f31458f8470ee0be7468cfc9ce5b627446 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/reward_function/r1v.py" @@ -0,0 +1,47 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# 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 re +from typing import Dict + +from mathruler.grader import grade_answer + + +def format_reward(predict: str) -> float: + pattern = re.compile(r".*?\s*.*?", re.DOTALL) + format_match = re.fullmatch(pattern, predict) + return 1.0 if format_match else 0.0 + + +def accuracy_reward(predict: str, ground_truth: str) -> float: + try: + content_match = re.search(r"(.*?)", predict) + given_answer = content_match.group(1).strip() if content_match else predict.strip() + if grade_answer(given_answer, ground_truth.strip()): + return 1.0 + + except Exception: + pass + + return 0.0 + + +def compute_score(predict: str, ground_truth: str, format_weight: float = 0.5) -> Dict[str, float]: + format_score = format_reward(predict) + accuracy_score = accuracy_reward(predict, ground_truth) + return { + "overall": (1 - format_weight) * accuracy_score + format_weight * format_score, + "format": format_score, + "accuracy": accuracy_score, + } diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/runtime_env.yaml" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/runtime_env.yaml" new file mode 100644 index 0000000000000000000000000000000000000000..a4086253d4f7198f85225941c076285ab9f5321a --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/runtime_env.yaml" @@ -0,0 +1,9 @@ +working_dir: ./ +excludes: ["/.git/"] +env_vars: + TOKENIZERS_PARALLELISM: "true" + NCCL_DEBUG: "WARN" + VLLM_LOGGING_LEVEL: "WARN" + TORCH_NCCL_AVOID_RECORD_STREAMS: "1" + PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:False" + PYTHONUNBUFFERED: "1" diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/thinklite_vl_7b_llava_critic_grpo.sh" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/thinklite_vl_7b_llava_critic_grpo.sh" new file mode 100644 index 0000000000000000000000000000000000000000..13c4766819e1b89070bd2014c57d39ca39c93a33 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/examples/thinklite_vl_7b_llava_critic_grpo.sh" @@ -0,0 +1,19 @@ +#!/bin/bash + +MODEL_PATH=russwang/ThinkLite-VL-7B + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=lmms-lab/LLaVA-Critic-GRPO-dataset@train \ + data.val_files=lmms-lab/LLaVA-Critic-GRPO-dataset@train \ + data.filter_overlong_prompts=True \ + data.prompt_key=question \ + data.max_prompt_length=6142 \ + worker.actor.is_entropy_reg=False \ + worker.actor.global_batch_size=128 \ + worker.actor.optim.lr=5.0e-7 \ + worker.actor.micro_batch_size_per_device_for_update=4 \ + worker.actor.micro_batch_size_per_device_for_experience=8 \ + worker.actor.model.model_path=${MODEL_PATH} \ + trainer.experiment_name=thinklite_vl_7b_llava_critic_grpo \ + trainer.n_gpus_per_node=8 \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/requirements.txt" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/requirements.txt" new file mode 100644 index 0000000000000000000000000000000000000000..8543c231b9ec75fe9300417c1498d9328dfadbf2 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/requirements.txt" @@ -0,0 +1,19 @@ +accelerate +codetiming +datasets +liger-kernel +mathruler +numpy +omegaconf +pandas +peft +pillow +pyarrow>=15.0.0 +pylatexenc +qwen-vl-utils +ray[default] +tensordict +torchdata +transformers>=4.51.0 +vllm>=0.7.3 +wandb diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/scripts/model_merger.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/scripts/model_merger.py" new file mode 100644 index 0000000000000000000000000000000000000000..4f4dd3daee1728f35e9fb0aaea94a04b0591a02c --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/scripts/model_merger.py" @@ -0,0 +1,187 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# 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 os +import re +from concurrent.futures import ThreadPoolExecutor +from typing import Dict, List, Tuple + +import numpy as np +import torch +from torch.distributed._tensor import DTensor, Placement, Shard +from transformers import ( + AutoConfig, + AutoModelForCausalLM, + AutoModelForTokenClassification, + AutoModelForVision2Seq, + PretrainedConfig, + PreTrainedModel, +) + + +def merge_by_placement(tensors: List[torch.Tensor], placement: Placement): + if placement.is_replicate(): + return tensors[0] + elif placement.is_partial(): + raise NotImplementedError("Partial placement is not supported yet") + elif placement.is_shard(): + return torch.cat(tensors, dim=placement.dim).contiguous() + else: + raise ValueError(f"Unsupported placement: {placement}") + + +def upload_model_to_huggingface(local_path: str, remote_path: str): + # Push to hugging face + from huggingface_hub import HfApi + + api = HfApi() + api.create_repo(repo_id=remote_path, private=False, exist_ok=True) + api.upload_folder(repo_id=remote_path, folder_path=local_path, repo_type="model") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--local_dir", required=True, type=str, help="The path for your saved model") + parser.add_argument("--hf_upload_path", default=False, type=str, help="The path of the huggingface repo to upload") + args = parser.parse_args() + local_dir: str = args.local_dir + + assert not local_dir.endswith("huggingface"), "The local_dir should not end with huggingface." + + # copy rank zero to find the shape of (dp, fsdp) + rank = 0 + world_size = 0 + for filename in os.listdir(local_dir): + match = re.match(r"model_world_size_(\d+)_rank_0\.pt", filename) + if match: + world_size = match.group(1) + break + + assert world_size, "No model file with the proper format." + + rank0_weight_path = os.path.join(local_dir, f"model_world_size_{world_size}_rank_{rank}.pt") + state_dict = torch.load(rank0_weight_path, map_location="cpu", weights_only=False) + pivot_key = sorted(state_dict.keys())[0] + weight = state_dict[pivot_key] + if isinstance(weight, DTensor): + # get sharding info + device_mesh = weight.device_mesh + mesh = device_mesh.mesh + mesh_dim_names = device_mesh.mesh_dim_names + else: + # for non-DTensor + mesh = np.array([int(world_size)], dtype=np.int64) + mesh_dim_names = ("fsdp",) + + print(f"Got device mesh {mesh}, mesh_dim_names {mesh_dim_names}") + + assert mesh_dim_names in (("fsdp",), ("ddp", "fsdp")), f"Unsupported mesh_dim_names {mesh_dim_names}." + + if "tp" in mesh_dim_names: + # fsdp * tp + total_shards = mesh.shape[-1] * mesh.shape[-2] + mesh_shape = (mesh.shape[-2], mesh.shape[-1]) + else: + # fsdp + total_shards = mesh.shape[-1] + mesh_shape = (mesh.shape[-1],) + + print(f"Processing {total_shards} model shards in total.") + model_state_dict_lst = [] + model_state_dict_lst.append(state_dict) + model_state_dict_lst.extend([""] * (total_shards - 1)) + + def process_one_shard(rank, model_state_dict_lst): + model_path = os.path.join(local_dir, f"model_world_size_{world_size}_rank_{rank}.pt") + state_dict = torch.load(model_path, map_location="cpu", weights_only=False) + model_state_dict_lst[rank] = state_dict + return state_dict + + with ThreadPoolExecutor(max_workers=min(32, os.cpu_count())) as executor: + for rank in range(1, total_shards): + executor.submit(process_one_shard, rank, model_state_dict_lst) + + state_dict: Dict[str, List[torch.Tensor]] = {} + param_placements: Dict[str, List[Placement]] = {} + keys = set(model_state_dict_lst[0].keys()) + for key in keys: + state_dict[key] = [] + for model_state_dict in model_state_dict_lst: + try: + tensor = model_state_dict.pop(key) + except Exception: + print(f"Cannot find key {key} in rank {rank}.") + + if isinstance(tensor, DTensor): + state_dict[key].append(tensor._local_tensor.bfloat16()) + placements = tuple(tensor.placements) + # replicated placement at ddp dimension can be discarded + if mesh_dim_names[0] == "ddp": + placements = placements[1:] + + if key not in param_placements: + param_placements[key] = placements + else: + assert param_placements[key] == placements + else: + state_dict[key].append(tensor.bfloat16()) + + del model_state_dict_lst + + for key in sorted(state_dict): + if not isinstance(state_dict[key], list): + print(f"No need to merge key {key}") + continue + + if key in param_placements: + # merge shards + placements: Tuple[Shard] = param_placements[key] + if len(mesh_shape) == 1: + # 1-D list, FSDP without TP + assert len(placements) == 1 + shards = state_dict[key] + state_dict[key] = merge_by_placement(shards, placements[0]) + else: + # 2-D list, FSDP + TP + raise NotImplementedError("FSDP + TP is not supported yet.") + else: + state_dict[key] = torch.cat(state_dict[key], dim=0) + + print("Merge completed.") + hf_path = os.path.join(local_dir, "huggingface") + config: PretrainedConfig = AutoConfig.from_pretrained(hf_path) + architectures: List[str] = getattr(config, "architectures", ["Unknown"]) + + if "ForTokenClassification" in architectures[0]: + AutoClass = AutoModelForTokenClassification + elif "ForCausalLM" in architectures[0]: + AutoClass = AutoModelForCausalLM + elif "ForConditionalGeneration" in architectures[0]: + AutoClass = AutoModelForVision2Seq + else: + raise NotImplementedError(f"Unknown architecture {architectures}.") + + with torch.device("meta"): + model: PreTrainedModel = AutoClass.from_config(config, torch_dtype=torch.bfloat16) + + assert isinstance(model, PreTrainedModel) + model.to_empty(device="cpu") + + print(f"Saving model to {hf_path}...") + model.save_pretrained(hf_path, state_dict=state_dict) + del state_dict, model + + if args.hf_upload_path: + upload_model_to_huggingface(hf_path, args.hf_upload_path) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/setup.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/setup.py" new file mode 100644 index 0000000000000000000000000000000000000000..b836e58c98f8ec15ddcfcf9f4f96daa71de0bf59 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava-critic-r1/EasyR1/setup.py" @@ -0,0 +1,61 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# 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 re + +from setuptools import find_packages, setup + + +def get_version() -> str: + with open(os.path.join("verl", "__init__.py"), encoding="utf-8") as f: + file_content = f.read() + pattern = r"__version__\W*=\W*\"([^\"]+)\"" + (version,) = re.findall(pattern, file_content) + return version + + +def get_requires() -> list[str]: + with open("requirements.txt", encoding="utf-8") as f: + file_content = f.read() + lines = [line.strip() for line in file_content.strip().split("\n") if not line.startswith("#")] + return lines + + +extra_require = { + "dev": ["pre-commit", "ruff"], +} + + +def main(): + setup( + name="verl", + version=get_version(), + description="An Efficient, Scalable, Multi-Modality RL Training Framework based on veRL", + long_description=open("README.md", encoding="utf-8").read(), + long_description_content_type="text/markdown", + author="verl", + author_email="zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk, hiyouga@buaa.edu.cn", + license="Apache 2.0 License", + url="https://github.com/volcengine/verl", + package_dir={"": "."}, + packages=find_packages(where="."), + python_requires=">=3.9.0", + install_requires=get_requires(), + extras_require=extra_require, + ) + + +if __name__ == "__main__": + main() diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/eval/evaluate_interleave.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/eval/evaluate_interleave.py" new file mode 100644 index 0000000000000000000000000000000000000000..b00d32f2d3f732614384d648cbda85b69af32466 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/eval/evaluate_interleave.py" @@ -0,0 +1,339 @@ +import re +from rouge import Rouge +import argparse +import os +import json +import numpy as np +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.metrics.pairwise import cosine_similarity + + +spot_the_diff = ["Spot-the-Diff", "Birds-to-Words", "CLEVR-Change"] +image_edit_instruct = ["IEdit", "HQ-Edit", "MagicBrush"] +visual_story_telling = ["AESOP", "FlintstonesSV", "PororoSV", "VIST"] +visual_cloze = ["COMICS_Dialogue", "RecipeQA_VisualCloze"] +text_rich_vqa = ["WebQA", "TQA", "OCR-VQA", "DocVQA"] +multi_image_vqa = ["MIT-States_StateCoherence", "MIT-States_PropertyCoherence", "VISION", "RecipeQA_ImageCoherence"] + +puzzle = ["RAVEN"] +nlrv2 = ["NLVR2_Mantis"] +qbench = ["QBench"] + +class Eval: + def __init__(self): + self.periodStrip = re.compile("(?!<=\d)(\.)(?!\d)") + self.commaStrip = re.compile("(\d)(\,)(\d)") + self.punct = [ + ";", + r"/", + "[", + "]", + '"', + "{", + "}", + "(", + ")", + "=", + "+", + "\\", + "_", + "-", + ">", + "<", + "@", + "`", + ",", + "?", + "!", + ] + + def processPunctuation(self, inText): + outText = inText + for p in self.punct: + if (p + " " in inText or " " + p in inText) or ( + re.search(self.commaStrip, inText) != None + ): + outText = outText.replace(p, "") + else: + outText = outText.replace(p, " ") + outText = self.periodStrip.sub("", outText, re.UNICODE) + return outText + + def process(self, answer): + answer = answer.replace("\n", " ") + answer = answer.replace("\t", " ") + answer = answer.strip() + answer = self.processPunctuation(answer) + answer = answer.strip('\'') + answer = answer.strip('\"') + answer = answer.strip(')') + answer = answer.strip('(') + answer = answer.strip().lower() + return answer + + def evaluate_rouge(self,preds): + rouge = Rouge() + acc = {'f': []} + eval_list = [] + for i, res in enumerate(preds): + sample_id = res['sample_id'] + # print(sample_id) + gt_ans = self.process(res["gt_response"]) + pred_ans = self.process(res["pred_response"]) + # assert gt_ans != '' + + if gt_ans == '': + continue + + if pred_ans == '': + s = 0 + else: + if len(pred_ans) > 512: + pred_ans = pred_ans[0: 512] + s = rouge.get_scores(pred_ans, gt_ans)[0]['rouge-l']['f'] + acc['f'].append(s) + eval_list.append({'id':str(sample_id),'score':str(round(s,3))}) + results = {'Rouge-L f': np.mean(acc['f'])} + return results,eval_list + + + def judge_multi_choice(self,sample): + sample_id = sample['sample_id'] + gt_ans = sample["gt_response"] + pred_ans = sample["pred_response"] + + if ":" in pred_ans: + a_list = pred_ans.split(":") + a_list = [a.strip() for a in a_list ] + for a in a_list: + if len(a) == 1 and a[-1] in ["a", "b", "c", "d", "e", "f", "g", "h"]: + pred_ans = a + + if pred_ans == gt_ans: + return 1 + else: + return 0 + + def process_sample(self,sample): + sample["gt_response"] = self.process(sample["gt_response"]) + sample["pred_response"] = self.process(sample["pred_response"]) + + def evaluate_multichoice(self, preditions): + correct = 0 + eval_list = [] + for i, sample in enumerate(preditions): + self.process_sample(sample) + score = self.judge_multi_choice(sample) + sample_id = sample['sample_id'] + sample['result'] = score + eval_list.append({'id':str(sample_id),'score':str(score)}) + correct+=score + return {'Accuracy':correct/len(preditions)},eval_list + + def evaluate_multi_choice_image(self,preditions): + correct = 0 + eval_list = [] + for i,sample in enumerate(preditions): + gt_ans = self.process(sample["gt_response"]) + pred_ans = self.process(sample["pred_response"]) + sample_id = sample['sample_id'] + + if ":" in pred_ans: + a_list = pred_ans.split(":") + a_list = [a.strip() for a in a_list ] + for a in a_list: + if len(a) == 1 and a[-1] in ["a", "b", "c", "d", "e", "f", "g", "h"]: + pred_ans = a + + if gt_ans == pred_ans: + score = 1 + else: + score = 0 + sample_id = sample['sample_id'] + sample['result'] = score + eval_list.append({'id':str(sample_id),'score':str(score)}) + correct+=score + return {'Accuracy':correct/len(preditions)},eval_list + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument('--result-dir', type=str, required=True) + + args = parser.parse_args() + + result_file = os.path.join(args.result_dir, "result.jsonl") + + if not os.path.exists(result_file): + print('No prediction file found') + exit(0) + with open(result_file, 'r') as f: + preds_all = [json.loads(line) for line in f] + + preds_all_dict = dict() + for pred in preds_all: + if pred["dataset"] not in preds_all_dict: + preds_all_dict[pred["dataset"]] = list() + preds_all_dict[pred["dataset"]].append(pred) + + image_choice_dataset_list = ["recipeqa-RecipeQA_VisualCloze", "RecipeQA_ImageCoherence", "COMICS_Panel"] + E = Eval() + + eval_result_list = dict() + eval_result_list_detail = dict() + + for dataset in preds_all_dict: + + preds = preds_all_dict[dataset] + question_type = preds[0]["question_type"] + + if question_type == 'open-ended': + eval_result, eval_list = E.evaluate_rouge(preds) + + elif question_type == 'multi-choice' or dataset == 'nlrv2': + if dataset in image_choice_dataset_list: + eval_result, eval_list = E.evaluate_multi_choice_image(preds) + else: + eval_result, eval_list = E.evaluate_multichoice(preds) + + else: + eval_result = 'Dataset not supported' + print('Dataset not supported') + exit(0) + + print(dataset, end = ': ') + print(eval_result) + + eval_result_list[dataset] = eval_result + eval_result_list_detail[dataset] = eval_list + + os.makedirs(args.result_dir, exist_ok=True) + with open(os.path.join(args.result_dir, 'eval_dataset.json'), 'w') as f: + json.dump(eval_result_list, f, indent=4) + + with open(os.path.join(args.result_dir,'eval_dataset_details.json'), 'w') as f: + json.dump(eval_result_list_detail, f, indent=4) + + + eval_cat_list = dict() + print() + + # spot_the_diff + score = 0 + count = 0 + for dataset in eval_result_list: + if dataset in spot_the_diff: + count += 1 + score += list(eval_result_list[dataset].values())[0] + if count > 0: + score /= count + eval_cat_list["spot_the_diff"] = score + print("spot_the_diff", end = ': ') + print('{:.2f}'.format(100 * score)) + + # image_edit_instruct + score = 0 + count = 0 + for dataset in eval_result_list: + if dataset in image_edit_instruct: + count += 1 + score += list(eval_result_list[dataset].values())[0] + if count > 0: + score /= count + eval_cat_list["image_edit_instruct"] = score + print("image_edit_instruct", end = ': ') + print('{:.2f}'.format(100 * score)) + + # visual_story_telling + score = 0 + count = 0 + for dataset in eval_result_list: + if dataset in visual_story_telling: + count += 1 + score += list(eval_result_list[dataset].values())[0] + if count > 0: + score /= count + eval_cat_list["visual_story_telling"] = score + print("visual_story_telling", end = ': ') + print('{:.2f}'.format(100 * score)) + + # visual_cloze + score = 0 + count = 0 + for dataset in eval_result_list: + if dataset in visual_cloze: + count += 1 + score += list(eval_result_list[dataset].values())[0] + if count > 0: + score /= count + eval_cat_list["visual_cloze"] = score + print("visual_cloze", end = ': ') + print('{:.2f}'.format(100 * score)) + + # text_rich_vqa + score = 0 + count = 0 + for dataset in eval_result_list: + if dataset in text_rich_vqa: + count += 1 + score += list(eval_result_list[dataset].values())[0] + if count > 0: + score /= count + eval_cat_list["text_rich_vqa"] = score + print("text_rich_vqa", end = ': ') + print('{:.2f}'.format(100 * score)) + + # multi_image_vqa + score = 0 + count = 0 + for dataset in eval_result_list: + if dataset in multi_image_vqa: + count += 1 + score += list(eval_result_list[dataset].values())[0] + if count > 0: + score /= count + eval_cat_list["multi_image_vqa"] = score + print("multi_image_vqa", end = ': ') + print('{:.2f}'.format(100 * score)) + + # puzzle + score = 0 + count = 0 + for dataset in eval_result_list: + if dataset in puzzle: + count += 1 + score += list(eval_result_list[dataset].values())[0] + if count > 0: + score /= count + eval_cat_list["puzzle"] = score + print("puzzle", end = ': ') + print('{:.2f}'.format(100 * score)) + + # nlrv2 + score = 0 + count = 0 + for dataset in eval_result_list: + if dataset in nlrv2: + count += 1 + score += list(eval_result_list[dataset].values())[0] + if count > 0: + score /= count + eval_cat_list["nlrv2"] = score + print("nlrv2", end = ': ') + print('{:.2f}'.format(100 * score)) + + # qbench + score = 0 + count = 0 + for dataset in eval_result_list: + if dataset in qbench: + count += 1 + score += list(eval_result_list[dataset].values())[0] + if count > 0: + score /= count + eval_cat_list["qbench"] = score + print("qbench", end = ': ') + print('{:.2f}'.format(100 * score)) + + with open(os.path.join(args.result_dir,'eval_cat.json'), 'w') as f: + json.dump(eval_cat_list, f, indent=4) \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/eval/model_vqa.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/eval/model_vqa.py" new file mode 100644 index 0000000000000000000000000000000000000000..2ebceedafe23eaf90e51e0971fbdfcae45555838 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/eval/model_vqa.py" @@ -0,0 +1,240 @@ +import argparse +import torch +import os +import json +from tqdm import tqdm +import shortuuid + +from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.conversation import conv_templates, SeparatorStyle +from llava.model.builder import load_pretrained_model +from llava.utils import disable_torch_init +from llava.mm_utils import tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria + +from llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN, IMAGE_TOKEN_INDEX +from typing import Dict, Optional, Sequence, List +import transformers +import re + +from PIL import Image +import math + + +def split_list(lst, n): + """Split a list into n (roughly) equal-sized chunks""" + chunk_size = math.ceil(len(lst) / n) # integer division + return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] + + +def get_chunk(lst, n, k): + chunks = split_list(lst, n) + return chunks[k] + +def preprocess_qwen(sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, max_len=2048, system_message: str = "You are a helpful assistant.") -> Dict: + roles = {"human": "<|im_start|>user", "gpt": "<|im_start|>assistant"} + + im_start, im_end = tokenizer.additional_special_tokens_ids + nl_tokens = tokenizer("\n").input_ids + _system = tokenizer("system").input_ids + nl_tokens + _user = tokenizer("user").input_ids + nl_tokens + _assistant = tokenizer("assistant").input_ids + nl_tokens + + # Apply prompt templates + input_ids, targets = [], [] + + source = sources + if roles[source[0]["from"]] != roles["human"]: + source = source[1:] + + input_id, target = [], [] + system = [im_start] + _system + tokenizer(system_message).input_ids + [im_end] + nl_tokens + input_id += system + target += [im_start] + [IGNORE_INDEX] * (len(system) - 3) + [im_end] + nl_tokens + assert len(input_id) == len(target) + for j, sentence in enumerate(source): + role = roles[sentence["from"]] + if has_image and sentence["value"] is not None and "" in sentence["value"]: + num_image = len(re.findall(DEFAULT_IMAGE_TOKEN, sentence["value"])) + texts = sentence["value"].split('') + _input_id = tokenizer(role).input_ids + nl_tokens + for i,text in enumerate(texts): + _input_id += tokenizer(text).input_ids + if iuser": + _target = [im_start] + [IGNORE_INDEX] * (len(_input_id) - 3) + [im_end] + nl_tokens + elif role == "<|im_start|>assistant": + _target = [im_start] + [IGNORE_INDEX] * len(tokenizer(role).input_ids) + _input_id[len(tokenizer(role).input_ids) + 1 : -2] + [im_end] + nl_tokens + else: + raise NotImplementedError + target += _target + + input_ids.append(input_id) + targets.append(target) + input_ids = torch.tensor(input_ids, dtype=torch.long) + targets = torch.tensor(targets, dtype=torch.long) + return input_ids + +def eval_model(args): + + # Model + disable_torch_init() + model_path = os.path.expanduser(args.model_path) + model_name = get_model_name_from_path(model_path) + tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, args.model_base, model_name) + + # Data + with open(os.path.expanduser(args.question_file)) as f: + questions = json.load(f) + questions = get_chunk(questions, args.num_chunks, args.chunk_idx) + answers_file = os.path.expanduser(args.answers_file) + os.makedirs(os.path.dirname(answers_file), exist_ok=True) + ans_file = open(answers_file, "w") + + for line in tqdm(questions): + idx = line["sample_id"] + question_type = line["metadata"]["question_type"] + dataset_name = line["metadata"]["dataset"] + gt = line["conversations"][1]["value"] + + image_files = line["image"] + qs = line["conversations"][0]["value"] + cur_prompt = args.extra_prompt + qs + + args.conv_mode = "qwen_1_5" + + conv = conv_templates[args.conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + input_ids = preprocess_qwen([line["conversations"][0],{'from': 'gpt','value': None}], tokenizer, has_image=True).cuda() + img_num = list(input_ids.squeeze()).count(IMAGE_TOKEN_INDEX) + + image_tensors = [] + for image_file in image_files: + image = Image.open(os.path.join(args.image_folder, image_file)) + image_tensor = image_processor.preprocess(image, return_tensors='pt')['pixel_values'] + image_tensors.append(image_tensor.half().cuda()) + # image_tensors = torch.cat(image_tensors, dim=0) + + stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 + keywords = [stop_str] + stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids) + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=image_tensors, + do_sample=True if args.temperature > 0 else False, + temperature=args.temperature, + top_p=args.top_p, + num_beams=args.num_beams, + # no_repeat_ngram_size=3, + max_new_tokens=1024, + use_cache=True) + + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0] + outputs = outputs.strip() + if outputs.endswith(stop_str): + outputs = outputs[:-len(stop_str)] + outputs = outputs.strip() + + ans_id = shortuuid.uuid() + ans_file.write(json.dumps({ + "dataset": dataset_name, + "sample_id": idx, + "prompt": cur_prompt, + "pred_response": outputs, + "gt_response": gt, + "shortuuid": ans_id, + "model_id": model_name, + "question_type": question_type, + }) + "\n") + ans_file.flush() + + if len(line["conversations"]) > 2: + + for i in range(2, len(line["conversations"]), 2): + input_ids = torch.cat((input_ids, output_ids), dim=1) + + gt = line["conversations"][i + 1]["value"] + qs = line["conversations"][i]["value"] + cur_prompt = args.extra_prompt + qs + + args.conv_mode = "qwen_1_5" + + conv = conv_templates[args.conv_mode].copy() + conv.append_message(conv.roles[0], qs) + conv.append_message(conv.roles[1], None) + prompt = conv.get_prompt() + + input_ids_new = preprocess_qwen([line["conversations"][i],{'from': 'gpt','value': None}], tokenizer, has_image=True).cuda() + input_ids = torch.cat((input_ids, input_ids_new), dim=1) + img_num = list(input_ids_new.squeeze()).count(IMAGE_TOKEN_INDEX) + + stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 + keywords = [stop_str] + stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids) + + with torch.inference_mode(): + output_ids = model.generate( + input_ids, + images=image_tensors, + do_sample=True if args.temperature > 0 else False, + temperature=args.temperature, + top_p=args.top_p, + num_beams=args.num_beams, + # no_repeat_ngram_size=3, + max_new_tokens=1024, + use_cache=True) + + outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0] + outputs = outputs.strip() + if outputs.endswith(stop_str): + outputs = outputs[:-len(stop_str)] + outputs = outputs.strip() + + ans_id = shortuuid.uuid() + ans_file.write(json.dumps({ + "dataset": dataset_name, + "sample_id": idx, + "prompt": cur_prompt, + "pred_response": outputs, + "gt_response": gt, + "shortuuid": ans_id, + "model_id": model_name, + "question_type": question_type, + }) + "\n") + ans_file.flush() + + + ans_file.close() + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--model-path", type=str, default="facebook/opt-350m") + parser.add_argument("--model-base", type=str, default=None) + parser.add_argument("--image-folder", type=str, default="") + parser.add_argument("--extra-prompt", type=str, default="") + parser.add_argument("--question-file", type=str, default="tables/question.jsonl") + parser.add_argument("--answers-file", type=str, default="answer.jsonl") + parser.add_argument("--conv-mode", type=str, default="llava_v1") + parser.add_argument("--num-chunks", type=int, default=1) + parser.add_argument("--chunk-idx", type=int, default=0) + parser.add_argument("--temperature", type=float, default=0.2) + parser.add_argument("--top_p", type=float, default=None) + parser.add_argument("--num_beams", type=int, default=1) + parser.add_argument("--test_size", type=int, default=10000000) + args = parser.parse_args() + + eval_model(args) \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_gemma.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_gemma.py" new file mode 100644 index 0000000000000000000000000000000000000000..5c0ac173017034bbbb03b158067d4e4f7ff970f6 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_gemma.py" @@ -0,0 +1,122 @@ +# Copyright 2024 Duc Q. Nguyen, Haotian Liu and Bo Li +# +# 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 List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from torch.nn import CrossEntropyLoss + +from transformers import AutoConfig, AutoModelForCausalLM, GemmaConfig, GemmaModel, GemmaForCausalLM + +from transformers.modeling_outputs import CausalLMOutputWithPast +from transformers.generation.utils import GenerateOutput + +from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM + + +class LlavaGemmaConfig(GemmaConfig): + model_type = "llava_gemma" + + +class LlavaGemmaModel(LlavaMetaModel, GemmaModel): + config_class = LlavaGemmaConfig + + def __init__(self, config: GemmaConfig): + super(LlavaGemmaModel, self).__init__(config) + + +class LlavaGemmaForCausalLM(GemmaForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaGemmaConfig + + def __init__(self, config): + super(GemmaForCausalLM, self).__init__(config) + self.model = LlavaGemmaModel(config) + + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + images: Optional[torch.FloatTensor] = None, + image_sizes: Optional[List[List[int]]] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + + if inputs_embeds is None: + (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, image_sizes) + + return super().forward( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + cache_position=cache_position, + ) + + @torch.no_grad() + def generate( + self, + inputs: Optional[torch.Tensor] = None, + images: Optional[torch.Tensor] = None, + image_sizes: Optional[torch.Tensor] = None, + **kwargs, + ) -> Union[GenerateOutput, torch.LongTensor]: + position_ids = kwargs.pop("position_ids", None) + attention_mask = kwargs.pop("attention_mask", None) + if "inputs_embeds" in kwargs: + raise NotImplementedError("`inputs_embeds` is not supported") + + if images is not None: + (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, image_sizes=image_sizes) + else: + inputs_embeds = self.get_model().embed_tokens(inputs) + + return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + image_sizes = kwargs.pop("image_sizes", None) + inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs) + if images is not None: + inputs["images"] = images + if image_sizes is not None: + inputs["image_sizes"] = image_sizes + return inputs + + +AutoConfig.register("llava_gemma", LlavaGemmaConfig) +AutoModelForCausalLM.register(LlavaGemmaConfig, LlavaGemmaForCausalLM) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_llama.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_llama.py" new file mode 100644 index 0000000000000000000000000000000000000000..1a930e97ddee3eda14c226118b51ea42a712de78 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_llama.py" @@ -0,0 +1,156 @@ +# Copyright 2023 Haotian Liu +# +# 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 List, Optional, Tuple, Union + +import torch +import torch.nn as nn + +from transformers import AutoConfig, AutoModelForCausalLM, LlamaConfig + +from torch.nn import CrossEntropyLoss + + +# , LlamaModel, LlamaForCausalLM, GenerationConfig +# from .modeling_llama import LlamaModel, LlamaForCausalLM +from transformers import LlamaModel, LlamaForCausalLM +from transformers.modeling_outputs import CausalLMOutputWithPast +from transformers.generation.utils import GenerateOutput + +from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM + + +class LlavaConfig(LlamaConfig): + model_type = "llava_llama" + temperature: float = 0.0 # reset to 0.0, previously 0.9 for Vicuna + max_new_tokens: int = 1024 + do_sample: bool = False + top_p: Optional[float] = None + # rope_scaling: Optional[dict] = {} + + +class LlavaLlamaModel(LlavaMetaModel, LlamaModel): + config_class = LlavaConfig + + def __init__(self, config: LlamaConfig): + super(LlavaLlamaModel, self).__init__(config) + + +class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaConfig + + def __init__(self, config): + LlamaForCausalLM.__init__(self, config) + + # configure default generation settings + config.model_type = "llava_llama" + # config.rope_scaling = None + + self.model = LlavaLlamaModel(config) + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + images: Optional[torch.FloatTensor] = None, + image_sizes: Optional[List[List[int]]] = None, + return_dict: Optional[bool] = None, + modalities: Optional[List[str]] = ["image"], + dpo_forward: Optional[bool] = None, + cache_position=None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + + if inputs_embeds is None: + (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes) + + if dpo_forward: + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + return logits, labels + + else: + return super().forward( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + @torch.no_grad() + def generate( + self, + inputs: Optional[torch.Tensor] = None, + images: Optional[torch.Tensor] = None, + image_sizes: Optional[torch.Tensor] = None, + modalities: Optional[List[str]] = ["image"], + **kwargs, + ) -> Union[GenerateOutput, torch.LongTensor]: + modalities = kwargs.pop("modalities", None) if "modalities" in kwargs and modalities is None else modalities + position_ids = kwargs.pop("position_ids", None) + attention_mask = kwargs.pop("attention_mask", None) + if "inputs_embeds" in kwargs: + raise NotImplementedError("`inputs_embeds` is not supported") + + if images is not None: + (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes) + else: + inputs_embeds = self.get_model().embed_tokens(inputs) + + return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + image_sizes = kwargs.pop("image_sizes", None) + inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs) + if images is not None: + inputs["images"] = images + if image_sizes is not None: + inputs["image_sizes"] = image_sizes + return inputs + + +AutoConfig.register("llava_llama", LlavaConfig) +AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_mistral.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_mistral.py" new file mode 100644 index 0000000000000000000000000000000000000000..2cc3b0157be23db5ed4aab0c0802f40b4702e116 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_mistral.py" @@ -0,0 +1,127 @@ +# Copyright 2023 Haotian Liu +# +# 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 List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from torch.nn import CrossEntropyLoss + +from transformers import AutoConfig, AutoModelForCausalLM, MistralConfig, MistralModel, MistralForCausalLM, GenerationConfig + +from transformers.modeling_outputs import CausalLMOutputWithPast +from transformers.generation.utils import GenerateOutput + +from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM + + +class LlavaMistralConfig(MistralConfig): + model_type = "llava_mistral" + temperature: float = 0.0 # reset to 0.0, previously 0.9 for Vicuna + max_new_tokens: int = 1024 + do_sample: bool = False + top_p: Optional[float] = None + + +class LlavaMistralModel(LlavaMetaModel, MistralModel): + config_class = LlavaMistralConfig + + def __init__(self, config: MistralConfig): + super(LlavaMistralModel, self).__init__(config) + + +class LlavaMistralForCausalLM(MistralForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaMistralConfig + + def __init__(self, config): + super(MistralForCausalLM, self).__init__(config) + + config.model_type = "llava_mistral" + config.rope_scaling = None + + self.model = LlavaMistralModel(config) + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + images: Optional[torch.FloatTensor] = None, + image_sizes: Optional[List[List[int]]] = None, + return_dict: Optional[bool] = None, + cache_position=None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + + if inputs_embeds is None: + (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, image_sizes) + + return super().forward( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + @torch.no_grad() + def generate( + self, + inputs: Optional[torch.Tensor] = None, + images: Optional[torch.Tensor] = None, + image_sizes: Optional[torch.Tensor] = None, + **kwargs, + ) -> Union[GenerateOutput, torch.LongTensor]: + position_ids = kwargs.pop("position_ids", None) + attention_mask = kwargs.pop("attention_mask", None) + if "inputs_embeds" in kwargs: + raise NotImplementedError("`inputs_embeds` is not supported") + + if images is not None: + (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, image_sizes=image_sizes) + else: + inputs_embeds = self.get_model().embed_tokens(inputs) + + return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + image_sizes = kwargs.pop("image_sizes", None) + inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs) + if images is not None: + inputs["images"] = images + if image_sizes is not None: + inputs["image_sizes"] = image_sizes + return inputs + + +AutoConfig.register("llava_mistral", LlavaMistralConfig) +AutoModelForCausalLM.register(LlavaMistralConfig, LlavaMistralForCausalLM) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_mixtral.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_mixtral.py" new file mode 100644 index 0000000000000000000000000000000000000000..ca6c25da47a1a7fbb21db1e4a5406cbfbe4242c6 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_mixtral.py" @@ -0,0 +1,143 @@ +# Copyright 2023 Haotian Liu +# +# 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 List, Optional, Tuple, Union + +import torch +import torch.nn as nn +from torch.nn import CrossEntropyLoss + +from transformers import AutoConfig, AutoModelForCausalLM, MixtralConfig, MixtralModel, MixtralForCausalLM, GenerationConfig + +from transformers.modeling_outputs import CausalLMOutputWithPast +from transformers.generation.utils import GenerateOutput + +from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM + + +class LlavaMixtralConfig(MixtralConfig): + model_type = "llava_mixtral" + + +class LlavaMixtralModel(LlavaMetaModel, MixtralModel): + config_class = LlavaMixtralConfig + + def __init__(self, config: MixtralConfig): + super(LlavaMixtralModel, self).__init__(config) + + +class LlavaMixtralForCausalLM(MixtralForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaMixtralConfig + + def __init__(self, config): + super(MixtralForCausalLM, self).__init__(config) + + config.model_type = "llava_mixtral" + config.rope_scaling = None + self.model = LlavaMixtralModel(config) + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + images: Optional[torch.FloatTensor] = None, + image_sizes: Optional[List[List[int]]] = None, + return_dict: Optional[bool] = None, + modalities: Optional[List[str]] = ["image"], + dpo_forward: Optional[bool] = None, + cache_position=None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + + if inputs_embeds is None: + (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes) + + if dpo_forward: + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + return logits, labels + + else: + return super().forward( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + @torch.no_grad() + def generate( + self, + inputs: Optional[torch.Tensor] = None, + images: Optional[torch.Tensor] = None, + image_sizes: Optional[torch.Tensor] = None, + modalities: Optional[List[str]] = ["image"], + **kwargs, + ) -> Union[GenerateOutput, torch.LongTensor]: + position_ids = kwargs.pop("position_ids", None) + attention_mask = kwargs.pop("attention_mask", None) + if "inputs_embeds" in kwargs: + raise NotImplementedError("`inputs_embeds` is not supported") + + if images is not None: + (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes) + else: + inputs_embeds = self.get_model().embed_tokens(inputs) + + return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + image_sizes = kwargs.pop("image_sizes", None) + inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs) + if images is not None: + inputs["images"] = images + if image_sizes is not None: + inputs["image_sizes"] = image_sizes + return inputs + + +AutoConfig.register("llava_mixtral", LlavaMixtralConfig) +AutoModelForCausalLM.register(LlavaMixtralConfig, LlavaMixtralForCausalLM) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_mpt.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_mpt.py" new file mode 100644 index 0000000000000000000000000000000000000000..c3bce7d37e9c0bff41cf8a5fe2f99d29d7cc4495 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_mpt.py" @@ -0,0 +1,105 @@ +# Copyright 2023 Haotian Liu +# +# 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, Tuple + +import torch + +from transformers import AutoConfig, AutoModelForCausalLM, MptConfig, MptForCausalLM, MptModel, GenerationConfig +from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM + + +class LlavaMptConfig(MptConfig): + model_type = "llava_mpt" + + +class LlavaMptModel(LlavaMetaModel, MptModel): + config_class = LlavaMptConfig + + def __init__(self, config: MptConfig): + config.hidden_size = config.d_model + super(LlavaMptModel, self).__init__(config) + + def embed_tokens(self, x): + return self.wte(x) + + +class LlavaMptForCausalLM(MptForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaMptConfig + supports_gradient_checkpointing = True + + def __init__(self, config): + super(MptForCausalLM, self).__init__(config) + + config.model_type = "llava_mpt" + config.rope_scaling = None + self.generation_config = GenerationConfig( + temperature=0.0, + max_new_tokens=1024, + do_sample=False, + top_p=None, + ) + + self.transformer = LlavaMptModel(config) + self.lm_head = torch.nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.transformer + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, LlavaMptModel): + module.gradient_checkpointing = value + + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None, + attention_mask: Optional[torch.Tensor] = None, + inputs_embeds: Optional[torch.Tensor] = None, + labels: Optional[torch.Tensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position=None, + images=None, + ): + + input_ids, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images) + + return super().forward( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + _inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs) + _inputs["images"] = images + return _inputs + + +AutoConfig.register("llava_mpt", LlavaMptConfig) +AutoModelForCausalLM.register(LlavaMptConfig, LlavaMptForCausalLM) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_qwen.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_qwen.py" new file mode 100644 index 0000000000000000000000000000000000000000..c19474761e875b10ce0d523404f85a4be313c205 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_qwen.py" @@ -0,0 +1,149 @@ +# Copyright 2024 Hao Zhang +# +# 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 List, Optional, Tuple, Union, Dict +import torch +import torch.nn as nn +from torch.nn import CrossEntropyLoss + +import transformers +from transformers import AutoConfig, AutoModelForCausalLM, LlamaConfig, LlamaModel, LlamaForCausalLM + +from transformers.modeling_outputs import CausalLMOutputWithPast +from transformers.generation.utils import GenerateOutput + +# from ...constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM +from transformers import Qwen2Config, Qwen2Model, Qwen2ForCausalLM + +# from .qwen.modeling_qwen import QWenLMHeadModel, QWenModel +# from .qwen.configuration_qwen import QWenConfig + + +class LlavaQwenConfig(Qwen2Config): + model_type = "llava_qwen" + + +class LlavaQwenModel(LlavaMetaModel, Qwen2Model): + config_class = LlavaQwenConfig + + def __init__(self, config: Qwen2Config): + super(LlavaQwenModel, self).__init__(config) + + +class LlavaQwenForCausalLM(Qwen2ForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaQwenConfig + + def __init__(self, config): + # super(Qwen2ForCausalLM, self).__init__(config) + Qwen2ForCausalLM.__init__(self, config) + config.model_type = "llava_qwen" + config.rope_scaling = None + + self.model = LlavaQwenModel(config) + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + images: Optional[torch.FloatTensor] = None, + image_sizes: Optional[List[List[int]]] = None, + return_dict: Optional[bool] = None, + modalities: Optional[List[str]] = ["image"], + dpo_forward: Optional[bool] = False, + cache_position=None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + + if inputs_embeds is None: + (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes) + + if dpo_forward: + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + return logits, labels + + else: + return super().forward( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + @torch.no_grad() + def generate( + self, + inputs: Optional[torch.Tensor] = None, + images: Optional[torch.Tensor] = None, + image_sizes: Optional[torch.Tensor] = None, + modalities: Optional[List[str]] = ["image"], + **kwargs, + ) -> Union[GenerateOutput, torch.LongTensor]: + position_ids = kwargs.pop("position_ids", None) + attention_mask = kwargs.pop("attention_mask", None) + if "inputs_embeds" in kwargs: + raise NotImplementedError("`inputs_embeds` is not supported") + + if images is not None: + (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes) + else: + inputs_embeds = self.get_model().embed_tokens(inputs) + + return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + image_sizes = kwargs.pop("image_sizes", None) + inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs) + if images is not None: + inputs["images"] = images + if image_sizes is not None: + inputs["image_sizes"] = image_sizes + return inputs + + +AutoConfig.register("llava_qwen", LlavaQwenConfig) +AutoModelForCausalLM.register(LlavaQwenConfig, LlavaQwenForCausalLM) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_qwen_moe.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_qwen_moe.py" new file mode 100644 index 0000000000000000000000000000000000000000..618a482234d1b59eeb136063783a4111c2768fe8 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/llava_qwen_moe.py" @@ -0,0 +1,149 @@ +# Copyright 2024 Hao Zhang +# +# 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 List, Optional, Tuple, Union, Dict +import torch +import torch.nn as nn +from torch.nn import CrossEntropyLoss + +import transformers +from transformers import AutoConfig, AutoModelForCausalLM + +from transformers.modeling_outputs import CausalLMOutputWithPast +from transformers.generation.utils import GenerateOutput + +# from ...constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN +from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM +from transformers import Qwen2MoeConfig, Qwen2MoeModel, Qwen2MoeForCausalLM + +# from .qwen.modeling_qwen import QWenLMHeadModel, QWenModel +# from .qwen.configuration_qwen import QWenConfig + + +class LlavaQwenMoeConfig(Qwen2MoeConfig): + model_type = "llava_qwen_moe" + + +class LlavaQwenMoeModel(LlavaMetaModel, Qwen2MoeModel): + config_class = LlavaQwenMoeConfig + + def __init__(self, config: Qwen2MoeConfig): + super(LlavaQwenMoeModel, self).__init__(config) + + +class LlavaQwenMoeForCausalLM(Qwen2MoeForCausalLM, LlavaMetaForCausalLM): + config_class = LlavaQwenMoeConfig + + def __init__(self, config): + # super(Qwen2MoeForCausalLM, self).__init__(config) + Qwen2MoeForCausalLM.__init__(self, config) + config.model_type = "llava_qwen_moe" + config.rope_scaling = None + + self.model = LlavaQwenMoeModel(config) + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + # Initialize weights and apply final processing + self.post_init() + + def get_model(self): + return self.model + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + images: Optional[torch.FloatTensor] = None, + image_sizes: Optional[List[List[int]]] = None, + return_dict: Optional[bool] = None, + modalities: Optional[List[str]] = ["image"], + dpo_forward: Optional[bool] = False, + cache_position=None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + + if inputs_embeds is None: + (input_ids, position_ids, attention_mask, past_key_values, inputs_embeds, labels) = self.prepare_inputs_labels_for_multimodal(input_ids, position_ids, attention_mask, past_key_values, labels, images, modalities, image_sizes) + + if dpo_forward: + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + return logits, labels + + else: + return super().forward( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + labels=labels, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + @torch.no_grad() + def generate( + self, + inputs: Optional[torch.Tensor] = None, + images: Optional[torch.Tensor] = None, + image_sizes: Optional[torch.Tensor] = None, + modalities: Optional[List[str]] = ["image"], + **kwargs, + ) -> Union[GenerateOutput, torch.LongTensor]: + position_ids = kwargs.pop("position_ids", None) + attention_mask = kwargs.pop("attention_mask", None) + if "inputs_embeds" in kwargs: + raise NotImplementedError("`inputs_embeds` is not supported") + + if images is not None: + (inputs, position_ids, attention_mask, _, inputs_embeds, _) = self.prepare_inputs_labels_for_multimodal(inputs, position_ids, attention_mask, None, None, images, modalities, image_sizes=image_sizes) + else: + inputs_embeds = self.get_model().embed_tokens(inputs) + + return super().generate(position_ids=position_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs): + images = kwargs.pop("images", None) + image_sizes = kwargs.pop("image_sizes", None) + inputs = super().prepare_inputs_for_generation(input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs) + if images is not None: + inputs["images"] = images + if image_sizes is not None: + inputs["image_sizes"] = image_sizes + return inputs + + +AutoConfig.register("llava_qwen_moe", LlavaQwenMoeConfig) +AutoModelForCausalLM.register(LlavaQwenMoeConfig, LlavaQwenMoeForCausalLM) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/modeling_llama.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/modeling_llama.py" new file mode 100644 index 0000000000000000000000000000000000000000..0d93738b9dcde4c7b61df79ec577ed3e13edf4ed --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/language_model/modeling_llama.py" @@ -0,0 +1,1649 @@ +# coding=utf-8 +# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. +# +# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX +# and OPT implementations in this library. It has been modified from its +# original forms to accommodate minor architectural differences compared +# to GPT-NeoX and OPT used by the Meta AI team that trained the model. +# +# 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. +""" PyTorch LLaMA model.""" +import math +import warnings +from typing import List, Optional, Tuple, Union + +import torch +import torch.nn.functional as F +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +from transformers.activations import ACT2FN +from transformers.cache_utils import Cache, DynamicCache, StaticCache +from transformers.modeling_outputs import ( + BaseModelOutputWithPast, + CausalLMOutputWithPast, + QuestionAnsweringModelOutput, + SequenceClassifierOutputWithPast, +) +from transformers.modeling_utils import PreTrainedModel +from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS +from transformers.utils import ( + add_start_docstrings, + add_start_docstrings_to_model_forward, + is_flash_attn_2_available, + is_flash_attn_greater_or_equal_2_10, + logging, + replace_return_docstrings, +) +from transformers.models.llama.configuration_llama import LlamaConfig + +if is_flash_attn_2_available(): + from flash_attn import flash_attn_func, flash_attn_varlen_func + from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa + + +logger = logging.get_logger(__name__) + +_CONFIG_FOR_DOC = "LlamaConfig" + + +def _get_unpad_data(attention_mask): + seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) + indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() + max_seqlen_in_batch = seqlens_in_batch.max().item() + cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) + return ( + indices, + cu_seqlens, + max_seqlen_in_batch, + ) + + +class LlamaRMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + """ + LlamaRMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states): + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return self.weight * hidden_states.to(input_dtype) + + +ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm) + + +class LlamaRotaryEmbedding(nn.Module): + def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): + super().__init__() + self.scaling_factor = scaling_factor + self.dim = dim + self.max_position_embeddings = max_position_embeddings + self.base = base + inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + # For BC we register cos and sin cached + self.max_seq_len_cached = max_position_embeddings + t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq) + t = t / self.scaling_factor + freqs = torch.outer(t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1) + self.register_buffer("_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False) + self.register_buffer("_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False) + + @property + def sin_cached(self): + logger.warning_once("The sin_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use " "the forward method of RoPE from now on instead. It is not used in the `LlamaAttention` class") + return self._sin_cached + + @property + def cos_cached(self): + logger.warning_once("The cos_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use " "the forward method of RoPE from now on instead. It is not used in the `LlamaAttention` class") + return self._cos_cached + + @torch.no_grad() + def forward(self, x, position_ids, seq_len=None): + if seq_len is not None: + logger.warning_once("The `seq_len` argument is deprecated and unused. It will be removed in v4.39.") + + # x: [bs, num_attention_heads, seq_len, head_size] + inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) + position_ids_expanded = position_ids[:, None, :].float() + # Force float32 since bfloat16 loses precision on long contexts + # See https://github.com/huggingface/transformers/pull/29285 + device_type = x.device.type + device_type = device_type if isinstance(device_type, str) else "cpu" + with torch.autocast(device_type=device_type, enabled=False): + freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) + emb = torch.cat((freqs, freqs), dim=-1) + cos = emb.cos() + sin = emb.sin() + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + + +class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding): + """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev""" + + def forward(self, x, position_ids, seq_len=None): + # difference to the original RoPE: a scaling factor is aplied to the position ids + position_ids = position_ids.float() / self.scaling_factor + cos, sin = super().forward(x, position_ids, seq_len) + return cos, sin + + +class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding): + """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla""" + + def forward(self, x, position_ids, seq_len=None): + # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length + seq_len = torch.max(position_ids) + 1 + if seq_len > self.max_position_embeddings: + base = self.base * ((self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)) ** (self.dim / (self.dim - 2)) + inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation + + cos, sin = super().forward(x, position_ids, seq_len) + return cos, sin + + +def rotate_half(x): + """Rotates half the hidden dims of the input.""" + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. + + Args: + q (`torch.Tensor`): The query tensor. + k (`torch.Tensor`): The key tensor. + cos (`torch.Tensor`): The cosine part of the rotary embedding. + sin (`torch.Tensor`): The sine part of the rotary embedding. + position_ids (`torch.Tensor`, *optional*): + Deprecated and unused. + unsqueeze_dim (`int`, *optional*, defaults to 1): + The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note + that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and + k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes + cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have + the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. + Returns: + `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. + """ + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + return q_embed, k_embed + + +class LlamaMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) + self.act_fn = ACT2FN[config.hidden_act] + + def forward(self, x): + if self.config.pretraining_tp > 1: + slice = self.intermediate_size // self.config.pretraining_tp + gate_proj_slices = self.gate_proj.weight.split(slice, dim=0) + up_proj_slices = self.up_proj.weight.split(slice, dim=0) + down_proj_slices = self.down_proj.weight.split(slice, dim=1) + + gate_proj = torch.cat([F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1) + up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1) + + intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2) + down_proj = [F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)] + down_proj = sum(down_proj) + else: + down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + + return down_proj + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +class LlamaAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None): + super().__init__() + self.config = config + self.layer_idx = layer_idx + if layer_idx is None: + logger.warning_once( + f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will " + "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` " + "when creating this class." + ) + + self.attention_dropout = config.attention_dropout + self.hidden_size = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = self.hidden_size // self.num_heads + self.num_key_value_heads = config.num_key_value_heads + self.num_key_value_groups = self.num_heads // self.num_key_value_heads + self.max_position_embeddings = config.max_position_embeddings + self.rope_theta = config.rope_theta + self.is_causal = True + + if (self.head_dim * self.num_heads) != self.hidden_size: + raise ValueError(f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" f" and `num_heads`: {self.num_heads}).") + + self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias) + self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias) + self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias) + self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias) + self._init_rope() + + def _init_rope(self): + if self.config.rope_scaling is None: + self.rotary_emb = LlamaRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + base=self.rope_theta, + ) + else: + scaling_type = self.config.rope_scaling["type"] + scaling_factor = self.config.rope_scaling["factor"] + if scaling_type == "linear": + self.rotary_emb = LlamaLinearScalingRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + scaling_factor=scaling_factor, + base=self.rope_theta, + ) + elif scaling_type == "dynamic": + self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + scaling_factor=scaling_factor, + base=self.rope_theta, + ) + else: + raise ValueError(f"Unknown RoPE scaling type {scaling_type}") + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + bsz, q_len, _ = hidden_states.size() + + if self.config.pretraining_tp > 1: + key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp + query_slices = self.q_proj.weight.split((self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0) + key_slices = self.k_proj.weight.split(key_value_slicing, dim=0) + value_slices = self.v_proj.weight.split(key_value_slicing, dim=0) + + query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)] + query_states = torch.cat(query_states, dim=-1) + + key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)] + key_states = torch.cat(key_states, dim=-1) + + value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)] + value_states = torch.cat(value_states, dim=-1) + + else: + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + past_key_value = getattr(self, "past_key_value", past_key_value) + cos, sin = self.rotary_emb(value_states, position_ids) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + + if past_key_value is not None: + # sin and cos are specific to RoPE models; position_ids needed for the static cache + cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) + + if attention_mask is not None: # no matter the length, we just slice it + causal_mask = attention_mask + if cache_position is not None: + causal_mask = attention_mask[:, :, cache_position, : key_states.shape[-2]] + attn_weights = attn_weights + causal_mask + + # upcast attention to fp32 + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) + attn_output = torch.matmul(attn_weights, value_states) + + if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): + raise ValueError(f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" f" {attn_output.size()}") + + attn_output = attn_output.transpose(1, 2).contiguous() + + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) + + if self.config.pretraining_tp > 1: + attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2) + o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1) + attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)]) + else: + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + +class LlamaRingFlashAttention2(LlamaAttention): + """ + Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays + untouched. The only required change would be on the forward pass where it needs to correctly call the public API of + flash attention and deal with padding tokens in case the input contains any of them. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. + # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. + # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). + self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + output_attentions = False + + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + # Flash attention requires the input to have the shape + # batch_size x seq_length x head_dim x hidden_dim + # therefore we just need to keep the original shape + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + cos, sin = self.rotary_emb(value_states, position_ids) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + + past_key_value = getattr(self, "past_key_value", past_key_value) + + if past_key_value is not None: + # sin and cos are specific to RoPE models; position_ids needed for the static cache + cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache + # to be able to avoid many of these transpose/reshape/view. + query_states = query_states.transpose(1, 2) + key_states = key_states.transpose(1, 2) + value_states = value_states.transpose(1, 2) + + dropout_rate = self.attention_dropout if self.training else 0.0 + + # In PEFT, usually we cast the layer norms in float32 for training stability reasons + # therefore the input hidden states gets silently casted in float32. Hence, we need + # cast them back in the correct dtype just to be sure everything works as expected. + # This might slowdown training & inference so it is recommended to not cast the LayerNorms + # in fp32. (LlamaRMSNorm handles it correctly) + + input_dtype = query_states.dtype + if input_dtype == torch.float32: + if torch.is_autocast_enabled(): + target_dtype = torch.get_autocast_gpu_dtype() + # Handle the case where the model is quantized + elif hasattr(self.config, "_pre_quantization_dtype"): + target_dtype = self.config._pre_quantization_dtype + else: + target_dtype = self.q_proj.weight.dtype + + logger.warning_once( + f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." + ) + + query_states = query_states.to(target_dtype) + key_states = key_states.to(target_dtype) + value_states = value_states.to(target_dtype) + + attn_output = self._flash_attention_forward(query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate) + + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + def _flash_attention_forward(self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None): + """ + Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token + first unpad the input, then computes the attention scores and pad the final attention scores. + + Args: + query_states (`torch.Tensor`): + Input query states to be passed to Flash Attention API + key_states (`torch.Tensor`): + Input key states to be passed to Flash Attention API + value_states (`torch.Tensor`): + Input value states to be passed to Flash Attention API + attention_mask (`torch.Tensor`): + The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the + position of padding tokens and 1 for the position of non-padding tokens. + dropout (`int`, *optional*): + Attention dropout + softmax_scale (`float`, *optional*): + The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) + """ + if not self._flash_attn_uses_top_left_mask: + causal = self.is_causal + else: + # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__. + causal = self.is_causal and query_length != 1 + + # Contains at least one padding token in the sequence + if attention_mask is not None: + batch_size = query_states.shape[0] + query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(query_states, key_states, value_states, attention_mask, query_length) + + cu_seqlens_q, cu_seqlens_k = cu_seq_lens + max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens + + attn_output_unpad = zigzag_ring_flash_attn_varlen_func( + query_states, + key_states, + value_states, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_in_batch_q, + max_seqlen_k=max_seqlen_in_batch_k, + dropout_p=dropout, + softmax_scale=softmax_scale, + causal=causal, + ) + + attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) + else: + # pack qkv + # query_states: (batch_size, seqlen, nheads, headdim) + # qkv: (batch_size, seqlen, 3, nheads, headdim) + qkv = torch.stack([query_states, key_states, value_states], dim=2) + attn_output = zigzag_ring_flash_attn_qkvpacked_func(qkv, dropout, softmax_scale, causal=causal) + + return attn_output + + def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length): + indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) + batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape + + key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k) + value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k) + if query_length == kv_seq_len: + query_layer = index_first_axis(query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k) + cu_seqlens_q = cu_seqlens_k + max_seqlen_in_batch_q = max_seqlen_in_batch_k + indices_q = indices_k + elif query_length == 1: + max_seqlen_in_batch_q = 1 + cu_seqlens_q = torch.arange(batch_size + 1, dtype=torch.int32, device=query_layer.device) # There is a memcpy here, that is very bad. + indices_q = cu_seqlens_q[:-1] + query_layer = query_layer.squeeze(1) + else: + # The -q_len: slice assumes left padding. + attention_mask = attention_mask[:, -query_length:] + query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask) + + return ( + query_layer, + key_layer, + value_layer, + indices_q, + (cu_seqlens_q, cu_seqlens_k), + (max_seqlen_in_batch_q, max_seqlen_in_batch_k), + ) + + +class LlamaFlashAttention2(LlamaAttention): + """ + Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays + untouched. The only required change would be on the forward pass where it needs to correctly call the public API of + flash attention and deal with padding tokens in case the input contains any of them. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. + # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. + # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). + self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + output_attentions = False + + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + # Flash attention requires the input to have the shape + # batch_size x seq_length x head_dim x hidden_dim + # therefore we just need to keep the original shape + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + cos, sin = self.rotary_emb(value_states, position_ids) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + + past_key_value = getattr(self, "past_key_value", past_key_value) + + if past_key_value is not None: + # sin and cos are specific to RoPE models; position_ids needed for the static cache + cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache + # to be able to avoid many of these transpose/reshape/view. + query_states = query_states.transpose(1, 2) + key_states = key_states.transpose(1, 2) + value_states = value_states.transpose(1, 2) + + dropout_rate = self.attention_dropout if self.training else 0.0 + + # In PEFT, usually we cast the layer norms in float32 for training stability reasons + # therefore the input hidden states gets silently casted in float32. Hence, we need + # cast them back in the correct dtype just to be sure everything works as expected. + # This might slowdown training & inference so it is recommended to not cast the LayerNorms + # in fp32. (LlamaRMSNorm handles it correctly) + + input_dtype = query_states.dtype + if input_dtype == torch.float32: + if torch.is_autocast_enabled(): + target_dtype = torch.get_autocast_gpu_dtype() + # Handle the case where the model is quantized + elif hasattr(self.config, "_pre_quantization_dtype"): + target_dtype = self.config._pre_quantization_dtype + else: + target_dtype = self.q_proj.weight.dtype + + logger.warning_once( + f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." + ) + + query_states = query_states.to(target_dtype) + key_states = key_states.to(target_dtype) + value_states = value_states.to(target_dtype) + + attn_output = self._flash_attention_forward(query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate) + + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + def _flash_attention_forward(self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None): + """ + Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token + first unpad the input, then computes the attention scores and pad the final attention scores. + + Args: + query_states (`torch.Tensor`): + Input query states to be passed to Flash Attention API + key_states (`torch.Tensor`): + Input key states to be passed to Flash Attention API + value_states (`torch.Tensor`): + Input value states to be passed to Flash Attention API + attention_mask (`torch.Tensor`): + The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the + position of padding tokens and 1 for the position of non-padding tokens. + dropout (`int`, *optional*): + Attention dropout + softmax_scale (`float`, *optional*): + The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) + """ + if not self._flash_attn_uses_top_left_mask: + causal = self.is_causal + else: + # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__. + causal = self.is_causal and query_length != 1 + + # Contains at least one padding token in the sequence + if attention_mask is not None: + batch_size = query_states.shape[0] + query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(query_states, key_states, value_states, attention_mask, query_length) + + cu_seqlens_q, cu_seqlens_k = cu_seq_lens + max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens + + attn_output_unpad = flash_attn_varlen_func( + query_states, + key_states, + value_states, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_in_batch_q, + max_seqlen_k=max_seqlen_in_batch_k, + dropout_p=dropout, + softmax_scale=softmax_scale, + causal=causal, + ) + + attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) + else: + attn_output = flash_attn_func(query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal) + + return attn_output + + def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length): + indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) + batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape + + key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k) + value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k) + if query_length == kv_seq_len: + query_layer = index_first_axis(query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k) + cu_seqlens_q = cu_seqlens_k + max_seqlen_in_batch_q = max_seqlen_in_batch_k + indices_q = indices_k + elif query_length == 1: + max_seqlen_in_batch_q = 1 + cu_seqlens_q = torch.arange(batch_size + 1, dtype=torch.int32, device=query_layer.device) # There is a memcpy here, that is very bad. + indices_q = cu_seqlens_q[:-1] + query_layer = query_layer.squeeze(1) + else: + # The -q_len: slice assumes left padding. + attention_mask = attention_mask[:, -query_length:] + query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask) + + return ( + query_layer, + key_layer, + value_layer, + indices_q, + (cu_seqlens_q, cu_seqlens_k), + (max_seqlen_in_batch_q, max_seqlen_in_batch_k), + ) + + +class LlamaSdpaAttention(LlamaAttention): + """ + Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from + `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to + SDPA API. + """ + + # Adapted from LlamaAttention.forward + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + cache_position: Optional[torch.LongTensor] = None, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if output_attentions: + # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented. + logger.warning_once( + "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, " + 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' + ) + return super().forward( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + cache_position=cache_position, + ) + + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + cos, sin = self.rotary_emb(value_states, position_ids) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + + # In case static cache is used, it is an instance attribute. + past_key_value = getattr(self, "past_key_value", past_key_value) + + if past_key_value is not None: + # sin and cos are specific to RoPE models; position_ids needed for the static cache + cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + causal_mask = attention_mask + if attention_mask is not None and cache_position is not None: + causal_mask = causal_mask[:, :, cache_position, : key_states.shape[-2]] + + # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask, + # Reference: https://github.com/pytorch/pytorch/issues/112577. + if query_states.device.type == "cuda" and causal_mask is not None: + query_states = query_states.contiguous() + key_states = key_states.contiguous() + value_states = value_states.contiguous() + + attn_output = torch.nn.functional.scaled_dot_product_attention( + query_states, + key_states, + value_states, + attn_mask=causal_mask, + dropout_p=self.attention_dropout if self.training else 0.0, + ) + + attn_output = attn_output.transpose(1, 2).contiguous() + attn_output = attn_output.view(bsz, q_len, self.hidden_size) + + attn_output = self.o_proj(attn_output) + + return attn_output, None, past_key_value + + +try: + from ring_flash_attn import zigzag_ring_flash_attn_qkvpacked_func, zigzag_ring_flash_attn_varlen_func +except ImportError: + print("Please install the ring-flash-attn package") + +LLAMA_ATTENTION_CLASSES = { + "eager": LlamaAttention, + "flash_attention_2": LlamaFlashAttention2, + "ring_flash_attention_2": LlamaRingFlashAttention2, + "sdpa": LlamaSdpaAttention, +} + + +class LlamaDecoderLayer(nn.Module): + def __init__(self, config: LlamaConfig, layer_idx: int): + super().__init__() + self.hidden_size = config.hidden_size + + self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx) + + self.mlp = LlamaMLP(config) + self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + cache_position: Optional[torch.LongTensor] = None, + **kwargs, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): + attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, + query_sequence_length, key_sequence_length)` if default attention is used. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + if "padding_mask" in kwargs: + warnings.warn("Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`") + + residual = hidden_states + + hidden_states = self.input_layernorm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + cache_position=cache_position, + **kwargs, + ) + hidden_states = residual + hidden_states + + # Fully Connected + residual = hidden_states + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +LLAMA_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`LlamaConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", + LLAMA_START_DOCSTRING, +) +class LlamaPreTrainedModel(PreTrainedModel): + config_class = LlamaConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["LlamaDecoderLayer"] + _skip_keys_device_placement = ["past_key_values", "causal_mask"] + _supports_flash_attn_2 = True + _supports_sdpa = True + _supports_cache_class = True + + def _init_weights(self, module): + std = self.config.initializer_range + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None): + if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache: + raise ValueError("`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` " "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers") + + if max_cache_len > self.model.causal_mask.shape[-1] or self.device != self.model.causal_mask.device: + causal_mask = torch.full((max_cache_len, max_cache_len), fill_value=True, device=self.device, dtype=torch.bool) + self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False) + + for layer in self.model.layers: + device = layer.input_layernorm.weight.device + if hasattr(self.config, "_pre_quantization_dtype"): + dtype = self.config._pre_quantization_dtype + else: + dtype = layer.self_attn.o_proj.weight.dtype + layer.self_attn.past_key_value = cache_cls(self.config, max_batch_size, max_cache_len, device=device, dtype=dtype) + + def _reset_cache(self): + for layer in self.model.layers: + layer.self_attn.past_key_value = None + + +LLAMA_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.n_positions - 1]`. + + [What are position IDs?](../glossary#position-ids) + past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): + Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` + returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`. + + Two formats are allowed: + - a [`~cache_utils.Cache`] instance; + - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy + cache format. + + The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the + legacy cache format will be returned. + + If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't + have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` + of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +@add_start_docstrings( + "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", + LLAMA_START_DOCSTRING, +) +class LlamaModel(LlamaPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`] + + Args: + config: LlamaConfig + """ + + def __init__(self, config: LlamaConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]) + self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.gradient_checkpointing = False + + # Register a causal mask to separate causal and padding mask creation. Merging happens in the attention class. + # NOTE: This is not friendly with TorchScript, ONNX, ExportedProgram serialization for very large `max_position_embeddings`. + causal_mask = torch.full((config.max_position_embeddings, config.max_position_embeddings), fill_value=True, dtype=torch.bool) + self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one") + + if self.gradient_checkpointing and self.training and use_cache: + logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.") + use_cache = False + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + past_seen_tokens = 0 + if use_cache: # kept for BC (cache positions) + if not isinstance(past_key_values, StaticCache): + past_key_values = DynamicCache.from_legacy_cache(past_key_values) + past_seen_tokens = past_key_values.get_seq_length() + + if cache_position is None: + if isinstance(past_key_values, StaticCache): + raise ValueError("cache_position is a required argument when using StaticCache.") + cache_position = torch.arange(past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device) + + if position_ids is None: + position_ids = cache_position.unsqueeze(0) + + causal_mask = self._update_causal_mask(attention_mask, inputs_embeds) + + # embed positions + hidden_states = inputs_embeds + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = None + + for decoder_layer in self.layers: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if self.gradient_checkpointing and self.training: + layer_outputs = self._gradient_checkpointing_func( + decoder_layer.__call__, + hidden_states, + causal_mask, + position_ids, + past_key_values, + output_attentions, + use_cache, + cache_position, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=causal_mask, + position_ids=position_ids, + past_key_value=past_key_values, + output_attentions=output_attentions, + use_cache=use_cache, + cache_position=cache_position, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache = layer_outputs[2 if output_attentions else 1] + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = None + if use_cache: + next_cache = next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static + # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes. + # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using + # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114 + def _update_causal_mask(self, attention_mask, input_tensor): + if self.config._attn_implementation == "flash_attention_2": + if attention_mask is not None and 0.0 in attention_mask: + return attention_mask + return None + + batch_size, seq_length = input_tensor.shape[:2] + dtype = input_tensor.dtype + device = input_tensor.device + + # support going beyond cached `max_position_embedding` + if seq_length > self.causal_mask.shape[-1]: + causal_mask = torch.full((2 * self.causal_mask.shape[-1], 2 * self.causal_mask.shape[-1]), fill_value=1) + self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False) + + # We use the current dtype to avoid any overflows + min_dtype = torch.finfo(dtype).min + causal_mask = self.causal_mask[None, None, :, :].repeat(batch_size, 1, 1, 1).to(dtype) * min_dtype + + causal_mask = causal_mask.to(dtype=dtype, device=device) + if attention_mask is not None and attention_mask.dim() == 2: + mask_length = attention_mask.shape[-1] + padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0) + causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype) + + if self.config._attn_implementation == "sdpa" and attention_mask is not None and attention_mask.device.type == "cuda": + # TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400). + is_tracing = torch.jit.is_tracing() or isinstance(input_tensor, torch.fx.Proxy) or (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling()) + if not is_tracing and torch.any(attention_mask != 1): + # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when + # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. + # Details: https://github.com/pytorch/pytorch/issues/110213 + causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) + + return causal_mask + + +class LlamaForCausalLM(LlamaPreTrainedModel): + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = LlamaModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + cache_position: Optional[torch.LongTensor] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, LlamaForCausalLM + + >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf") + >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") + + >>> prompt = "Hey, are you conscious? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." + ```""" + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + cache_position=cache_position, + ) + + hidden_states = outputs[0] + if self.config.pretraining_tp > 1: + lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0) + logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)] + logits = torch.cat(logits, dim=-1) + else: + logits = self.lm_head(hidden_states) + logits = logits.float() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + shift_logits = shift_logits.view(-1, self.config.vocab_size) + shift_labels = shift_labels.view(-1) + # Enable model parallelism + shift_labels = shift_labels.to(shift_logits.device) + loss = loss_fct(shift_logits, shift_labels) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs): + past_length = 0 + if past_key_values is not None: + if isinstance(past_key_values, Cache): + cache_length = past_key_values.get_seq_length() + past_length = past_key_values.seen_tokens + max_cache_length = past_key_values.get_max_length() + else: + cache_length = past_length = past_key_values[0][0].shape[2] + max_cache_length = None + + # Keep only the unprocessed tokens: + # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where + # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as + # input) + if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]: + input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :] + # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard + # input_ids based on the past_length. + elif past_length < input_ids.shape[1]: + input_ids = input_ids[:, past_length:] + # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens. + + # If we are about to go beyond the maximum cache length, we need to crop the input attention mask. + if max_cache_length is not None and attention_mask is not None and cache_length + input_ids.shape[1] > max_cache_length: + attention_mask = attention_mask[:, -max_cache_length:] + + position_ids = kwargs.get("position_ids", None) + if attention_mask is not None and position_ids is None: + # create position_ids on the fly for batch generation + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + if past_key_values: + position_ids = position_ids[:, -input_ids.shape[1] :] + + if self.generation_config.cache_implementation == "static": + # generation with static cache + cache_position = kwargs.get("cache_position", None) + if cache_position is None: + past_length = 0 + else: + past_length = cache_position[-1] + 1 + input_ids = input_ids[:, past_length:] + position_ids = position_ids[:, past_length:] + + # TODO @gante we should only keep a `cache_position` in generate, and do +=1. + # same goes for position ids. Could also help with continued generation. + input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1] + cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device) + position_ids = position_ids.contiguous() if position_ids is not None else None + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise + # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114 + # TODO: use `next_tokens` directly instead. + model_inputs = {"input_ids": input_ids.contiguous()} + + model_inputs.update( + { + "position_ids": position_ids, + "cache_position": cache_position, + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += (tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),) + return reordered_past + + +@add_start_docstrings( + """ + The LLaMa Model transformer with a sequence classification head on top (linear layer). + + [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + LLAMA_START_DOCSTRING, +) +class LlamaForSequenceClassification(LlamaPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + self.model = LlamaModel(config) + self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + + if self.config.pad_token_id is None and batch_size != 1: + raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility + sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1 + sequence_lengths = sequence_lengths % input_ids.shape[-1] + sequence_lengths = sequence_lengths.to(logits.device) + else: + sequence_lengths = -1 + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + labels = labels.to(logits.device) + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + +@add_start_docstrings( + """ +The Llama Model transformer with a span classification head on top for extractive question-answering tasks like +SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`). + """, + LLAMA_START_DOCSTRING, +) +class LlamaForQuestionAnswering(LlamaPreTrainedModel): + base_model_prefix = "transformer" + + # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama + def __init__(self, config): + super().__init__(config) + self.transformer = LlamaModel(config) + self.qa_outputs = nn.Linear(config.hidden_size, 2) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.transformer.embed_tokens + + def set_input_embeddings(self, value): + self.transformer.embed_tokens = value + + @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + start_positions: Optional[torch.LongTensor] = None, + end_positions: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, QuestionAnsweringModelOutput]: + r""" + start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.transformer( + input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + sequence_output = outputs[0] + + logits = self.qa_outputs(sequence_output) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1).to(start_logits.device) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1).to(end_logits.device) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-18B.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-18B.json" new file mode 100644 index 0000000000000000000000000000000000000000..4917556693fe9dcbddeadf7459be363740d55aa5 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-18B.json" @@ -0,0 +1,27 @@ +{ + "embed_dim": 1536, + "vision_cfg": { + "image_size": 224, + "layers": 48, + "width": 5120, + "head_width": 128, + "mlp_ratio": 5, + "patch_size": 14, + "eva_model_name": "eva-clip-18b-14-x", + "drop_path_rate": 0, + "qkv_bias": false, + "xattn": true, + "postnorm": true, + "fusedLN": false, + "use_rms_norm": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32, + "xattn": false, + "fusedLN": false + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-8B.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-8B.json" new file mode 100644 index 0000000000000000000000000000000000000000..689492a25d365436fd85ed432e6fb7295ca1c7bd --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/dev_eva_clip/eva_clip/model_configs/EVA-CLIP-8B.json" @@ -0,0 +1,27 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 4096, + "head_width": 128, + "mlp_ratio": 5, + "patch_size": 14, + "eva_model_name": "eva-clip-8b-14-x", + "drop_path_rate": 0, + "qkv_bias": false, + "xattn": true, + "postnorm": false, + "fusedLN": false, + "use_rms_norm": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32, + "xattn": false, + "fusedLN": false + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_clip_encoder.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_clip_encoder.py" new file mode 100644 index 0000000000000000000000000000000000000000..aaef516a9b0e958c2f156d29a44bf978dd31eebd --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_clip_encoder.py" @@ -0,0 +1,74 @@ +import torch +import torch.nn as nn + +from .eva_clip_processors import EvaClipImageTrainProcessor +from .eva_vit import EVAEncoderWrapper +from .factory import list_models, add_model_config, get_model_config + +from llava.utils import rank0_print + + +class EvaClipVisionTower(nn.Module): + def __init__(self, vision_tower, args, delay_load=False): + super().__init__() + + self.is_loaded = False + self.vision_tower_name = vision_tower + self.vision_tower_pretrained = args.vision_tower_pretrained + self.config = get_model_config(vision_tower) + + if not delay_load: + rank0_print(f"Loading EVA ViT: {self.vision_tower_name}") + self.load_model() + elif getattr(args, "unfreeze_mm_vision_tower", False): + # TODO: better detector is needed. + rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `unfreeze_mm_vision_tower`: True.") + self.load_model() + elif hasattr(args, "mm_tunable_parts") and "mm_vision_tower" in args.mm_tunable_parts: + rank0_print(f"The checkpoint seems to contain `vision_tower` weights: `mm_tunable_parts` contains `mm_vision_tower`.") + self.load_model() + else: + self.cfg_only = self.config + + def load_model(self, device_map=None): + rank0_print(f"Pretrained: {self.vision_tower_pretrained}") + self.image_processor = EvaClipImageTrainProcessor(self.config["vision_cfg"]["image_size"]) + self.vision_tower = EVAEncoderWrapper(self.vision_tower_pretrained, self.config) + rank0_print(f"Loaded image processor: {self.image_processor}") + self.vision_tower.requires_grad_(False) + self.is_loaded = True + + def forward(self, images): + if type(images) is list: + image_features = [] + for image in images: + image_feature = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0)).to(image.dtype) + image_features.append(image_feature) + else: + image_features = self.vision_tower(images.to(device=self.device, dtype=self.dtype)).to(images.dtype) + + return image_features + + @property + def dtype(self): + return self.vision_tower.dtype + + @property + def device(self): + return self.vision_tower.device + + @property + def hidden_size(self): + return self.config["vision_cfg"]["width"] + + @property + def num_patches(self): + return (self.config["vision_cfg"]["image_size"] // self.config["vision_cfg"]["patch_size"]) ** 2 + + @property + def num_patches_per_side(self): + return self.config["vision_cfg"]["image_size"] // self.config["vision_cfg"]["patch_size"] + + @property + def image_size(self): + return self.config["vision_cfg"]["image_size"] diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_clip_processors.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_clip_processors.py" new file mode 100644 index 0000000000000000000000000000000000000000..7ee1273155ddf1c32f1ac4085f8141582d9259cd --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_clip_processors.py" @@ -0,0 +1,72 @@ +""" +# Adapted from https://github.com/baaivision/EVA/tree/master/EVA-CLIP +""" + +from torchvision import transforms +from torchvision.transforms.functional import InterpolationMode +from transformers.image_processing_utils import BatchFeature +from PIL import Image +from transformers.image_transforms import convert_to_rgb + + +class BaseProcessor: + def __init__(self): + self.transform = lambda x: x + return + + def __call__(self, item): + return self.transform(item) + + +class EvaClipImageBaseProcessor(BaseProcessor): + def __init__(self, mean=None, std=None): + self.mean = (0.48145466, 0.4578275, 0.40821073) if mean is None else mean + self.std = (0.26862954, 0.26130258, 0.27577711) if std is None else std + + self.normalize = transforms.Normalize(self.mean, self.std) + + @property + def image_mean(self): + return self.mean + + +class EvaClipImageTrainProcessor(EvaClipImageBaseProcessor): + def __init__(self, image_size=224, mean=None, std=None, min_scale=0.5, max_scale=1.0): + super().__init__(mean=mean, std=std) + + self.transform = transforms.Compose( + [ + convert_to_rgb, + transforms.Resize( + image_size, + interpolation=InterpolationMode.BICUBIC, + ), + transforms.CenterCrop(image_size), + transforms.ToTensor(), + self.normalize, + ] + ) + + self.image_size = image_size + + def preprocess(self, images, return_tensors): + if isinstance(images, Image.Image): + images = [images] + else: + assert isinstance(images, list) + + transformed_images = [self.transform(image).numpy() for image in images] + data = {"pixel_values": transformed_images} + + return BatchFeature(data=data, tensor_type=return_tensors) + + def __call__(self, item): + return self.transform(item) + + @property + def crop_size(self): + return {"height": self.image_size, "width": self.image_size} + + @property + def size(self): + return {"shortest_edge": self.image_size} diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_vit.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_vit.py" new file mode 100644 index 0000000000000000000000000000000000000000..d2330c322677b860c0c04c3d153b99caaf4f6a7a --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/eva_vit.py" @@ -0,0 +1,856 @@ +""" +# Adapted from https://github.com/baaivision/EVA/tree/master/EVA-CLIP +""" + +from math import pi +import torch +from torch import nn +from einops import rearrange, repeat +import logging +from llava.utils import rank0_print + + +def broadcat(tensors, dim=-1): + num_tensors = len(tensors) + shape_lens = set(list(map(lambda t: len(t.shape), tensors))) + assert len(shape_lens) == 1, "tensors must all have the same number of dimensions" + shape_len = list(shape_lens)[0] + dim = (dim + shape_len) if dim < 0 else dim + dims = list(zip(*map(lambda t: list(t.shape), tensors))) + expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim] + assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), "invalid dimensions for broadcastable concatentation" + max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims)) + expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims)) + expanded_dims.insert(dim, (dim, dims[dim])) + expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims))) + tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes))) + return torch.cat(tensors, dim=dim) + + +def rotate_half(x): + x = rearrange(x, "... (d r) -> ... d r", r=2) + x1, x2 = x.unbind(dim=-1) + x = torch.stack((-x2, x1), dim=-1) + return rearrange(x, "... d r -> ... (d r)") + + +class VisionRotaryEmbeddingFast(nn.Module): + def __init__(self, dim, pt_seq_len, ft_seq_len=None, custom_freqs=None, freqs_for="lang", theta=10000, max_freq=10, num_freqs=1, patch_dropout=0.0): + super().__init__() + if custom_freqs: + freqs = custom_freqs + elif freqs_for == "lang": + freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) + elif freqs_for == "pixel": + freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi + elif freqs_for == "constant": + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f"unknown modality {freqs_for}") + + if ft_seq_len is None: + ft_seq_len = pt_seq_len + t = torch.arange(ft_seq_len) / ft_seq_len * pt_seq_len + + freqs = torch.einsum("..., f -> ... f", t, freqs) + freqs = repeat(freqs, "... n -> ... (n r)", r=2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1) + + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]) + + self.patch_dropout = patch_dropout + + self.register_buffer("freqs_cos", freqs_cos) + self.register_buffer("freqs_sin", freqs_sin) + + logging.info(f"Shape of rope freq: {self.freqs_cos.shape}") + + def forward(self, t, patch_indices_keep=None): + if patch_indices_keep is not None: + batch = t.size()[0] + batch_indices = torch.arange(batch) + batch_indices = batch_indices[..., None] + + freqs_cos = repeat(self.freqs_cos, "i j -> n i m j", n=t.shape[0], m=t.shape[1]) + freqs_sin = repeat(self.freqs_sin, "i j -> n i m j", n=t.shape[0], m=t.shape[1]) + + freqs_cos = freqs_cos[batch_indices, patch_indices_keep] + freqs_cos = rearrange(freqs_cos, "n i m j -> n m i j") + freqs_sin = freqs_sin[batch_indices, patch_indices_keep] + freqs_sin = rearrange(freqs_sin, "n i m j -> n m i j") + + return t * freqs_cos + rotate_half(t) * freqs_sin + + return t * self.freqs_cos + rotate_half(t) * self.freqs_sin + + +class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm (with cast back to input dtype).""" + + def forward(self, x: torch.Tensor): + orig_type = x.dtype + x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) + return x.to(orig_type) + + +class PatchDropout(nn.Module): + """ + https://arxiv.org/abs/2212.00794 + """ + + def __init__(self, prob, exclude_first_token=True): + super().__init__() + assert 0 <= prob < 1.0 + self.prob = prob + self.exclude_first_token = exclude_first_token # exclude CLS token + logging.info(f"os.getenv('RoPE')={os.getenv('RoPE')}") + + def forward(self, x): + if not self.training or self.prob == 0.0: + return x + + if self.exclude_first_token: + cls_tokens, x = x[:, :1], x[:, 1:] + else: + cls_tokens = torch.jit.annotate(torch.Tensor, x[:, :1]) + + batch = x.size()[0] + num_tokens = x.size()[1] + + batch_indices = torch.arange(batch) + batch_indices = batch_indices[..., None] + + keep_prob = 1 - self.prob + num_patches_keep = max(1, int(num_tokens * keep_prob)) + + rand = torch.randn(batch, num_tokens) + patch_indices_keep = rand.topk(num_patches_keep, dim=-1).indices + + x = x[batch_indices, patch_indices_keep] + + if self.exclude_first_token: + x = torch.cat((cls_tokens, x), dim=1) + + if self.training and os.getenv("RoPE") == "1": + return x, patch_indices_keep + + return x + + +# -------------------------------------------------------- +# Adapted from https://github.com/microsoft/unilm/tree/master/beit +# -------------------------------------------------------- +import math +import os +import torch.nn as nn +import torch.nn.functional as F + +try: + from timm.models.layers import drop_path, to_2tuple, trunc_normal_ +except: + from timm.layers import drop_path, to_2tuple, trunc_normal_ + +if os.getenv("ENV_TYPE") == "deepspeed": + try: + from deepspeed.runtime.activation_checkpointing.checkpointing import checkpoint + except: + from torch.utils.checkpoint import checkpoint +else: + from torch.utils.checkpoint import checkpoint + +try: + import xformers.ops as xops +except ImportError: + xops = None + # print("Please 'pip install xformers'") + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) + + def extra_repr(self) -> str: + return "p={}".format(self.drop_prob) + + +class Mlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + drop=0.0, + subln=False, + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + + self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity() + + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + # x = self.drop(x) + # commit this for the orignal BERT implement + x = self.ffn_ln(x) + + x = self.fc2(x) + x = self.drop(x) + return x + + +class SwiGLU(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.0, norm_layer=nn.LayerNorm, subln=False): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + + self.w1 = nn.Linear(in_features, hidden_features) + self.w2 = nn.Linear(in_features, hidden_features) + + self.act = act_layer() + self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity() + self.w3 = nn.Linear(hidden_features, out_features) + + self.drop = nn.Dropout(drop) + + def forward(self, x): + x1 = self.w1(x) + x2 = self.w2(x) + hidden = self.act(x1) * x2 + x = self.ffn_ln(hidden) + x = self.w3(x) + x = self.drop(x) + return x + + +class Attention(nn.Module): + def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, window_size=None, attn_head_dim=None, xattn=False, rope=None, subln=False, norm_layer=nn.LayerNorm): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + if attn_head_dim is not None: + head_dim = attn_head_dim + all_head_dim = head_dim * self.num_heads + self.scale = qk_scale or head_dim**-0.5 + + self.subln = subln + if self.subln: + self.q_proj = nn.Linear(dim, all_head_dim, bias=False) + self.k_proj = nn.Linear(dim, all_head_dim, bias=False) + self.v_proj = nn.Linear(dim, all_head_dim, bias=False) + else: + self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False) + + if qkv_bias: + self.q_bias = nn.Parameter(torch.zeros(all_head_dim)) + self.v_bias = nn.Parameter(torch.zeros(all_head_dim)) + else: + self.q_bias = None + self.v_bias = None + + if window_size: + self.window_size = window_size + self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 + self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH + # cls to token & token 2 cls & cls to cls + + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(window_size[0]) + coords_w = torch.arange(window_size[1]) + coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * window_size[1] - 1 + relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype) + relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww + relative_position_index[0, 0:] = self.num_relative_distance - 3 + relative_position_index[0:, 0] = self.num_relative_distance - 2 + relative_position_index[0, 0] = self.num_relative_distance - 1 + + self.register_buffer("relative_position_index", relative_position_index) + else: + self.window_size = None + self.relative_position_bias_table = None + self.relative_position_index = None + + self.attn_drop = nn.Dropout(attn_drop) + self.inner_attn_ln = norm_layer(all_head_dim) if subln else nn.Identity() + # self.proj = nn.Linear(all_head_dim, all_head_dim) + self.proj = nn.Linear(all_head_dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.xattn = xattn + self.xattn_drop = attn_drop + + self.rope = rope + + def forward(self, x, rel_pos_bias=None, attn_mask=None): + B, N, C = x.shape + if self.subln: + q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias) + k = F.linear(input=x, weight=self.k_proj.weight, bias=None) + v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias) + + q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C + k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) + else: + + qkv_bias = None + if self.q_bias is not None: + qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias)) + + qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias) + qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # 3, B, num_heads, N, C + q, k, v = qkv[0], qkv[1], qkv[2] + + if self.rope: + # slightly fast impl + q_t = q[:, :, 1:, :] + ro_q_t = self.rope(q_t) + q = torch.cat((q[:, :, :1, :], ro_q_t), -2).type_as(v) + + k_t = k[:, :, 1:, :] + ro_k_t = self.rope(k_t) + k = torch.cat((k[:, :, :1, :], ro_k_t), -2).type_as(v) + + if self.xattn and xops is not None: + q = q.permute(0, 2, 1, 3) # B, num_heads, N, C -> B, N, num_heads, C + k = k.permute(0, 2, 1, 3) + v = v.permute(0, 2, 1, 3) + + x = xops.memory_efficient_attention( + q, + k, + v, + p=self.xattn_drop, + scale=self.scale, + ) + x = x.reshape(B, N, -1) + x = self.inner_attn_ln(x) + x = self.proj(x) + x = self.proj_drop(x) + else: + q = q * self.scale + attn = q @ k.transpose(-2, -1) + + if self.relative_position_bias_table is not None: + relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + attn = attn + relative_position_bias.unsqueeze(0).type_as(attn) + + if rel_pos_bias is not None: + attn = attn + rel_pos_bias.type_as(attn) + + if attn_mask is not None: + attn_mask = attn_mask.bool() + attn = attn.masked_fill(~attn_mask[:, None, None, :], float("-inf")) + + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, -1) + x = self.inner_attn_ln(x) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class Block(nn.Module): + + def __init__( + self, + dim, + num_heads, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + init_values=None, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + window_size=None, + attn_head_dim=None, + xattn=False, + rope=None, + postnorm=False, + subln=False, + naiveswiglu=False, + ): + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, window_size=window_size, attn_head_dim=attn_head_dim, xattn=xattn, rope=rope, subln=subln, norm_layer=norm_layer + ) + # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + + if naiveswiglu: + self.mlp = SwiGLU( + in_features=dim, + hidden_features=mlp_hidden_dim, + subln=subln, + norm_layer=norm_layer, + ) + else: + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, subln=subln, drop=drop) + + if init_values is not None and init_values > 0: + self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True) + self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True) + else: + self.gamma_1, self.gamma_2 = None, None + + self.postnorm = postnorm + + def forward(self, x, rel_pos_bias=None, attn_mask=None): + if self.gamma_1 is None: + if self.postnorm: + x = x + self.drop_path(self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))) + x = x + self.drop_path(self.norm2(self.mlp(x))) + else: + x = x + self.drop_path(self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)) + x = x + self.drop_path(self.mlp(self.norm2(x))) + else: + if self.postnorm: + x = x + self.drop_path(self.gamma_1 * self.norm1(self.attn(x, rel_pos_bias=rel_pos_bias, attn_mask=attn_mask))) + x = x + self.drop_path(self.gamma_2 * self.norm2(self.mlp(x))) + else: + x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), rel_pos_bias=rel_pos_bias, attn_mask=attn_mask)) + x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) + return x + + +class PatchEmbed(nn.Module): + """Image to Patch Embedding""" + + def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): + super().__init__() + img_size = to_2tuple(img_size) + patch_size = to_2tuple(patch_size) + num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) + self.patch_shape = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) + self.img_size = img_size + self.patch_size = patch_size + self.num_patches = num_patches + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) + + def forward(self, x, **kwargs): + B, C, H, W = x.shape + # FIXME look at relaxing size constraints + assert H == self.img_size[0] and W == self.img_size[1], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." + x = self.proj(x).flatten(2).transpose(1, 2) + return x + + +class RelativePositionBias(nn.Module): + + def __init__(self, window_size, num_heads): + super().__init__() + self.window_size = window_size + self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3 + self.relative_position_bias_table = nn.Parameter(torch.zeros(self.num_relative_distance, num_heads)) # 2*Wh-1 * 2*Ww-1, nH + # cls to token & token 2 cls & cls to cls + + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(window_size[0]) + coords_w = torch.arange(window_size[1]) + coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * window_size[1] - 1 + relative_position_index = torch.zeros(size=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype) + relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww + relative_position_index[0, 0:] = self.num_relative_distance - 3 + relative_position_index[0:, 0] = self.num_relative_distance - 2 + relative_position_index[0, 0] = self.num_relative_distance - 1 + + self.register_buffer("relative_position_index", relative_position_index) + + def forward(self): + relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH + return relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww + + +class EVAVisionTransformer(nn.Module): + """Vision Transformer with support for patch or hybrid CNN input stage""" + + def __init__( + self, + img_size=224, + patch_size=16, + in_chans=3, + num_classes=1000, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + norm_layer=nn.LayerNorm, + init_values=None, + patch_dropout=0.0, + use_abs_pos_emb=True, + use_rel_pos_bias=False, + use_shared_rel_pos_bias=False, + rope=False, + use_mean_pooling=True, + init_scale=0.001, + grad_checkpointing=False, + xattn=False, + postnorm=False, + pt_hw_seq_len=16, + intp_freq=False, + naiveswiglu=False, + subln=False, + ): + super().__init__() + self.image_size = img_size + self.num_classes = num_classes + self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models + + self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) + num_patches = self.patch_embed.num_patches + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + # self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + if use_abs_pos_emb: + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) + else: + self.pos_embed = None + self.pos_drop = nn.Dropout(p=drop_rate) + + if use_shared_rel_pos_bias: + self.rel_pos_bias = RelativePositionBias(window_size=self.patch_embed.patch_shape, num_heads=num_heads) + else: + self.rel_pos_bias = None + + if rope: + half_head_dim = embed_dim // num_heads // 2 + hw_seq_len = img_size // patch_size + self.rope = VisionRotaryEmbeddingFast( + dim=half_head_dim, + pt_seq_len=pt_hw_seq_len, + ft_seq_len=hw_seq_len if intp_freq else None, + # patch_dropout=patch_dropout + ) + else: + self.rope = None + + self.naiveswiglu = naiveswiglu + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + self.use_rel_pos_bias = use_rel_pos_bias + self.blocks = nn.ModuleList( + [ + Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + init_values=init_values, + window_size=self.patch_embed.patch_shape if use_rel_pos_bias else None, + xattn=xattn, + rope=self.rope, + postnorm=postnorm, + subln=subln, + naiveswiglu=naiveswiglu, + ) + for i in range(depth) + ] + ) + self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim) + self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None + self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() + + if self.pos_embed is not None: + trunc_normal_(self.pos_embed, std=0.02) + + trunc_normal_(self.cls_token, std=0.02) + # trunc_normal_(self.mask_token, std=.02) + + self.apply(self._init_weights) + self.fix_init_weight() + + if isinstance(self.head, nn.Linear): + trunc_normal_(self.head.weight, std=0.02) + self.head.weight.data.mul_(init_scale) + self.head.bias.data.mul_(init_scale) + + # setting a patch_dropout of 0. would mean it is disabled and this function would be the identity fn + self.patch_dropout = PatchDropout(patch_dropout) if patch_dropout > 0.0 else nn.Identity() + + self.grad_checkpointing = grad_checkpointing + + def fix_init_weight(self): + def rescale(param, layer_id): + param.div_(math.sqrt(2.0 * layer_id)) + + for layer_id, layer in enumerate(self.blocks): + rescale(layer.attn.proj.weight.data, layer_id + 1) + if self.naiveswiglu: + rescale(layer.mlp.w3.weight.data, layer_id + 1) + else: + rescale(layer.mlp.fc2.weight.data, layer_id + 1) + + def get_cast_dtype(self) -> torch.dtype: + return self.blocks[0].mlp.fc2.weight.dtype + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def get_num_layers(self): + return len(self.blocks) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + assert unlocked_groups == 0, "partial locking not currently supported for this model" + for param in self.parameters(): + param.requires_grad = False + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.grad_checkpointing = enable + + @torch.jit.ignore + def no_weight_decay(self): + return {"pos_embed", "cls_token"} + + def get_classifier(self): + return self.head + + def reset_classifier(self, num_classes, global_pool=""): + self.num_classes = num_classes + self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() + + def forward_features(self, x, return_all_features=False): + + x = self.patch_embed(x) + batch_size, seq_len, _ = x.size() + + cls_tokens = self.cls_token.expand(batch_size, -1, -1) # stole cls_tokens impl from Phil Wang, thanks + x = torch.cat((cls_tokens, x), dim=1) + if self.pos_embed is not None: + x = x + self.pos_embed + x = self.pos_drop(x) + + # a patch_dropout of 0. would mean it is disabled and this function would do nothing but return what was passed in + if os.getenv("RoPE") == "1": + if self.training and not isinstance(self.patch_dropout, nn.Identity): + x, patch_indices_keep = self.patch_dropout(x) + # Directly pass patch_indices_keep to self.rope.forward + x = self.rope.forward(x, patch_indices_keep=patch_indices_keep) + else: + # Pass None or omit the patch_indices_keep argument for default behavior + x = self.rope.forward(x, patch_indices_keep=None) + x = self.patch_dropout(x) + else: + x = self.patch_dropout(x) + + rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None + for i, blk in enumerate(self.blocks): + if i == len(self.blocks) - 1: + continue + if self.grad_checkpointing: + x = checkpoint(blk, x, (rel_pos_bias,)) + else: + x = blk(x, rel_pos_bias=rel_pos_bias) + + if not return_all_features: + x = self.norm(x) + if self.fc_norm is not None: + return self.fc_norm(x.mean(1)) + else: + return x[:, 0] + return x + + def forward(self, x, return_all_features=False): + if return_all_features: + return self.forward_features(x, return_all_features) + x = self.forward_features(x) + x = self.head(x) + return x + + +def load_state_dict(checkpoint_path: str, map_location: str = "cpu", model_key: str = "model|module|state_dict", is_openai: bool = False, skip_list: list = []): + if is_openai: + model = torch.jit.load(checkpoint_path, map_location="cpu").eval() + state_dict = model.state_dict() + for key in ["input_resolution", "context_length", "vocab_size"]: + state_dict.pop(key, None) + else: + checkpoint = torch.load(checkpoint_path, map_location=map_location) + for mk in model_key.split("|"): + if isinstance(checkpoint, dict) and mk in checkpoint: + state_dict = checkpoint[mk] + break + else: + state_dict = checkpoint + if next(iter(state_dict.items()))[0].startswith("module"): + state_dict = {k[7:]: v for k, v in state_dict.items()} + + for k in skip_list: + if k in list(state_dict.keys()): + logging.info(f"Removing key {k} from pretrained checkpoint") + del state_dict[k] + + if os.getenv("RoPE") == "1": + for k in list(state_dict.keys()): + if "freqs_cos" in k or "freqs_sin" in k: + del state_dict[k] + return state_dict + + +def load_clip_visual_state_dict(checkpoint_path: str, map_location: str = "cpu", is_openai: bool = False, skip_list: list = []): + state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list) + # for k in list(state_dict.keys()): + # if not k.startswith("visual."): + # del state_dict[k] + # for k in list(state_dict.keys()): + # if k.startswith("visual."): + # new_k = k[7:] + # state_dict[new_k] = state_dict[k] + # del state_dict[k] + return state_dict + + +from dataclasses import dataclass +from typing import Optional, Tuple, Union + +try: + from apex.normalization import FusedLayerNorm +except: + FusedLayerNorm = LayerNorm + # print("Please build and install Nvidia apex package with option '--cuda_ext' according to https://github.com/NVIDIA/apex#from-source .") + + +@dataclass +class CLIPVisionCfg: + layers: Union[Tuple[int, int, int, int], int] = 12 + width: int = 768 + head_width: int = 64 + mlp_ratio: float = 4.0 + patch_size: int = 16 + image_size: Union[Tuple[int, int], int] = 224 + ls_init_value: Optional[float] = None # layer scale initial value + patch_dropout: float = 0.0 # what fraction of patches to dropout during training (0 would mean disabled and no patches dropped) - 0.5 to 0.75 recommended in the paper for optimal results + global_average_pool: bool = False # whether to global average pool the last embedding layer, instead of using CLS token (https://arxiv.org/abs/2205.01580) + drop_path_rate: Optional[float] = None # drop path rate + timm_model_name: str = None # a valid model name overrides layers, width, patch_size + timm_model_pretrained: bool = False # use (imagenet) pretrained weights for named model + timm_pool: str = "avg" # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '') + timm_proj: str = "linear" # linear projection for timm model output ('linear', 'mlp', '') + timm_proj_bias: bool = False # enable bias final projection + eva_model_name: str = None # a valid eva model name overrides layers, width, patch_size + qkv_bias: bool = True + fusedLN: bool = False + xattn: bool = False + postnorm: bool = False + rope: bool = False + pt_hw_seq_len: int = 16 # 224/14 + intp_freq: bool = False + naiveswiglu: bool = False + subln: bool = False + + +def create_norm_layer_factory(use_fused_ln, eps=1e-6): + # Otherwise, use the standard LayerNorm + return lambda num_features: nn.LayerNorm(num_features, eps=eps) + + +def _build_vision_tower(vision_tower_path: str, embed_dim: int, vision_cfg: CLIPVisionCfg, **kwargs): + if isinstance(vision_cfg, dict): + vision_cfg = CLIPVisionCfg(**vision_cfg) + + if vision_cfg.eva_model_name: + vision_heads = vision_cfg.width // vision_cfg.head_width + # Determine the appropriate norm layer factory based on the configuration + norm_layer_factory = create_norm_layer_factory(vision_cfg.fusedLN, eps=1e-6) + + visual = EVAVisionTransformer( + img_size=vision_cfg.image_size, + patch_size=vision_cfg.patch_size, + num_classes=embed_dim, + use_mean_pooling=vision_cfg.global_average_pool, # False + init_values=vision_cfg.ls_init_value, + patch_dropout=vision_cfg.patch_dropout, + embed_dim=vision_cfg.width, + depth=vision_cfg.layers, + num_heads=vision_heads, + mlp_ratio=vision_cfg.mlp_ratio, + qkv_bias=vision_cfg.qkv_bias, + drop_path_rate=vision_cfg.drop_path_rate, + norm_layer=norm_layer_factory, + xattn=vision_cfg.xattn, + rope=vision_cfg.rope, + postnorm=vision_cfg.postnorm, + pt_hw_seq_len=vision_cfg.pt_hw_seq_len, # 224/14 + intp_freq=vision_cfg.intp_freq, + naiveswiglu=vision_cfg.naiveswiglu, + subln=vision_cfg.subln, + ) + + state_dict = load_clip_visual_state_dict(vision_tower_path) + incompatible_keys = visual.load_state_dict(state_dict, strict=False) + rank0_print("EVA-CLIP incompatible_keys:", incompatible_keys) + + return visual + + +class EVAEncoderWrapper(nn.Module): + def __init__(self, vision_tower_pretrained, config): + super(EVAEncoderWrapper, self).__init__() + self.config = config + self.config["vision_tower_path"] = vision_tower_pretrained + self.model = _build_vision_tower(**self.config) + + def forward(self, image, **kwargs): + encode = self.model(image, return_all_features=True)[:, 1:, :] # remove the CLS token + return encode + + @property + def dtype(self): + return list(self.parameters())[-1].dtype + + @property + def device(self): + return list(self.parameters())[-1].device diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/factory.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/factory.py" new file mode 100644 index 0000000000000000000000000000000000000000..6d3fafcfd086c6c038a4577246f42c05264d5802 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/factory.py" @@ -0,0 +1,60 @@ +import json +import logging +import os +import pathlib +import re +from copy import deepcopy +from pathlib import Path +from typing import Optional, Tuple, Union, Dict, Any +import torch + +_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"] +_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs + + +def _natural_key(string_): + return [int(s) if s.isdigit() else s for s in re.split(r"(\d+)", string_.lower())] + + +def _rescan_model_configs(): + global _MODEL_CONFIGS + + config_ext = (".json",) + config_files = [] + for config_path in _MODEL_CONFIG_PATHS: + if config_path.is_file() and config_path.suffix in config_ext: + config_files.append(config_path) + elif config_path.is_dir(): + for ext in config_ext: + config_files.extend(config_path.glob(f"*{ext}")) + + for cf in config_files: + with open(cf, "r", encoding="utf8") as f: + model_cfg = json.load(f) + if all(a in model_cfg for a in ("embed_dim", "vision_cfg", "text_cfg")): + _MODEL_CONFIGS[cf.stem] = model_cfg + + _MODEL_CONFIGS = dict(sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))) + + +_rescan_model_configs() # initial populate of model config registry + + +def list_models(): + """enumerate available model architectures based on config files""" + return list(_MODEL_CONFIGS.keys()) + + +def add_model_config(path): + """add model config path or file and update registry""" + if not isinstance(path, Path): + path = Path(path) + _MODEL_CONFIG_PATHS.append(path) + _rescan_model_configs() + + +def get_model_config(model_name): + if model_name in _MODEL_CONFIGS: + return deepcopy(_MODEL_CONFIGS[model_name]) + else: + return None diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-18B.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-18B.json" new file mode 100644 index 0000000000000000000000000000000000000000..4917556693fe9dcbddeadf7459be363740d55aa5 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-18B.json" @@ -0,0 +1,27 @@ +{ + "embed_dim": 1536, + "vision_cfg": { + "image_size": 224, + "layers": 48, + "width": 5120, + "head_width": 128, + "mlp_ratio": 5, + "patch_size": 14, + "eva_model_name": "eva-clip-18b-14-x", + "drop_path_rate": 0, + "qkv_bias": false, + "xattn": true, + "postnorm": true, + "fusedLN": false, + "use_rms_norm": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32, + "xattn": false, + "fusedLN": false + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B-plus.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B-plus.json" new file mode 100644 index 0000000000000000000000000000000000000000..7d843daa36c36b6100291fa3a2cb58672db6bbfb --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B-plus.json" @@ -0,0 +1,27 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 448, + "layers": 32, + "width": 4096, + "head_width": 128, + "mlp_ratio": 5, + "patch_size": 14, + "eva_model_name": "eva-clip-8b-14-plus-x", + "drop_path_rate": 0, + "qkv_bias": false, + "xattn": true, + "postnorm": false, + "fusedLN": false, + "use_rms_norm": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32, + "xattn": false, + "fusedLN": false + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B.json" new file mode 100644 index 0000000000000000000000000000000000000000..689492a25d365436fd85ed432e6fb7295ca1c7bd --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA-CLIP-8B.json" @@ -0,0 +1,27 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 4096, + "head_width": 128, + "mlp_ratio": 5, + "patch_size": 14, + "eva_model_name": "eva-clip-8b-14-x", + "drop_path_rate": 0, + "qkv_bias": false, + "xattn": true, + "postnorm": false, + "fusedLN": false, + "use_rms_norm": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32, + "xattn": false, + "fusedLN": false + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-B-16.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-B-16.json" new file mode 100644 index 0000000000000000000000000000000000000000..aad2058003962a4ab286bf4e1ae956288af34e62 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-B-16.json" @@ -0,0 +1,19 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 16, + "eva_model_name": "eva-clip-b-16", + "ls_init_value": 0.1, + "drop_path_rate": 0.0 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json" new file mode 100644 index 0000000000000000000000000000000000000000..100279572ff6d1bcca601f0eb526b4d4ff174c7d --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-g-14-plus.json" @@ -0,0 +1,24 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 40, + "width": 1408, + "head_width": 88, + "mlp_ratio": 4.3637, + "patch_size": 14, + "eva_model_name": "eva-clip-g-14-x", + "drop_path_rate": 0, + "xattn": true, + "fusedLN": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-g-14.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-g-14.json" new file mode 100644 index 0000000000000000000000000000000000000000..5d338b4e6104241d1f0304ee82400035d5385332 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA01-CLIP-g-14.json" @@ -0,0 +1,24 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 40, + "width": 1408, + "head_width": 88, + "mlp_ratio": 4.3637, + "patch_size": 14, + "eva_model_name": "eva-clip-g-14-x", + "drop_path_rate": 0.4, + "xattn": true, + "fusedLN": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-B-16.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-B-16.json" new file mode 100644 index 0000000000000000000000000000000000000000..e4a6e723f77033caa341ddf9b5be1787d64ad42c --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-B-16.json" @@ -0,0 +1,29 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "head_width": 64, + "patch_size": 16, + "mlp_ratio": 2.6667, + "eva_model_name": "eva-clip-b-16-X", + "drop_path_rate": 0.0, + "xattn": true, + "fusedLN": true, + "rope": true, + "pt_hw_seq_len": 16, + "intp_freq": true, + "naiveswiglu": true, + "subln": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12, + "xattn": true, + "fusedLN": true + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14-336.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14-336.json" new file mode 100644 index 0000000000000000000000000000000000000000..3e1d124e1118911c5ad7b1ce85df195aca363ac4 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14-336.json" @@ -0,0 +1,29 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 336, + "layers": 24, + "width": 1024, + "drop_path_rate": 0, + "head_width": 64, + "mlp_ratio": 2.6667, + "patch_size": 14, + "eva_model_name": "eva-clip-l-14-336", + "xattn": true, + "fusedLN": true, + "rope": true, + "pt_hw_seq_len": 16, + "intp_freq": true, + "naiveswiglu": true, + "subln": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14.json" new file mode 100644 index 0000000000000000000000000000000000000000..03b22ad3cfb92f9c843b9ec8d672e57e7a9ba4a2 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-L-14.json" @@ -0,0 +1,29 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "drop_path_rate": 0, + "head_width": 64, + "mlp_ratio": 2.6667, + "patch_size": 14, + "eva_model_name": "eva-clip-l-14", + "xattn": true, + "fusedLN": true, + "rope": true, + "pt_hw_seq_len": 16, + "intp_freq": true, + "naiveswiglu": true, + "subln": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-bigE-14-plus.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-bigE-14-plus.json" new file mode 100644 index 0000000000000000000000000000000000000000..aa04e2545ac1e015daae2c10133956ce969524f7 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-bigE-14-plus.json" @@ -0,0 +1,25 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 64, + "width": 1792, + "head_width": 112, + "mlp_ratio": 8.571428571428571, + "patch_size": 14, + "eva_model_name": "eva-clip-4b-14-x", + "drop_path_rate": 0, + "xattn": true, + "postnorm": true, + "fusedLN": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32, + "xattn": false, + "fusedLN": true + } +} diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-bigE-14.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-bigE-14.json" new file mode 100644 index 0000000000000000000000000000000000000000..747ffccc8bd49dbb6701b58e15843b7fe3754e64 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/EVA02-CLIP-bigE-14.json" @@ -0,0 +1,25 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 64, + "width": 1792, + "head_width": 112, + "mlp_ratio": 8.571428571428571, + "patch_size": 14, + "eva_model_name": "eva-clip-4b-14-x", + "drop_path_rate": 0, + "xattn": true, + "postnorm": true, + "fusedLN": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24, + "xattn": false, + "fusedLN": true + } +} \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14-448.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14-448.json" new file mode 100644 index 0000000000000000000000000000000000000000..ad71aff86a4d3b0e34c0bb55ea2b8e3ac220477a --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14-448.json" @@ -0,0 +1,25 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 448, + "layers": 77, + "width": 2304, + "head_width": 144, + "mlp_ratio": 10.9722, + "patch_size": 14, + "eva_model_name": "eva-clip-10b-14-x", + "drop_path_rate": 0, + "xattn": true, + "postnorm": false, + "fusedLN": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32, + "xattn": false, + "fusedLN": true + } +} diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14.json" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14.json" new file mode 100644 index 0000000000000000000000000000000000000000..21b20680715e6e719b6c8d51c86701a4811ac37f --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/eva_clip/model_configs/Internal-EVA02-CLIP-10B-14.json" @@ -0,0 +1,25 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 77, + "width": 2304, + "head_width": 144, + "mlp_ratio": 10.9722, + "patch_size": 14, + "eva_model_name": "eva-clip-10b-14-x", + "drop_path_rate": 0, + "xattn": true, + "postnorm": false, + "fusedLN": true + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32, + "xattn": false, + "fusedLN": true + } +} diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/mlcd/vit_rope2d_hf.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/mlcd/vit_rope2d_hf.py" new file mode 100644 index 0000000000000000000000000000000000000000..5ddedae5baa9702cb9235a77d562cdeff2c386e1 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_encoder/mlcd/vit_rope2d_hf.py" @@ -0,0 +1,452 @@ +from typing import Optional, Tuple, Union + +import torch +import torch.utils.checkpoint +from torch import nn +from torch.nn import functional as F +from transformers.models.clip.modeling_clip import (CLIPMLP, BaseModelOutput, + BaseModelOutputWithPooling, + CLIPVisionConfig, + PreTrainedModel) + + +def rotate_half(x): + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor: + orig_dtype = tensor.dtype + tensor = tensor.float() + cos = freqs.cos() + sin = freqs.sin() + cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() + sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() + output = (tensor * cos) + (rotate_half(tensor) * sin) + output = output.to(orig_dtype) + return output + + +class VisionRotaryEmbedding(nn.Module): + def __init__(self, dim: int, theta: float = 10000.0) -> None: + super().__init__() + inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + + def forward(self, seqlen: int) -> torch.Tensor: + seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype) + freqs = torch.outer(seq, self.inv_freq) + return freqs + + +class MLCDVisionConfig(CLIPVisionConfig): + + model_type = "mlcd_vision_model" + + def __init__(self,**kwargs): + super().__init__(**kwargs) + + +class MLCDMLP(CLIPMLP): + def __init__(self, config: MLCDVisionConfig): + super().__init__(config) + + +class MLCDVisionEmbeddings(torch.nn.Module): + def __init__(self, config: MLCDVisionConfig): + super().__init__() + self.config = config + self.embed_dim = config.hidden_size + self.image_size = config.image_size + self.patch_size = config.patch_size + + self.class_embedding = nn.Parameter(torch.randn(self.embed_dim)) + + self.patch_embedding = nn.Conv2d( + in_channels=config.num_channels, + out_channels=self.embed_dim, + kernel_size=self.patch_size, + stride=self.patch_size, + bias=False, + ) + + self.num_patches = (self.image_size // self.patch_size) ** 2 + self.num_positions = self.num_patches + 1 + + + def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor: + batch_size = pixel_values.shape[0] + target_dtype = self.patch_embedding.weight.dtype + patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid] + patch_embeds = patch_embeds.flatten(2).transpose(1, 2) + + class_embeds = self.class_embedding.expand(batch_size, 1, -1) + embeddings = torch.cat([class_embeds, patch_embeds], dim=1) + + return embeddings + + +class MLCDSdpaAttention(torch.nn.Module): + """Multi-headed attention from these papers + + - Attention is all you need: + https://arxiv.org/abs/1706.03762 + + - RoFormer: Enhanced Transformer with Rotary Position Embedding: + https://arxiv.org/abs/2104.09864 + """ + + def __init__(self, config: MLCDVisionConfig): + super().__init__() + self.config = config + self.embed_dim = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = self.embed_dim // self.num_heads + if self.head_dim * self.num_heads != self.embed_dim: + raise ValueError( + f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:" + f" {self.num_heads})." + ) + self.scale = self.head_dim**-0.5 + self.dropout = config.attention_dropout + self.q_proj = nn.Linear(self.embed_dim, self.embed_dim) + self.k_proj = nn.Linear(self.embed_dim, self.embed_dim) + self.v_proj = nn.Linear(self.embed_dim, self.embed_dim) + self.out_proj = nn.Linear(self.embed_dim, self.embed_dim) + + + def forward( + self, + hidden_states: torch.Tensor, + rotary_pos_emb: torch.Tensor, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + """Input shape: Batch x Seq x Hidden Size""" + batch_size, seq_length , hidden_size = hidden_states.size() + # Each of shape: [batch_size, seq_length, num_heads, head_dim] + q = self.q_proj(hidden_states).reshape((batch_size, seq_length, self.num_heads, self.head_dim)) + k = self.k_proj(hidden_states).reshape((batch_size, seq_length, self.num_heads, self.head_dim)) + v = self.v_proj(hidden_states).reshape((batch_size, seq_length, self.num_heads, self.head_dim)) + q = apply_rotary_pos_emb_vision(q, rotary_pos_emb) + k = apply_rotary_pos_emb_vision(k, rotary_pos_emb) + q = q.permute(0, 2, 1, 3).contiguous() + k = k.permute(0, 2, 1, 3).contiguous() + v = v.permute(0, 2, 1, 3).contiguous() + # q (batch_size, num_heads, seq_length, head_dim) + # k (batch_size, num_heads, seq_length, head_dim) + # v (batch_size, num_heads, seq_length, head_dim) + attn_output = F.scaled_dot_product_attention(q, k, v, None, dropout_p=0.0) + attn_output = attn_output.permute(2, 0, 1, 3).contiguous() # [seq_length, batch_size, num_heads, head_dim] + attn_output = attn_output.view(seq_length, batch_size, -1) # [seq_length, batch_size, embedding_dim] + attn_output = self.out_proj(attn_output) + attn_output = attn_output.permute(1, 0, 2).contiguous() # [batch_size, seq_length, embedding_dim] + return attn_output, None + + +class MLCDEncoderLayer(nn.Module): + def __init__(self, config: MLCDVisionConfig): + super().__init__() + self.embed_dim = config.hidden_size + self.self_attn = MLCDSdpaAttention(config) + self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) + self.mlp = MLCDMLP(config) + self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + rotary_pos_emb: torch.Tensor, + ) -> Tuple[torch.FloatTensor]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + `(config.encoder_attention_heads,)`. + """ + residual = hidden_states + + hidden_states = self.layer_norm1(hidden_states) + + hidden_states = self.self_attn( + hidden_states=hidden_states, + rotary_pos_emb=rotary_pos_emb, + )[0] + hidden_states = residual + hidden_states + + residual = hidden_states + hidden_states = self.layer_norm2(hidden_states) + + hidden_states = self.mlp(hidden_states) + + hidden_states = residual + hidden_states + + outputs = (hidden_states,) + return outputs + + +class MLCDEncoder(nn.Module): + """ + Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a + [`MLCDEncoderLayer`]. + + Args: + config: MLCDVisionConfig + """ + + def __init__(self, config: MLCDVisionConfig): + super().__init__() + self.config = config + self.layers = nn.ModuleList([MLCDEncoderLayer(config) for _ in range(config.num_hidden_layers)]) + self.gradient_checkpointing = False + + def forward( + self, + inputs_embeds, + rotary_pos_emb, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutput]: + r""" + Args: + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Causal mask for the text model. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + """ + + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + encoder_states = () if output_hidden_states else None + + hidden_states = inputs_embeds + for idx, encoder_layer in enumerate(self.layers): + if output_hidden_states: + encoder_states = encoder_states + (hidden_states,) + if self.gradient_checkpointing and self.training: + layer_outputs = self._gradient_checkpointing_func( + encoder_layer.__call__, + hidden_states, + rotary_pos_emb + ) + else: + layer_outputs = encoder_layer( + hidden_states, + rotary_pos_emb + ) + + hidden_states = layer_outputs[0] + + if output_hidden_states: + encoder_states = encoder_states + (hidden_states,) + + if not return_dict: + return tuple(v for v in [hidden_states, encoder_states, None] if v is not None) + return BaseModelOutput( + last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=None, + ) + + +class MLCDVisionTransformer(nn.Module): + def __init__(self, config: MLCDVisionConfig): + super().__init__() + self.config = config + embed_dim = config.hidden_size + + self.embeddings = MLCDVisionEmbeddings(config) + self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) + self.encoder = MLCDEncoder(config) + self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) + + self.vision_rotary_embedding = VisionRotaryEmbedding(config.hidden_size // config.num_attention_heads // 2) + self.class_pos_emb = nn.Parameter(torch.randn(1, config.hidden_size // config.num_attention_heads // 2)) + + + def rot_pos_emb(self, grid_thw): + pos_ids = [] + for t, h, w in grid_thw: + hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w) + hpos_ids = hpos_ids.reshape(h, 1, w, 1) + hpos_ids = hpos_ids.permute(0, 2, 1, 3) + hpos_ids = hpos_ids.flatten() + + wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1) + wpos_ids = wpos_ids.reshape(h, 1, w, 1) + wpos_ids = wpos_ids.permute(0, 2, 1, 3) + wpos_ids = wpos_ids.flatten() + pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1)) + pos_ids = torch.cat(pos_ids, dim=0) + max_grid_size = grid_thw[:, 1:].max() + rotary_pos_emb_full = self.vision_rotary_embedding(max_grid_size) + rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1) + return rotary_pos_emb + + + def forward( + self, + pixel_values: Optional[torch.FloatTensor] = None, + # output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPooling]: + r""" + Returns: + + """ + + twh = (1, pixel_values.size(3) // self.config.patch_size, pixel_values.size(2) // self.config.patch_size) + rotary_pos_emb = self.rot_pos_emb(torch.tensor([twh], device=pixel_values.device)) + rotary_pos_emb = torch.cat([self.class_pos_emb, rotary_pos_emb], dim=0) + + # output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if pixel_values is None: + raise ValueError("You have to specify pixel_values") + + hidden_states = self.embeddings(pixel_values) + hidden_states = self.pre_layrnorm(hidden_states) + + encoder_outputs = self.encoder( + inputs_embeds=hidden_states, + rotary_pos_emb=rotary_pos_emb, + # output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + last_hidden_state = encoder_outputs[0] + pooled_output = last_hidden_state[:, 0, :] + pooled_output = self.post_layernorm(pooled_output) + + if not return_dict: + return (last_hidden_state, pooled_output) + encoder_outputs[1:] + + return BaseModelOutputWithPooling( + last_hidden_state=last_hidden_state, + pooler_output=pooled_output, + hidden_states=encoder_outputs.hidden_states, + # attentions=encoder_outputs.attentions, + ) + + +class MLCDPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + config_class = MLCDVisionConfig + base_model_prefix = "mlcd" + supports_gradient_checkpointing = True + _supports_sdpa = True + # _supports_flash_attn_2 = True + + def _init_weights(self, module): + """Initialize the weights""" + factor = self.config.initializer_factor + if isinstance(module, MLCDVisionEmbeddings): + factor = self.config.initializer_factor + nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor) + nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor) + elif isinstance(module, MLCDSdpaAttention): + factor = self.config.initializer_factor + in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor + out_proj_std = (module.embed_dim**-0.5) * factor + nn.init.normal_(module.q_proj.weight, std=in_proj_std) + nn.init.normal_(module.k_proj.weight, std=in_proj_std) + nn.init.normal_(module.v_proj.weight, std=in_proj_std) + nn.init.normal_(module.out_proj.weight, std=out_proj_std) + elif isinstance(module, MLCDMLP): + factor = self.config.initializer_factor + in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor + fc_std = (2 * module.config.hidden_size) ** -0.5 * factor + nn.init.normal_(module.fc1.weight, std=fc_std) + nn.init.normal_(module.fc2.weight, std=in_proj_std) + + + if isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) + if isinstance(module, nn.Linear) and module.bias is not None: + module.bias.data.zero_() + + +class MLCDVisionModel(MLCDPreTrainedModel): + config_class = MLCDVisionConfig + main_input_name = "pixel_values" + _no_split_modules = ["MLCDEncoderLayer"] + + def __init__(self, config: MLCDVisionConfig): + super().__init__(config) + self.vision_model = MLCDVisionTransformer(config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self) -> nn.Module: + return self.vision_model.embeddings.patch_embedding + + def forward( + self, + pixel_values: Optional[torch.FloatTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPooling]: + r""" + Returns: + + Examples: + + ```python + >>> from PIL import Image + >>> import requests + >>> from transformers import AutoProcessor, MLCDVisionModel + + >>> model = MLCDVisionModel.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14") + >>> processor = AutoProcessor.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14") + + >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" + >>> image = Image.open(requests.get(url, stream=True).raw) + + >>> inputs = processor(images=image, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> last_hidden_state = outputs.last_hidden_state + >>> pooled_output = outputs.pooler_output # pooled CLS states + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + return self.vision_model( + pixel_values=pixel_values, + # output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) \ No newline at end of file diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_projector/builder.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_projector/builder.py" new file mode 100644 index 0000000000000000000000000000000000000000..3122a0c3bc5b50f1c921ba9b186fd736f018c9cf --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_projector/builder.py" @@ -0,0 +1,65 @@ +import torch +import torch.nn as nn +import re + +from .pooler_projector import PoolerProjector + + +class IdentityMap(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x, *args, **kwargs): + return x + + @property + def config(self): + return {"mm_projector_type": "identity"} + + +class SimpleResBlock(nn.Module): + def __init__(self, channels): + super().__init__() + self.pre_norm = nn.LayerNorm(channels) + + self.proj = nn.Sequential(nn.Linear(channels, channels), nn.GELU(), nn.Linear(channels, channels)) + + def forward(self, x): + x = self.pre_norm(x) + return x + self.proj(x) + + +def build_vision_projector(config, delay_load=False, **kwargs): + projector_type = getattr(config, "mm_projector_type", "linear") + + if projector_type == "linear": + return nn.Linear(config.mm_hidden_size, config.hidden_size) + + if projector_type == "pooler": + return PoolerProjector(config, kwargs["vision_cfg"]) + + mlp_gelu_match = re.match(r"^mlp(\d+)x_gelu$", projector_type) + if mlp_gelu_match: + mlp_depth = int(mlp_gelu_match.group(1)) + modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)] + for _ in range(1, mlp_depth): + modules.append(nn.GELU()) + modules.append(nn.Linear(config.hidden_size, config.hidden_size)) + return nn.Sequential(*modules) + + mlp_gelu_resnet_match = re.match(r"^mlp(\d+)x_res(\d+)x_gelu$", projector_type) + if mlp_gelu_resnet_match: + mlp_depth = int(mlp_gelu_resnet_match.group(1)) + res_depth = int(mlp_gelu_resnet_match.group(2)) + modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)] + for _ in range(1, mlp_depth): + modules.append(nn.GELU()) + modules.append(nn.Linear(config.hidden_size, config.hidden_size)) + for _ in range(res_depth): + modules.append(SimpleResBlock(config.hidden_size)) + return nn.Sequential(*modules) + + if projector_type == "identity": + return IdentityMap() + + raise ValueError(f"Unknown projector type: {projector_type}") diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_projector/pooler_projector.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_projector/pooler_projector.py" new file mode 100644 index 0000000000000000000000000000000000000000..ce5a2e05fa44ad2978272aea6dcf0aa9ca135e55 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_projector/pooler_projector.py" @@ -0,0 +1,33 @@ +import torch +import torch.nn as nn + +import math + +from transformers.models.clip.modeling_clip import CLIPVisionModel + + +class PoolerProjector(nn.Module): + def __init__(self, config, vision_cfg): + super().__init__() + self._config = config + self.hw = vision_cfg.image_size // vision_cfg.patch_size + + self.conv_pool = nn.Conv2d(config.mm_hidden_size, config.hidden_size, kernel_size=2, stride=2) + + self.proj = nn.Sequential( + nn.GELU(), + nn.Linear(config.hidden_size, config.hidden_size), + ) + + def forward(self, x, *args, **kwargs): + height = width = self.hw + assert height * width == x.shape[1] + x = x.view(x.shape[0], height, width, -1).permute(0, 3, 1, 2) + x = self.conv_pool(x) + x = x.flatten(2).transpose(1, 2) + x = self.proj(x) + return x + + @property + def config(self): + return {"mm_projector_type": "pooler"} diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/builder.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/builder.py" new file mode 100644 index 0000000000000000000000000000000000000000..7a4b207f3bded33b89ddef3899233c3825d91701 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/builder.py" @@ -0,0 +1,34 @@ +import torch + +from .masked_drop import MaskedDrop +from .spatial_pool import SpatialPool +from .perceiver import PerceiverResampler +from .qformer import Qformer + + +class IdentityMap(torch.nn.Module): + def __init__(self): + super().__init__() + + def forward(self, x, *args, **kwargs): + return x + + @property + def config(self): + return {"mm_resampler_type": None} + + +def build_vision_resampler(model_args, delay_load=False, **kwargs): + resampler_type = getattr(model_args, "mm_resampler_type", None) + if resampler_type == "masked_drop": + return MaskedDrop(model_args) + elif resampler_type == "spatial_pool": + return SpatialPool(model_args, **kwargs) + elif resampler_type == "perceiver": + return PerceiverResampler(model_args, **kwargs) + elif resampler_type == "qformer": + return Qformer(model_args, **kwargs) + elif resampler_type is None: + return IdentityMap() + + raise ValueError(f"Unknown resampler type: {resampler_type}") diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/masked_drop.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/masked_drop.py" new file mode 100644 index 0000000000000000000000000000000000000000..03f0bf0b259ff5d96adea4aad91ee5498d459030 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/masked_drop.py" @@ -0,0 +1,80 @@ +import torch +import torch.nn as nn + +import random + + +class MaskedDrop(nn.Module): + def __init__(self, model_args): + super().__init__() + + self.mode = model_args.mm_mask_drop_mode + self.skip_percentage = model_args.mm_mask_drop_skip_percentage + self.ratio = model_args.mm_mask_drop_ratio + self.ratio_upper = model_args.mm_mask_drop_ratio_upper + self.ratio_lower = model_args.mm_mask_drop_ratio_lower + + def forward(self, image_features, *args, **kwargs): + + if not self.training: + return image_features + + if self.skip_percentage > random.random(): + return image_features + + masked_features = [] + + for image_feature in image_features: + num_tokens = image_feature.shape[0] + if self.mode == "fixed": + num_keep = int(num_tokens * self.ratio) + masked_features.append(self.random_masking(image_feature.unsqueeze(0), num_keep)[0][0]) + elif self.mode == "range": + num_keep = int(num_tokens * random.uniform(self.ratio_lower, self.ratio_upper)) + masked_features.append(self.random_masking(image_feature.unsqueeze(0), num_keep)[0]) + elif self.mode == "cls_only": + masked_features.append(image_feature[0:1]) + else: + raise ValueError(f"Unexpected masked drop mode: {self.mode}") + + if self.mode not in ["range"] and (type(image_features) is not list or self.mode in ["cls_only"]): + masked_features = torch.stack(masked_features, dim=0) + + return masked_features + + @property + def config(self): + return { + "mm_resampler_type": "masked_drop", + "mm_mask_drop_mode": self.mode, + "mm_mask_drop_skip_percentage": self.skip_percentage, + "mm_mask_drop_ratio": self.ratio, + "mm_mask_drop_ratio_upper": self.ratio_upper, + "mm_mask_drop_ratio_lower": self.ratio_lower, + } + + def random_masking(self, x, len_keep): + """ + Perform per-sample random masking by per-sample shuffling. + Per-sample shuffling is done by argsort random noise. + x: [N, L, D], sequence + """ + N, L, D = x.shape # batch, length, dim + + noise = torch.rand(N, L, device=x.device) # noise in [0, 1] + + # sort noise for each sample + ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove + ids_restore = torch.argsort(ids_shuffle, dim=1) + + # keep the first subset + ids_keep = ids_shuffle[:, :len_keep] + x_masked = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D)) + + # generate the binary mask: 0 is keep, 1 is remove + mask = torch.ones([N, L], device=x.device) + mask[:, :len_keep] = 0 + # unshuffle to get the binary mask + mask = torch.gather(mask, dim=1, index=ids_restore) + + return x_masked, mask, ids_restore diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/perceiver.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/perceiver.py" new file mode 100644 index 0000000000000000000000000000000000000000..d6b17a559b2225832c7d87c4fb6894617779b9c1 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/perceiver.py" @@ -0,0 +1,155 @@ +""" +Taken from https://github.com/lucidrains/flamingo-pytorch +""" + +import torch +from einops import rearrange, repeat + +try: + from einops_exts import rearrange_many +except: + pass + +from torch import einsum, nn + + +def exists(val): + return val is not None + + +def FeedForward(dim, mult=4): + inner_dim = int(dim * mult) + return nn.Sequential( + nn.LayerNorm(dim), + nn.Linear(dim, inner_dim, bias=False), + nn.GELU(), + nn.Linear(inner_dim, dim, bias=False), + ) + + +class PerceiverAttention(nn.Module): + def __init__(self, *, dim, dim_head=64, heads=8): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + inner_dim = dim_head * heads + + self.norm_media = nn.LayerNorm(dim) + self.norm_latents = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + def forward(self, x, latents): + """ + Args: + x (torch.Tensor): image features + shape (b, T, n1, D) + latent (torch.Tensor): latent features + shape (b, T, n2, D) + """ + x = self.norm_media(x) + latents = self.norm_latents(latents) + + h = self.heads + + q = self.to_q(latents) + kv_input = torch.cat((x, latents), dim=-2) + k, v = self.to_kv(kv_input).chunk(2, dim=-1) + q, k, v = rearrange_many((q, k, v), "b t n (h d) -> b h t n d", h=h) + q = q * self.scale + + # attention + sim = einsum("... i d, ... j d -> ... i j", q, k) + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + attn = sim.softmax(dim=-1) + + out = einsum("... i j, ... j d -> ... i d", attn, v) + out = rearrange(out, "b h t n d -> b t n (h d)", h=h) + return self.to_out(out) + + +class PerceiverResamplerModule(nn.Module): + def __init__( + self, + *, + dim, + depth=6, + dim_head=64, + heads=8, + num_latents=64, + max_num_media=None, + max_num_frames=None, + ff_mult=4, + ): + super().__init__() + self.latents = nn.Parameter(torch.randn(num_latents, dim)) + self.frame_embs = nn.Parameter(torch.randn(max_num_frames, dim)) if exists(max_num_frames) else None + self.media_time_embs = nn.Parameter(torch.randn(max_num_media, 1, dim)) if exists(max_num_media) else None + + self.layers = nn.ModuleList([]) + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads), + FeedForward(dim=dim, mult=ff_mult) if ff_mult > 0 else nn.Identity(), + ] + ) + ) + + self.norm = nn.LayerNorm(dim) + + def forward(self, x): + """ + Args: + x (torch.Tensor): image features + shape (b, T, F, v, D) + Returns: + shape (b, T, n, D) where n is self.num_latents + """ + b, T, F, v = x.shape[:4] + + # frame and media time embeddings + if exists(self.frame_embs): + frame_embs = repeat(self.frame_embs[:F], "F d -> b T F v d", b=b, T=T, v=v) + x = x + frame_embs + x = rearrange(x, "b T F v d -> b T (F v) d") # flatten the frame and spatial dimensions + if exists(self.media_time_embs): + x = x + self.media_time_embs[:T] + + # blocks + latents = repeat(self.latents, "n d -> b T n d", b=b, T=T) + for attn, ff in self.layers: + latents = attn(x, latents) + latents + latents = ff(latents) + latents + return self.norm(latents) + + +class PerceiverResampler(nn.Module): + def __init__(self, model_args, vision_tower): + super().__init__() + + self.depth = model_args.mm_perceiver_depth + self.num_latents = model_args.mm_perceiver_latents + self.ff_mult = model_args.mm_perceiver_ff_mult + self.pretrained = model_args.mm_perceiver_pretrained + + self.perceiver = PerceiverResamplerModule(dim=vision_tower.hidden_size, depth=self.depth, num_latents=self.num_latents, ff_mult=self.ff_mult) + + if self.pretrained is not None: + self.load_state_dict(torch.load(self.pretrained)) + + def forward(self, image_features, *args, **kwargs): + return self.perceiver(image_features[:, None, None]).squeeze(1) + + @property + def config(self): + return { + "mm_resampler_type": "perceiver", + "mm_perceiver_depth": self.depth, + "mm_perceiver_latents": self.num_latents, + "mm_perceiver_ff_mult": self.ff_mult, + "mm_perceiver_pretrained": self.pretrained, + } diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/qformer.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/qformer.py" new file mode 100644 index 0000000000000000000000000000000000000000..b86754c24adbfa5ce34e37ee4726c74e3b7f910f --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/qformer.py" @@ -0,0 +1,1160 @@ +""" + * Copyright (c) 2023, salesforce.com, inc. + * All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + * By Junnan Li + * Based on huggingface code base + * https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/bert +""" + +import math +import os +import warnings +from dataclasses import dataclass +from typing import Optional, Tuple, Dict, Any + +import torch +from torch import Tensor, device, dtype, nn +import torch.utils.checkpoint +from torch import nn +from torch.nn import CrossEntropyLoss +import torch.nn.functional as F + +from transformers.activations import ACT2FN +from transformers.file_utils import ( + ModelOutput, +) +from transformers.modeling_outputs import ( + BaseModelOutputWithPastAndCrossAttentions, + BaseModelOutputWithPoolingAndCrossAttentions, + CausalLMOutputWithCrossAttentions, + MaskedLMOutput, + MultipleChoiceModelOutput, + NextSentencePredictorOutput, + QuestionAnsweringModelOutput, + SequenceClassifierOutput, + TokenClassifierOutput, +) +from transformers.modeling_utils import ( + PreTrainedModel, + apply_chunking_to_forward, + find_pruneable_heads_and_indices, + prune_linear_layer, +) +from transformers.utils import logging +from transformers.models.bert.configuration_bert import BertConfig + +logger = logging.get_logger(__name__) + + +def disabled_train(self, mode=True): + """Overwrite model.train with this function to make sure train/eval mode + does not change anymore.""" + return self + + +class BertEmbeddings(nn.Module): + """Construct the embeddings from word and position embeddings.""" + + def __init__(self, config): + super().__init__() + self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) + self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) + + # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load + # any TensorFlow checkpoint file + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + # position_ids (1, len position emb) is contiguous in memory and exported when serialized + self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) + self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") + + self.config = config + + def forward( + self, + input_ids=None, + position_ids=None, + query_embeds=None, + past_key_values_length=0, + ): + if input_ids is not None: + seq_length = input_ids.size()[1] + else: + seq_length = 0 + + if position_ids is None: + position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length].clone() + + if input_ids is not None: + embeddings = self.word_embeddings(input_ids) + if self.position_embedding_type == "absolute": + position_embeddings = self.position_embeddings(position_ids) + embeddings = embeddings + position_embeddings + + if query_embeds is not None: + embeddings = torch.cat((query_embeds, embeddings), dim=1) + else: + embeddings = query_embeds + + embeddings = self.LayerNorm(embeddings) + embeddings = self.dropout(embeddings) + return embeddings + + +class BertSelfAttention(nn.Module): + def __init__(self, config, is_cross_attention): + super().__init__() + self.config = config + if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): + raise ValueError("The hidden size (%d) is not a multiple of the number of attention " "heads (%d)" % (config.hidden_size, config.num_attention_heads)) + + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + self.query = nn.Linear(config.hidden_size, self.all_head_size) + if is_cross_attention: + self.key = nn.Linear(config.encoder_width, self.all_head_size) + self.value = nn.Linear(config.encoder_width, self.all_head_size) + else: + self.key = nn.Linear(config.hidden_size, self.all_head_size) + self.value = nn.Linear(config.hidden_size, self.all_head_size) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") + if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": + self.max_position_embeddings = config.max_position_embeddings + self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) + self.save_attention = False + + def save_attn_gradients(self, attn_gradients): + self.attn_gradients = attn_gradients + + def get_attn_gradients(self): + return self.attn_gradients + + def save_attention_map(self, attention_map): + self.attention_map = attention_map + + def get_attention_map(self): + return self.attention_map + + def transpose_for_scores(self, x): + new_x_shape = x.size()[:-1] + ( + self.num_attention_heads, + self.attention_head_size, + ) + x = x.view(*new_x_shape) + return x.permute(0, 2, 1, 3) + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_value=None, + output_attentions=False, + ): + + # If this is instantiated as a cross-attention module, the keys + # and values come from an encoder; the attention mask needs to be + # such that the encoder's padding tokens are not attended to. + is_cross_attention = encoder_hidden_states is not None + + if is_cross_attention: + key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) + value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) + attention_mask = encoder_attention_mask + elif past_key_value is not None: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + key_layer = torch.cat([past_key_value[0], key_layer], dim=2) + value_layer = torch.cat([past_key_value[1], value_layer], dim=2) + else: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + + mixed_query_layer = self.query(hidden_states) + + query_layer = self.transpose_for_scores(mixed_query_layer) + + past_key_value = (key_layer, value_layer) + + # Take the dot product between "query" and "key" to get the raw attention scores. + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + + if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": + seq_length = hidden_states.size()[1] + position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) + position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1) + distance = position_ids_l - position_ids_r + positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) + positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility + + if self.position_embedding_type == "relative_key": + relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) + attention_scores = attention_scores + relative_position_scores + elif self.position_embedding_type == "relative_key_query": + relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) + relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) + attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key + + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + if attention_mask is not None: + # Apply the attention mask is (precomputed for all layers in BertModel forward() function) + attention_scores = attention_scores + attention_mask + + # Normalize the attention scores to probabilities. + attention_probs = nn.Softmax(dim=-1)(attention_scores) + + if is_cross_attention and self.save_attention: + self.save_attention_map(attention_probs) + attention_probs.register_hook(self.save_attn_gradients) + + # This is actually dropping out entire tokens to attend to, which might + # seem a bit unusual, but is taken from the original Transformer paper. + attention_probs_dropped = self.dropout(attention_probs) + + # Mask heads if we want to + if head_mask is not None: + attention_probs_dropped = attention_probs_dropped * head_mask + + context_layer = torch.matmul(attention_probs_dropped, value_layer) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(*new_context_layer_shape) + + outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) + + outputs = outputs + (past_key_value,) + return outputs + + +class BertSelfOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states, input_tensor): + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +class BertAttention(nn.Module): + def __init__(self, config, is_cross_attention=False): + super().__init__() + self.self = BertSelfAttention(config, is_cross_attention) + self.output = BertSelfOutput(config) + self.pruned_heads = set() + + def prune_heads(self, heads): + if len(heads) == 0: + return + heads, index = find_pruneable_heads_and_indices( + heads, + self.self.num_attention_heads, + self.self.attention_head_size, + self.pruned_heads, + ) + + # Prune linear layers + self.self.query = prune_linear_layer(self.self.query, index) + self.self.key = prune_linear_layer(self.self.key, index) + self.self.value = prune_linear_layer(self.self.value, index) + self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) + + # Update hyper params and store pruned heads + self.self.num_attention_heads = self.self.num_attention_heads - len(heads) + self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads + self.pruned_heads = self.pruned_heads.union(heads) + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_value=None, + output_attentions=False, + ): + self_outputs = self.self( + hidden_states, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + ) + attention_output = self.output(self_outputs[0], hidden_states) + + outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them + return outputs + + +class BertIntermediate(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states): + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + return hidden_states + + +class BertOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states, input_tensor): + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +class BertLayer(nn.Module): + def __init__(self, config, layer_num): + super().__init__() + self.config = config + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = BertAttention(config) + self.layer_num = layer_num + if self.config.add_cross_attention and layer_num % self.config.cross_attention_freq == 0: + self.crossattention = BertAttention(config, is_cross_attention=self.config.add_cross_attention) + self.has_cross_attention = True + else: + self.has_cross_attention = False + self.intermediate = BertIntermediate(config) + self.output = BertOutput(config) + + self.intermediate_query = BertIntermediate(config) + self.output_query = BertOutput(config) + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_value=None, + output_attentions=False, + query_length=0, + ): + # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 + self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None + self_attention_outputs = self.attention( + hidden_states, + attention_mask, + head_mask, + output_attentions=output_attentions, + past_key_value=self_attn_past_key_value, + ) + attention_output = self_attention_outputs[0] + outputs = self_attention_outputs[1:-1] + + present_key_value = self_attention_outputs[-1] + + if query_length > 0: + query_attention_output = attention_output[:, :query_length, :] + + if self.has_cross_attention: + assert encoder_hidden_states is not None, "encoder_hidden_states must be given for cross-attention layers" + cross_attention_outputs = self.crossattention( + query_attention_output, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + output_attentions=output_attentions, + ) + query_attention_output = cross_attention_outputs[0] + outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights + + layer_output = apply_chunking_to_forward( + self.feed_forward_chunk_query, + self.chunk_size_feed_forward, + self.seq_len_dim, + query_attention_output, + ) + if attention_output.shape[1] > query_length: + layer_output_text = apply_chunking_to_forward( + self.feed_forward_chunk, + self.chunk_size_feed_forward, + self.seq_len_dim, + attention_output[:, query_length:, :], + ) + layer_output = torch.cat([layer_output, layer_output_text], dim=1) + else: + layer_output = apply_chunking_to_forward( + self.feed_forward_chunk, + self.chunk_size_feed_forward, + self.seq_len_dim, + attention_output, + ) + outputs = (layer_output,) + outputs + + outputs = outputs + (present_key_value,) + + return outputs + + def feed_forward_chunk(self, attention_output): + intermediate_output = self.intermediate(attention_output) + layer_output = self.output(intermediate_output, attention_output) + return layer_output + + def feed_forward_chunk_query(self, attention_output): + intermediate_output = self.intermediate_query(attention_output) + layer_output = self.output_query(intermediate_output, attention_output) + return layer_output + + +class BertEncoder(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.layer = nn.ModuleList([BertLayer(config, i) for i in range(config.num_hidden_layers)]) + + def forward( + self, + hidden_states, + attention_mask=None, + head_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_values=None, + use_cache=None, + output_attentions=False, + output_hidden_states=False, + return_dict=True, + query_length=0, + ): + all_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None + + next_decoder_cache = () if use_cache else None + + for i in range(self.config.num_hidden_layers): + layer_module = self.layer[i] + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + layer_head_mask = head_mask[i] if head_mask is not None else None + past_key_value = past_key_values[i] if past_key_values is not None else None + + if getattr(self.config, "gradient_checkpointing", False) and self.training: + + if use_cache: + logger.warn("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...") + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs, past_key_value, output_attentions, query_length) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(layer_module), + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + ) + else: + layer_outputs = layer_module( + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + query_length, + ) + + hidden_states = layer_outputs[0] + if use_cache: + next_decoder_cache += (layer_outputs[-1],) + if output_attentions: + all_self_attentions = all_self_attentions + (layer_outputs[1],) + all_cross_attentions = all_cross_attentions + (layer_outputs[2],) + + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + if not return_dict: + return tuple( + v + for v in [ + hidden_states, + next_decoder_cache, + all_hidden_states, + all_self_attentions, + all_cross_attentions, + ] + if v is not None + ) + return BaseModelOutputWithPastAndCrossAttentions( + last_hidden_state=hidden_states, + past_key_values=next_decoder_cache, + hidden_states=all_hidden_states, + attentions=all_self_attentions, + cross_attentions=all_cross_attentions, + ) + + +class BertPooler(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.activation = nn.Tanh() + + def forward(self, hidden_states): + # We "pool" the model by simply taking the hidden state corresponding + # to the first token. + first_token_tensor = hidden_states[:, 0] + pooled_output = self.dense(first_token_tensor) + pooled_output = self.activation(pooled_output) + return pooled_output + + +class BertPredictionHeadTransform(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + if isinstance(config.hidden_act, str): + self.transform_act_fn = ACT2FN[config.hidden_act] + else: + self.transform_act_fn = config.hidden_act + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + def forward(self, hidden_states): + hidden_states = self.dense(hidden_states) + hidden_states = self.transform_act_fn(hidden_states) + hidden_states = self.LayerNorm(hidden_states) + return hidden_states + + +class BertLMPredictionHead(nn.Module): + def __init__(self, config): + super().__init__() + self.transform = BertPredictionHeadTransform(config) + + # The output weights are the same as the input embeddings, but there is + # an output-only bias for each token. + self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + self.bias = nn.Parameter(torch.zeros(config.vocab_size)) + + # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` + self.decoder.bias = self.bias + + def forward(self, hidden_states): + hidden_states = self.transform(hidden_states) + hidden_states = self.decoder(hidden_states) + return hidden_states + + +class BertOnlyMLMHead(nn.Module): + def __init__(self, config): + super().__init__() + self.predictions = BertLMPredictionHead(config) + + def forward(self, sequence_output): + prediction_scores = self.predictions(sequence_output) + return prediction_scores + + +class BertPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = BertConfig + base_model_prefix = "bert" + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, (nn.Linear, nn.Embedding)): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) + if isinstance(module, nn.Linear) and module.bias is not None: + module.bias.data.zero_() + + +class BertModel(BertPreTrainedModel): + """ + The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of + cross-attention is added between the self-attention layers, following the architecture described in `Attention is + all you need `__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, + Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. + argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an + input to the forward pass. + """ + + def __init__(self, config, add_pooling_layer=False): + super().__init__(config) + self.config = config + + self.embeddings = BertEmbeddings(config) + + self.encoder = BertEncoder(config) + + self.pooler = BertPooler(config) if add_pooling_layer else None + + self.init_weights() + + def get_input_embeddings(self): + return self.embeddings.word_embeddings + + def set_input_embeddings(self, value): + self.embeddings.word_embeddings = value + + def _prune_heads(self, heads_to_prune): + """ + Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base + class PreTrainedModel + """ + for layer, heads in heads_to_prune.items(): + self.encoder.layer[layer].attention.prune_heads(heads) + + def get_extended_attention_mask( + self, + attention_mask: Tensor, + input_shape: Tuple[int], + device: device, + is_decoder: bool, + has_query: bool = False, + ) -> Tensor: + """ + Makes broadcastable attention and causal masks so that future and masked tokens are ignored. + + Arguments: + attention_mask (:obj:`torch.Tensor`): + Mask with ones indicating tokens to attend to, zeros for tokens to ignore. + input_shape (:obj:`Tuple[int]`): + The shape of the input to the model. + device: (:obj:`torch.device`): + The device of the input to the model. + + Returns: + :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`. + """ + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + if attention_mask.dim() == 3: + extended_attention_mask = attention_mask[:, None, :, :] + elif attention_mask.dim() == 2: + # Provided a padding mask of dimensions [batch_size, seq_length] + # - if the model is a decoder, apply a causal mask in addition to the padding mask + # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] + if is_decoder: + batch_size, seq_length = input_shape + + seq_ids = torch.arange(seq_length, device=device) + causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None] + + # add a prefix ones mask to the causal mask + # causal and attention masks must have same type with pytorch version < 1.3 + causal_mask = causal_mask.to(attention_mask.dtype) + + if causal_mask.shape[1] < attention_mask.shape[1]: + prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1] + if has_query: # UniLM style attention mask + causal_mask = torch.cat( + [ + torch.zeros( + (batch_size, prefix_seq_len, seq_length), + device=device, + dtype=causal_mask.dtype, + ), + causal_mask, + ], + axis=1, + ) + causal_mask = torch.cat( + [ + torch.ones( + (batch_size, causal_mask.shape[1], prefix_seq_len), + device=device, + dtype=causal_mask.dtype, + ), + causal_mask, + ], + axis=-1, + ) + extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :] + else: + extended_attention_mask = attention_mask[:, None, None, :] + else: + raise ValueError("Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(input_shape, attention_mask.shape)) + + # Since attention_mask is 1.0 for positions we want to attend and 0.0 for + # masked positions, this operation will create a tensor which is 0.0 for + # positions we want to attend and -10000.0 for masked positions. + # Since we are adding it to the raw scores before the softmax, this is + # effectively the same as removing these entirely. + extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility + extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 + return extended_attention_mask + + def forward( + self, + input_ids=None, + attention_mask=None, + position_ids=None, + head_mask=None, + query_embeds=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + past_key_values=None, + use_cache=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + is_decoder=False, + ): + r""" + encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` + (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` + instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. + use_cache (:obj:`bool`, `optional`): + If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up + decoding (see :obj:`past_key_values`). + """ + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # use_cache = use_cache if use_cache is not None else self.config.use_cache + + if input_ids is None: + assert query_embeds is not None, "You have to specify query_embeds when input_ids is None" + + # past_key_values_length + past_key_values_length = past_key_values[0][0].shape[2] - self.config.query_length if past_key_values is not None else 0 + + query_length = query_embeds.shape[1] if query_embeds is not None else 0 + + embedding_output = self.embeddings( + input_ids=input_ids, + position_ids=position_ids, + query_embeds=query_embeds, + past_key_values_length=past_key_values_length, + ) + + input_shape = embedding_output.size()[:-1] + batch_size, seq_length = input_shape + device = embedding_output.device + + if attention_mask is None: + attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) + + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + if is_decoder: + extended_attention_mask = self.get_extended_attention_mask( + attention_mask, + input_ids.shape, + device, + is_decoder, + has_query=(query_embeds is not None), + ) + else: + extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, device, is_decoder) + + # If a 2D or 3D attention mask is provided for the cross-attention + # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] + if encoder_hidden_states is not None: + if type(encoder_hidden_states) == list: + encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size() + else: + ( + encoder_batch_size, + encoder_sequence_length, + _, + ) = encoder_hidden_states.size() + encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) + + if type(encoder_attention_mask) == list: + encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask] + elif encoder_attention_mask is None: + encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) + encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) + else: + encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) + else: + encoder_extended_attention_mask = None + + # Prepare head mask if needed + # 1.0 in head_mask indicate we keep the head + # attention_probs has shape bsz x n_heads x N x N + # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] + # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] + head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) + + encoder_outputs = self.encoder( + embedding_output, + attention_mask=extended_attention_mask, + head_mask=head_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_extended_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + query_length=query_length, + ) + sequence_output = encoder_outputs[0] + pooled_output = self.pooler(sequence_output) if self.pooler is not None else None + + if not return_dict: + return (sequence_output, pooled_output) + encoder_outputs[1:] + + return BaseModelOutputWithPoolingAndCrossAttentions( + last_hidden_state=sequence_output, + pooler_output=pooled_output, + past_key_values=encoder_outputs.past_key_values, + hidden_states=encoder_outputs.hidden_states, + attentions=encoder_outputs.attentions, + cross_attentions=encoder_outputs.cross_attentions, + ) + + +class BertLMHeadModel(BertPreTrainedModel): + + _keys_to_ignore_on_load_unexpected = [r"pooler"] + _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] + + def __init__(self, config): + super().__init__(config) + + self.bert = BertModel(config, add_pooling_layer=False) + self.cls = BertOnlyMLMHead(config) + + self.init_weights() + + def get_output_embeddings(self): + return self.cls.predictions.decoder + + def set_output_embeddings(self, new_embeddings): + self.cls.predictions.decoder = new_embeddings + + def forward( + self, + input_ids=None, + attention_mask=None, + position_ids=None, + head_mask=None, + query_embeds=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + labels=None, + past_key_values=None, + use_cache=True, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + return_logits=False, + is_decoder=True, + reduction="mean", + ): + r""" + encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in + ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are + ignored (masked), the loss is only computed for the tokens with labels n ``[0, ..., config.vocab_size]`` + past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` + (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` + instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. + use_cache (:obj:`bool`, `optional`): + If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up + decoding (see :obj:`past_key_values`). + Returns: + Example:: + >>> from transformers import BertTokenizer, BertLMHeadModel, BertConfig + >>> import torch + >>> tokenizer = BertTokenizer.from_pretrained('bert-base-cased') + >>> config = BertConfig.from_pretrained("bert-base-cased") + >>> model = BertLMHeadModel.from_pretrained('bert-base-cased', config=config) + >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + >>> outputs = model(**inputs) + >>> prediction_logits = outputs.logits + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + if labels is not None: + use_cache = False + if past_key_values is not None: + query_embeds = None + + outputs = self.bert( + input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + head_mask=head_mask, + query_embeds=query_embeds, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + is_decoder=is_decoder, + ) + + sequence_output = outputs[0] + if query_embeds is not None: + sequence_output = outputs[0][:, query_embeds.shape[1] :, :] + + prediction_scores = self.cls(sequence_output) + + if return_logits: + return prediction_scores[:, :-1, :].contiguous() + + lm_loss = None + if labels is not None: + # we are doing next-token prediction; shift prediction scores and input ids by one + shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous() + labels = labels[:, 1:].contiguous() + loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1) + lm_loss = loss_fct( + shifted_prediction_scores.view(-1, self.config.vocab_size), + labels.view(-1), + ) + if reduction == "none": + lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1) + + if not return_dict: + output = (prediction_scores,) + outputs[2:] + return ((lm_loss,) + output) if lm_loss is not None else output + + return CausalLMOutputWithCrossAttentions( + loss=lm_loss, + logits=prediction_scores, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + cross_attentions=outputs.cross_attentions, + ) + + def prepare_inputs_for_generation(self, input_ids, query_embeds, past=None, attention_mask=None, **model_kwargs): + # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly + if attention_mask is None: + attention_mask = input_ids.new_ones(input_ids.shape) + query_mask = input_ids.new_ones(query_embeds.shape[:-1]) + attention_mask = torch.cat([query_mask, attention_mask], dim=-1) + + # cut decoder_input_ids if past is used + if past is not None: + input_ids = input_ids[:, -1:] + + return { + "input_ids": input_ids, + "query_embeds": query_embeds, + "attention_mask": attention_mask, + "past_key_values": past, + "encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None), + "encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None), + "is_decoder": True, + } + + def _reorder_cache(self, past, beam_idx): + reordered_past = () + for layer_past in past: + reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) + return reordered_past + + +class BertForMaskedLM(BertPreTrainedModel): + + _keys_to_ignore_on_load_unexpected = [r"pooler"] + _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"] + + def __init__(self, config): + super().__init__(config) + + self.bert = BertModel(config, add_pooling_layer=False) + self.cls = BertOnlyMLMHead(config) + + self.init_weights() + + def get_output_embeddings(self): + return self.cls.predictions.decoder + + def set_output_embeddings(self, new_embeddings): + self.cls.predictions.decoder = new_embeddings + + def forward( + self, + input_ids=None, + attention_mask=None, + position_ids=None, + head_mask=None, + query_embeds=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + return_logits=False, + is_decoder=False, + ): + r""" + labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): + Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., + config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored + (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]`` + """ + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.bert( + input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + head_mask=head_mask, + query_embeds=query_embeds, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + is_decoder=is_decoder, + ) + + if query_embeds is not None: + sequence_output = outputs[0][:, query_embeds.shape[1] :, :] + prediction_scores = self.cls(sequence_output) + + if return_logits: + return prediction_scores + + masked_lm_loss = None + if labels is not None: + loss_fct = CrossEntropyLoss() # -100 index = padding token + masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) + + if not return_dict: + output = (prediction_scores,) + outputs[2:] + return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output + + return MaskedLMOutput( + loss=masked_lm_loss, + logits=prediction_scores, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class Qformer(nn.Module): + def __init__(self, model_args, vision_tower): + super().__init__() + + self.depth = model_args.mm_qformer_depth + self.num_latents = model_args.mm_qformer_latents + self.pretrained = model_args.mm_qformer_pretrained + + self.Qformer, self.query_tokens, self.ln_vision = self.build_Qformer(vision_tower.hidden_size, self.depth, self.num_latents) + + if self.pretrained is not None: + pretrained_dict = torch.load(self.pretrained, map_location="cpu")["model"] + pretrained_dict = {k: v for k, v in pretrained_dict.items() if not k.startswith("t5_proj")} + self.load_state_dict(pretrained_dict) + + def build_Qformer(self, vision_width, cross_attention_freq, num_query_token): + encoder_config = BertConfig.from_pretrained("bert-base-uncased") + encoder_config.encoder_width = vision_width + # insert cross-attention layer every other block + encoder_config.add_cross_attention = True + encoder_config.cross_attention_freq = cross_attention_freq + encoder_config.query_length = num_query_token + Qformer = BertLMHeadModel(config=encoder_config) + query_tokens = nn.Parameter(torch.zeros(1, num_query_token, encoder_config.hidden_size)) + query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range) + Qformer.cls = None + Qformer.bert.embeddings.word_embeddings = None + Qformer.bert.embeddings.position_embeddings = None + for layer in Qformer.bert.encoder.layer: + layer.output = None + layer.intermediate = None + return Qformer, query_tokens, nn.LayerNorm(vision_width) + + def forward(self, image_features, *args, **kwargs): + x = self.ln_vision(image_features) + image_atts = torch.ones(x.size()[:-1], dtype=torch.long).to(x.device) + + query_tokens = self.query_tokens.expand(x.shape[0], -1, -1) + query_output = self.Qformer.bert( + query_embeds=query_tokens, + encoder_hidden_states=x, + encoder_attention_mask=image_atts, + return_dict=True, + ) + + return query_output.last_hidden_state + + @property + def hidden_size(self): + return 768 + + @property + def config(self): + return { + "mm_resampler_type": "qformer", + "mm_qformer_depth": self.depth, + "mm_qformer_latents": self.num_latents, + "mm_qformer_pretrained": self.pretrained, + } diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/spatial_pool.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/spatial_pool.py" new file mode 100644 index 0000000000000000000000000000000000000000..4bdbe3aecc91183341816c800c8ad1fcfba9a169 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/llava/model/multimodal_resampler/spatial_pool.py" @@ -0,0 +1,45 @@ +import torch +import torch.nn as nn +import math + + +class SpatialPool(nn.Module): + def __init__(self, model_args, vision_tower): + super().__init__() + + self.mode = model_args.mm_spatial_pool_mode + self.stride = model_args.mm_spatial_pool_stride + self.out_channels = getattr(model_args, "mm_spatial_pool_out_channels", vision_tower.hidden_size) + + if self.mode == "average": + self.pool = nn.AvgPool2d(kernel_size=self.stride, stride=self.stride) + elif self.mode == "max": + self.pool = nn.MaxPool2d(kernel_size=self.stride, stride=self.stride) + elif self.mode == "conv": + self.pool = nn.Conv2d(in_channels=vision_tower.hidden_size, out_channels=self.out_channels, kernel_size=self.stride, stride=self.stride) + else: + raise ValueError(f"Unknown pooling mode: {self.pool}.") + + def forward(self, image_features, images, *args, **kwargs): + ori_W = int(math.sqrt(image_features.shape[1] * images.shape[3] // images.shape[2])) + ori_H = int(ori_W * images.shape[2] // images.shape[3]) + + B, _, F = image_features.shape + + image_features_spatial = image_features.view(B, ori_H, ori_H, F).permute(0, 3, 1, 2) + image_features_spatial_pool = self.pool(image_features_spatial) + + return image_features_spatial_pool.flatten(2).transpose(1, 2).contiguous() + + @property + def config(self): + return { + "mm_resampler_type": "spatial_pool", + "mm_spatial_pool_stride": self.stride, + "mm_spatial_pool_mode": self.mode, + "mm_spatial_pool_out_channels": self.out_channels, + } + + @property + def hidden_size(self): + return self.out_channels diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/trl/models/__init__.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/trl/models/__init__.py" new file mode 100644 index 0000000000000000000000000000000000000000..ec2034553379244d67d4e16a3537e631c9d0d100 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/trl/models/__init__.py" @@ -0,0 +1,35 @@ +# flake8: noqa + +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# 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 .modeling_base import PreTrainedModelWrapper, create_reference_model +from .modeling_value_head import AutoModelForCausalLMWithValueHead, AutoModelForSeq2SeqLMWithValueHead +from .utils import setup_chat_format + + +SUPPORTED_ARCHITECTURES = ( + AutoModelForCausalLMWithValueHead, + AutoModelForSeq2SeqLMWithValueHead, +) + +from ..import_utils import is_diffusers_available + + +if is_diffusers_available(): + from .modeling_sd_base import ( + DDPOPipelineOutput, + DDPOSchedulerOutput, + DDPOStableDiffusionPipeline, + DefaultDDPOStableDiffusionPipeline, + ) diff --git "a/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/trl/models/modeling_value_head.py" "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/trl/models/modeling_value_head.py" new file mode 100644 index 0000000000000000000000000000000000000000..f2ca25ee3a9c5176d82ad63e71ddf0ad582d74b6 --- /dev/null +++ "b/\344\271\213\345\211\215\347\232\204\344\273\243\347\240\201\347\211\210\346\234\254/\346\263\250\346\204\217\345\212\233\345\205\263\351\224\256\350\257\215\347\224\250\344\272\216sam\347\232\204/MedEvalKit/LLaVA-NeXT/trl/models/modeling_value_head.py" @@ -0,0 +1,421 @@ +# Copyright 2022 The HuggingFace Team. All rights reserved. +# +# 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 torch +import torch.nn as nn +from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM + +from .modeling_base import PreTrainedModelWrapper + + +class ValueHead(nn.Module): + r""" + The ValueHead class implements a head for GPT2 that returns a scalar for each output token. + """ + + def __init__(self, config, **kwargs): + super().__init__() + if not hasattr(config, "summary_dropout_prob"): + summary_dropout_prob = kwargs.pop("summary_dropout_prob", 0.1) + else: + summary_dropout_prob = config.summary_dropout_prob + + self.dropout = nn.Dropout(summary_dropout_prob) if summary_dropout_prob else nn.Identity() + + # some models such as OPT have a projection layer before the word embeddings - e.g. OPT-350m + if hasattr(config, "hidden_size"): + hidden_size = config.hidden_size + if hasattr(config, "word_embed_proj_dim"): + hidden_size = config.word_embed_proj_dim + elif hasattr(config, "is_encoder_decoder"): + if config.is_encoder_decoder and hasattr(config, "decoder"): + if hasattr(config.decoder, "hidden_size"): + hidden_size = config.decoder.hidden_size + + self.summary = nn.Linear(hidden_size, 1) + + self.flatten = nn.Flatten() + + def forward(self, hidden_states): + output = self.dropout(hidden_states) + + # For now force upcast in fp32 if needed. Let's keep the + # output in fp32 for numerical stability. + if output.dtype != self.summary.weight.dtype: + output = output.to(self.summary.weight.dtype) + + output = self.summary(output) + return output + + +class AutoModelForCausalLMWithValueHead(PreTrainedModelWrapper): + r""" + An autoregressive model with a value head in addition to the language model head. + This class inherits from `~trl.PreTrainedModelWrapper` and wraps a + `transformers.PreTrainedModel` class. The wrapper class supports classic functions + such as `from_pretrained`, `push_to_hub` and `generate`. To call a method of the wrapped + model, simply manipulate the `pretrained_model` attribute of this class. + + Class attributes: + - **transformers_parent_class** (`transformers.PreTrainedModel`) -- The parent class of the wrapped model. This + should be set to `transformers.AutoModelForCausalLM` for this class. + - **lm_head_namings** (`tuple`) -- A tuple of strings that are used to identify the language model head of the + wrapped model. This is set to `("lm_head", "embed_out")` for this class but can be changed for other models + in the future + - **supported_args** (`tuple`) -- A tuple of strings that are used to identify the arguments that are supported + by the `ValueHead` class. Currently, the supported args are: + - **summary_dropout_prob** (`float`, `optional`, defaults to `None`) -- The dropout probability for the + `ValueHead` class. + - **v_head_initializer_range** (`float`, `optional`, defaults to `0.2`) -- The initializer range for the + `ValueHead` if a specific initialization strategy is selected. + - **v_head_init_strategy** (`str`, `optional`, defaults to `None`) -- The initialization strategy for the + `ValueHead`. Currently, the supported strategies are: + - **`None`** -- Initializes the weights of the `ValueHead` with a random distribution. This is the default + strategy. + - **"normal"** -- Initializes the weights of the `ValueHead` with a normal distribution. + + """ + + transformers_parent_class = AutoModelForCausalLM + lm_head_namings = ["lm_head", "embed_out"] + supported_args = ( + "summary_dropout_prob", + "v_head_initializer_range", + "v_head_init_strategy", + ) + + def __init__(self, pretrained_model, **kwargs): + r""" + Initializes the model. + + Args: + pretrained_model (`transformers.PreTrainedModel`): + The model to wrap. It should be a causal language model such as GPT2. + or any model mapped inside the `AutoModelForCausalLM` class. + kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the `ValueHead` class. + """ + super().__init__(pretrained_model, **kwargs) + v_head_kwargs, _, _ = self._split_kwargs(kwargs) + + if not any(hasattr(self.pretrained_model, attribute) for attribute in self.lm_head_namings): + raise ValueError("The model does not have a language model head, please use a model that has one.") + + self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs) + + self._init_weights(**v_head_kwargs) + + def _init_weights(self, **kwargs): + r""" + Initializes the weights of the value head. The default initialization strategy is random. + Users can pass a different initialization strategy by passing the `v_head_init_strategy` argument + when calling `.from_pretrained`. Supported strategies are: + - `normal`: initializes the weights with a normal distribution. + + Args: + **kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the `ValueHead` class. These arguments + can contain the `v_head_init_strategy` argument as well as the `v_head_initializer_range` + argument. + """ + initializer_range = kwargs.pop("v_head_initializer_range", 0.2) + # random init by default + init_strategy = kwargs.pop("v_head_init_strategy", None) + if init_strategy is None: + # do nothing + pass + elif init_strategy == "normal": + self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range) + self.v_head.summary.bias.data.zero_() + + def forward( + self, + input_ids=None, + past_key_values=None, + attention_mask=None, + **kwargs, + ): + r""" + Applies a forward pass to the wrapped model and returns the logits of the value head. + + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. + past_key_values (`tuple(tuple(torch.FloatTensor))`, `optional`): + Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model + (see `past_key_values` input) to speed up sequential decoding. + attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`): + Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + kwargs (`dict`, `optional`): + Additional keyword arguments, that are passed to the wrapped model. + """ + kwargs["output_hidden_states"] = True # this had already been set in the LORA / PEFT examples + kwargs["past_key_values"] = past_key_values + + if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING": + kwargs.pop("past_key_values") + + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + **kwargs, + ) + + last_hidden_state = base_model_output.hidden_states[-1] + lm_logits = base_model_output.logits + loss = base_model_output.loss + + if last_hidden_state.device != self.v_head.summary.weight.device: + last_hidden_state = last_hidden_state.to(self.v_head.summary.weight.device) + + value = self.v_head(last_hidden_state).squeeze(-1) + + # force upcast in fp32 if logits are in half-precision + if lm_logits.dtype != torch.float32: + lm_logits = lm_logits.float() + + return (lm_logits, loss, value) + + def generate(self, *args, **kwargs): + r""" + A simple wrapper around the `generate` method of the wrapped model. + Please refer to the [`generate`](https://huggingface.co/docs/transformers/internal/generation_utils) + method of the wrapped model for more information about the supported arguments. + + Args: + *args (`list`, *optional*): + Positional arguments passed to the `generate` method of the wrapped model. + **kwargs (`dict`, *optional*): + Keyword arguments passed to the `generate` method of the wrapped model. + """ + return self.pretrained_model.generate(*args, **kwargs) + + def state_dict(self, *args, **kwargs): + r""" + Returns the state dictionary of the model. We add the state dictionary of the value head + to the state dictionary of the wrapped model by prepending the key with `v_head.`. + """ + if not self.is_peft_model: + pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs) + else: + # if it is a peft model, only save the v_head + pretrained_model_state_dict = {} + + v_head_state_dict = self.v_head.state_dict(*args, **kwargs) + for k, v in v_head_state_dict.items(): + pretrained_model_state_dict[f"v_head.{k}"] = v + return pretrained_model_state_dict + + def push_to_hub(self, *args, **kwargs): + setattr(self.pretrained_model, "v_head", self.v_head) + + return self.pretrained_model.push_to_hub(*args, **kwargs) + + def post_init(self, state_dict): + r""" + We add the state dictionary of the value head to the state dictionary of the wrapped model + by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the + keys of the value head state dictionary. + """ + for k in list(state_dict.keys()): + if "v_head." in k: + state_dict[k.replace("v_head.", "")] = state_dict.pop(k) + self.v_head.load_state_dict(state_dict, strict=False) + del state_dict + + if hasattr(self.pretrained_model, "hf_device_map"): + if "cpu" in self.pretrained_model.hf_device_map.values() or "disk" in self.pretrained_model.hf_device_map.values(): + raise ValueError("The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models.") + + first_device = list(set(self.pretrained_model.hf_device_map.values()))[0] + + self.v_head = self.v_head.to(first_device) + + def set_device_hook(module, input, outputs): + new_output = () + for output in outputs: + if isinstance(output, torch.Tensor): + new_output += (output.to(first_device),) + else: + new_output += (output,) + return new_output + + self.register_forward_hook(set_device_hook) + + self.is_sequential_parallel = True + + +class AutoModelForSeq2SeqLMWithValueHead(PreTrainedModelWrapper): + r""" + A seq2seq model with a value head in addition to the language model head. + This class inherits from `~trl.PreTrainedModelWrapper` and wraps a + `transformers.PreTrainedModel` class. The wrapper class supports classic functions + such as `from_pretrained` and `push_to_hub` and also provides some additional + functionalities such as `generate`. + + Args: + pretrained_model (`transformers.PreTrainedModel`): + The model to wrap. It should be a causal language model such as GPT2. + or any model mapped inside the `AutoModelForSeq2SeqLM` class. + kwargs: + Additional keyword arguments passed along to the `ValueHead` class. + """ + + transformers_parent_class = AutoModelForSeq2SeqLM + lm_head_namings = ["lm_head", "embed_out", "output_projection"] + supported_args = ( + "summary_dropout_prob", + "v_head_initializer_range", + "v_head_init_strategy", + ) + + def __init__(self, pretrained_model, **kwargs): + super().__init__(pretrained_model, **kwargs) + v_head_kwargs, _, _ = self._split_kwargs(kwargs) + self.is_encoder_decoder = True + + if not self._has_lm_head(): + raise ValueError("The model does not have a language model head, please use a model that has one.") + + self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs) + + self._init_weights(**v_head_kwargs) + + def _has_lm_head(self): + # check module names of all modules inside `pretrained_model` to find the language model head + for name, module in self.pretrained_model.named_modules(): + if any(attribute in name for attribute in self.lm_head_namings): + return True + return False + + def post_init(self, state_dict): + r""" + We add the state dictionary of the value head to the state dictionary of the wrapped model + by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the + keys of the value head state dictionary. + """ + for k in list(state_dict.keys()): + if "v_head." in k: + state_dict[k.replace("v_head.", "")] = state_dict.pop(k) + self.v_head.load_state_dict(state_dict, strict=False) + del state_dict + + if hasattr(self.pretrained_model, "hf_device_map"): + if "cpu" in self.pretrained_model.hf_device_map.values() or "disk" in self.pretrained_model.hf_device_map.values(): + raise ValueError("The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models.") + + # get the lm_head device + for name, module in self.pretrained_model.named_modules(): + if any(attribute in name for attribute in self.lm_head_namings): + lm_head_device = module.weight.device + break + + # put v_head on the same device as the lm_head to avoid issues + self.v_head = self.v_head.to(lm_head_device) + + def set_device_hook(module, input, outputs): + r""" + A hook that sets the device of the output of the model to the device of the first + parameter of the model. + + Args: + module (`nn.Module`): + The module to which the hook is attached. + input (`tuple`): + The input to the module. + outputs (`tuple`): + The output of the module. + """ + new_output = () + for output in outputs: + if isinstance(output, torch.Tensor): + new_output += (output.to(lm_head_device),) + else: + new_output += (output,) + return new_output + + self.register_forward_hook(set_device_hook) + self.is_sequential_parallel = True + + def state_dict(self, *args, **kwargs): + r""" + Returns the state dictionary of the model. We add the state dictionary of the value head + to the state dictionary of the wrapped model by prepending the key with `v_head.`. + """ + if not self.is_peft_model: + pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs) + else: + # if it is a peft model, only save the v_head + pretrained_model_state_dict = {} + + v_head_state_dict = self.v_head.state_dict(*args, **kwargs) + for k, v in v_head_state_dict.items(): + pretrained_model_state_dict[f"v_head.{k}"] = v + return pretrained_model_state_dict + + def push_to_hub(self, *args, **kwargs): + setattr(self.pretrained_model, "v_head", self.v_head) + + return self.pretrained_model.push_to_hub(*args, **kwargs) + + def _init_weights(self, **kwargs): + r""" + We initialize the weights of the value head. + """ + initializer_range = kwargs.pop("v_head_initializer_range", 0.2) + # random init by default + init_strategy = kwargs.pop("v_head_init_strategy", None) + if init_strategy is None: + # do nothing + pass + elif init_strategy == "normal": + self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range) + self.v_head.summary.bias.data.zero_() + + def forward( + self, + input_ids=None, + past_key_values=None, + attention_mask=None, + **kwargs, + ): + kwargs["past_key_values"] = past_key_values + if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING": + kwargs.pop("past_key_values") + + base_model_output = self.pretrained_model( + input_ids=input_ids, + attention_mask=attention_mask, + output_hidden_states=True, # We force the model to output hidden states + **kwargs, + ) + + last_hidden_state = base_model_output.decoder_hidden_states[-1] + lm_logits = base_model_output.logits + loss = base_model_output.loss + + value = self.v_head(last_hidden_state).squeeze(-1) + + # force upcast in fp32 if logits are in half-precision + if lm_logits.dtype != torch.float32: + lm_logits = lm_logits.float() + + return (lm_logits, loss, value) + + def generate(self, *args, **kwargs): + r""" + We call `generate` on the wrapped model. + """ + return self.pretrained_model.generate(*args, **kwargs)