diff --git a/analysis/failure_case_analysis/ov_lvis/results/clipself_vitb16/predictions.pkl b/analysis/failure_case_analysis/ov_lvis/results/clipself_vitb16/predictions.pkl new file mode 100644 index 0000000000000000000000000000000000000000..f83d524dc5da3470c5ed649dfe21c1bc967dd221 --- /dev/null +++ b/analysis/failure_case_analysis/ov_lvis/results/clipself_vitb16/predictions.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:698bb09843ee81a5060ba82e63ea313df798111524caf18d8055601f5f5b9f90 +size 3192741272 diff --git a/analysis/failure_case_analysis/ov_lvis/results/declip_vitb16/predictions.pkl b/analysis/failure_case_analysis/ov_lvis/results/declip_vitb16/predictions.pkl new file mode 100644 index 0000000000000000000000000000000000000000..1b133a50782c9a306c2d830a6a10fc4d42104d99 --- /dev/null +++ b/analysis/failure_case_analysis/ov_lvis/results/declip_vitb16/predictions.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fd3cbfd7ae377d70b65da5206343b6f44513b0db64001f07b191c8f414c0665 +size 3237760617 diff --git a/analysis/robustness_eval/results/clipself/brightness_4.pkl b/analysis/robustness_eval/results/clipself/brightness_4.pkl new file mode 100644 index 0000000000000000000000000000000000000000..d234707cfd8ad8b69bf7c6bacec096973e63f7dd --- /dev/null +++ b/analysis/robustness_eval/results/clipself/brightness_4.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8e55fda8287413fa966fae356a033e7026880e07418c74f79189c27325ea040 +size 30647285 diff --git a/analysis/robustness_eval/results/clipself/brightness_5.pkl b/analysis/robustness_eval/results/clipself/brightness_5.pkl new file mode 100644 index 0000000000000000000000000000000000000000..363a1fbfd2bf0228e4281886eddbce425d98a613 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/brightness_5.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d42a54b5e61279715b97dae351bfb1d117d9276b2067111981e7969cffbe708e +size 30700199 diff --git a/analysis/robustness_eval/results/clipself/contrast_1.pkl b/analysis/robustness_eval/results/clipself/contrast_1.pkl new file mode 100644 index 0000000000000000000000000000000000000000..5b21f7b70aba940de175db40e40c6bee3306c9dc --- /dev/null +++ b/analysis/robustness_eval/results/clipself/contrast_1.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a781a4e64d97cce311bfeec7315e80ca14173447fc7bf13a6f4a359c8866f508 +size 30523488 diff --git a/analysis/robustness_eval/results/clipself/contrast_2.pkl b/analysis/robustness_eval/results/clipself/contrast_2.pkl new file mode 100644 index 0000000000000000000000000000000000000000..288e259360a49009dea3a72395cb13273680239a --- /dev/null +++ b/analysis/robustness_eval/results/clipself/contrast_2.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82708d0b5f1a2653ba396f6f45d2e5d0772d45899497dc5098735c94ecd78362 +size 30542290 diff --git a/analysis/robustness_eval/results/clipself/contrast_3.pkl b/analysis/robustness_eval/results/clipself/contrast_3.pkl new file mode 100644 index 0000000000000000000000000000000000000000..a4e0a3512ee27f54e112992fb610241b1b9d9b31 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/contrast_3.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:797e284dbd17524fe33a6ce0aca245b3822f6f5282faa4703fe024d52cdc0f20 +size 30574697 diff --git a/analysis/robustness_eval/results/clipself/contrast_4.pkl b/analysis/robustness_eval/results/clipself/contrast_4.pkl new file mode 100644 index 0000000000000000000000000000000000000000..8d971fd04f15f721624f436d4b733ae353ce27ff --- /dev/null +++ b/analysis/robustness_eval/results/clipself/contrast_4.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09d3bbd2c969bd1261565a26bff9016cae5f4a10d1a1a945517f147dbf799965 +size 30649535 diff --git a/analysis/robustness_eval/results/clipself/contrast_5.pkl b/analysis/robustness_eval/results/clipself/contrast_5.pkl new file mode 100644 index 0000000000000000000000000000000000000000..5ce9f8d69fb7e204e642d7f0f852b9af74fc1388 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/contrast_5.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:377b8c8659c585c3e24ff9824206c7a306b9dc3b7d41561bd22b4f276db6d3f5 +size 30782599 diff --git a/analysis/robustness_eval/results/clipself/defocus_blur_1.pkl b/analysis/robustness_eval/results/clipself/defocus_blur_1.pkl new file mode 100644 index 0000000000000000000000000000000000000000..e5d5b3b191d5e9eeb3d54410b649d11deb80ac63 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/defocus_blur_1.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:889c94242a1e08d8ae794bcf9b777a810763fe3b7286922789227b7611f66798 +size 30505205 diff --git a/analysis/robustness_eval/results/clipself/defocus_blur_2.pkl b/analysis/robustness_eval/results/clipself/defocus_blur_2.pkl new file mode 100644 index 0000000000000000000000000000000000000000..046938a0c8d151d6118e97e7171213cc5bbf719a --- /dev/null +++ b/analysis/robustness_eval/results/clipself/defocus_blur_2.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e3f7c4671f3f0f36423d5e58aa93b84b834fc379f4974b58d5da452d1dcb081 +size 30527051 diff --git a/analysis/robustness_eval/results/clipself/defocus_blur_3.pkl b/analysis/robustness_eval/results/clipself/defocus_blur_3.pkl new file mode 100644 index 0000000000000000000000000000000000000000..a378a657dc0a4ea62c7ed94cfe9ddf4d3f97bc07 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/defocus_blur_3.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a1f88d6b8171fa23552432013a049a6e4e700352beb9f57787b04465b5fb246 +size 30600963 diff --git a/analysis/robustness_eval/results/clipself/defocus_blur_4.pkl b/analysis/robustness_eval/results/clipself/defocus_blur_4.pkl new file mode 100644 index 0000000000000000000000000000000000000000..e51da6548f066e379a6d1ecbd1741f3996b83460 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/defocus_blur_4.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be2a23c24859a20f25cf8c8c1873629e37611efb2101b2c0c4b1ec34162ca6cb +size 30687752 diff --git a/analysis/robustness_eval/results/clipself/defocus_blur_5.pkl b/analysis/robustness_eval/results/clipself/defocus_blur_5.pkl new file mode 100644 index 0000000000000000000000000000000000000000..7e57e18faa8d6e0dfd9a773ef8d315c6026bf974 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/defocus_blur_5.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aebcc714bf4fd8e6c41a1865de971f0c54936af3025b02fb51e2c4325463cf2c +size 30755801 diff --git a/analysis/robustness_eval/results/clipself/elastic_transform_1.pkl b/analysis/robustness_eval/results/clipself/elastic_transform_1.pkl new file mode 100644 index 0000000000000000000000000000000000000000..43fef23c2dae5e1e0a7cde9a03070f9da32e8d10 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/elastic_transform_1.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0544cbe29e443b7e0e0dc2212f76f32b0abea47f7323144919af817906a3732 +size 30599114 diff --git a/analysis/robustness_eval/results/clipself/elastic_transform_2.pkl b/analysis/robustness_eval/results/clipself/elastic_transform_2.pkl new file mode 100644 index 0000000000000000000000000000000000000000..a24c0dcaf32fa2ecfa0e2d341f798fe81959e896 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/elastic_transform_2.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e460435a6de94553136d8555403fc6fef6ef91e5c619ca03fe148cf975c7ebc2 +size 30654225 diff --git a/analysis/robustness_eval/results/clipself/elastic_transform_3.pkl b/analysis/robustness_eval/results/clipself/elastic_transform_3.pkl new file mode 100644 index 0000000000000000000000000000000000000000..1048f887e49ae5d41b64b38d7dd523cfd0508591 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/elastic_transform_3.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03a5a8f09fae5cf0f0c5371ba6b44dc2ef8a0854cb24c6fba696647b43a5f0c8 +size 30739664 diff --git a/analysis/robustness_eval/results/clipself/elastic_transform_4.pkl b/analysis/robustness_eval/results/clipself/elastic_transform_4.pkl new file mode 100644 index 0000000000000000000000000000000000000000..9e3c0224525fd942e3a3b1857a841b66a6be09e7 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/elastic_transform_4.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16d7826b8e88e929903d83de4435e6611109e4bec084a0bdf60aa8a31b055731 +size 30821024 diff --git a/analysis/robustness_eval/results/clipself/elastic_transform_5.pkl b/analysis/robustness_eval/results/clipself/elastic_transform_5.pkl new file mode 100644 index 0000000000000000000000000000000000000000..891c20d4dae7f7bbbf32a0b3cb4f0f6d6465edd6 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/elastic_transform_5.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bd70a3b81a7874928a6b04949d5b11893fd789fdb7840394282822ba2cddbb85 +size 30922721 diff --git a/analysis/robustness_eval/results/clipself/fog_1.pkl b/analysis/robustness_eval/results/clipself/fog_1.pkl new file mode 100644 index 0000000000000000000000000000000000000000..dc22069ecbf3ac2e3fc0f2dd35180da35b575392 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/fog_1.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77b4e07582299f2353ded7374646e2731a8bb5f99bdf53f31276de05d371c7e7 +size 30576011 diff --git a/analysis/robustness_eval/results/clipself/fog_2.pkl b/analysis/robustness_eval/results/clipself/fog_2.pkl new file mode 100644 index 0000000000000000000000000000000000000000..63cb03f356e0e7bcd58419f02ddddd8cac9b6e8b --- /dev/null +++ b/analysis/robustness_eval/results/clipself/fog_2.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d3ba8e407846524ef83f7cb38b50a6526b9c28b4e08dfdf0d9550ec020b41f0 +size 30598371 diff --git a/analysis/robustness_eval/results/clipself/fog_3.pkl b/analysis/robustness_eval/results/clipself/fog_3.pkl new file mode 100644 index 0000000000000000000000000000000000000000..8b9009886708e9a92e35aeb8ca3b6339c870fc92 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/fog_3.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cb876cbccbe3949111375556a884d5ce64fdc168c2fcd5012eb95e86401beb2 +size 30614691 diff --git a/analysis/robustness_eval/results/clipself/fog_4.pkl b/analysis/robustness_eval/results/clipself/fog_4.pkl new file mode 100644 index 0000000000000000000000000000000000000000..212e8315f0f7c9520ed4a70a25e67a36a9957df5 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/fog_4.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07fd06fbabad3f711f0b53059b64c34319f3486df2babbb6dc2a9db655f11251 +size 30614627 diff --git a/analysis/robustness_eval/results/clipself/frost_3_results.pkl b/analysis/robustness_eval/results/clipself/frost_3_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..80168c1c8e656ab70cfd66f4b5cca2e09ecdf315 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/frost_3_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98782f7870210cad46e07be087fdd029774ba6482e9463a72b4274b3019ac2b4 +size 356 diff --git a/analysis/robustness_eval/results/clipself/frost_4_results.pkl b/analysis/robustness_eval/results/clipself/frost_4_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..618e1bdc45c4db2645504ebf19fa4e8f8d61ae03 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/frost_4_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09c1f5183de8e9505fd383f27860ed31f677cb0082511c58932ced008d5b1e56 +size 356 diff --git a/analysis/robustness_eval/results/clipself/frost_5_results.pkl b/analysis/robustness_eval/results/clipself/frost_5_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..6436d86bf1a1fb298a13a244789b17b8a65f23b8 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/frost_5_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eca45a4a1593165097d6b0713125a21df9379bed55fa305c7a109ed7b868d351 +size 356 diff --git a/analysis/robustness_eval/results/clipself/gaussian_noise_1_results.pkl b/analysis/robustness_eval/results/clipself/gaussian_noise_1_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..6cfa47204f3d9a0b37fd4facfaaceec22af1855e --- /dev/null +++ b/analysis/robustness_eval/results/clipself/gaussian_noise_1_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b0f9b928be211056ac8ab94e5d3e4f4d15f65e38a088e778c371a04c44cf9e4 +size 365 diff --git a/analysis/robustness_eval/results/clipself/gaussian_noise_2_results.pkl b/analysis/robustness_eval/results/clipself/gaussian_noise_2_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..d93f2ead2590e06fe44e2c1a02d6be0d189c0b30 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/gaussian_noise_2_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c5f909eebb7ef90e3a8d29751547c1d909826c1ec7f888259705ebb0f1507691 +size 365 diff --git a/analysis/robustness_eval/results/clipself/gaussian_noise_3_results.pkl b/analysis/robustness_eval/results/clipself/gaussian_noise_3_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..768a3f69cd083d776e19ff42aacc123d84684228 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/gaussian_noise_3_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5abc6e6ba8690316ac0fb043ac1a62fbb636da882050d8b254db86fcc6c13bb +size 365 diff --git a/analysis/robustness_eval/results/clipself/gaussian_noise_4_results.pkl b/analysis/robustness_eval/results/clipself/gaussian_noise_4_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..4bae1293f8353d461fa719c1d30a8d3ed93ee02f --- /dev/null +++ b/analysis/robustness_eval/results/clipself/gaussian_noise_4_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d6a4ec4dc06fbc6f9c86e5c8aa7e8372b65d4431b52daa449ff05a5278bb90b +size 365 diff --git a/analysis/robustness_eval/results/clipself/gaussian_noise_5_results.pkl b/analysis/robustness_eval/results/clipself/gaussian_noise_5_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..2c8a5c7877e957c9300c3f9d9caa7d9e7f270bd4 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/gaussian_noise_5_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14ed51c180d0ae740a4f14a76ff849e8e317506cc5f838f574db456d70178674 +size 365 diff --git a/analysis/robustness_eval/results/clipself/glass_blur_1_results.pkl b/analysis/robustness_eval/results/clipself/glass_blur_1_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..d0b5a7231dc7d6f897f1baba70a751c37b59d930 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/glass_blur_1_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:232c824e36570c1dfd2179f1613e9cf6494c60fd6235cdb9a076845c1a6f146f +size 361 diff --git a/analysis/robustness_eval/results/clipself/glass_blur_2_results.pkl b/analysis/robustness_eval/results/clipself/glass_blur_2_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..44f4a660de33a9938f6d40acec1019a35cd43478 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/glass_blur_2_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a15ca9e744bbe1afde83d467c408d26c699a800df32bd247b2b507b6a0b5df3 +size 361 diff --git a/analysis/robustness_eval/results/clipself/glass_blur_3_results.pkl b/analysis/robustness_eval/results/clipself/glass_blur_3_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..a964b3affd5e18f2b81104c98ddb3673d1a40cbb --- /dev/null +++ b/analysis/robustness_eval/results/clipself/glass_blur_3_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3426160bfebc9fb4fcda8ba0eb53bdf1aa18fcbc2c856968f665f73f972a08dd +size 361 diff --git a/analysis/robustness_eval/results/clipself/glass_blur_4.pkl b/analysis/robustness_eval/results/clipself/glass_blur_4.pkl new file mode 100644 index 0000000000000000000000000000000000000000..25abb20a6212e106769d44b83e75072496bf4f5f --- /dev/null +++ b/analysis/robustness_eval/results/clipself/glass_blur_4.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:463d2c52acf78a3ca235b5dfb6f67506efc1286bf97df6696d2fe9ce39a35aad +size 30638580 diff --git a/analysis/robustness_eval/results/clipself/glass_blur_4_results.pkl b/analysis/robustness_eval/results/clipself/glass_blur_4_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..38f089f2e95c1584265a1e82890c5984b6485e82 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/glass_blur_4_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4b7cdabb4dd54a30d4a623b1e6fcf8c76fe095e4f4c7d239355de0fe20fb694 +size 361 diff --git a/analysis/robustness_eval/results/clipself/glass_blur_5.pkl b/analysis/robustness_eval/results/clipself/glass_blur_5.pkl new file mode 100644 index 0000000000000000000000000000000000000000..f5d60fcc97136388badd875c3abf338aa5d37f8b --- /dev/null +++ b/analysis/robustness_eval/results/clipself/glass_blur_5.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eaa3937b4fbd32637eac67eb31671fb82a0801762478b677114d893bfddac329 +size 30700944 diff --git a/analysis/robustness_eval/results/clipself/glass_blur_5_results.pkl b/analysis/robustness_eval/results/clipself/glass_blur_5_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..48270f5d42e15ec99d3e0a4f7828a8732b500cea --- /dev/null +++ b/analysis/robustness_eval/results/clipself/glass_blur_5_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2671fe8492422ed304feee600aaeabbf688aee4955c053f4306e13d227309e0 +size 361 diff --git a/analysis/robustness_eval/results/clipself/impulse_noise_1.pkl b/analysis/robustness_eval/results/clipself/impulse_noise_1.pkl new file mode 100644 index 0000000000000000000000000000000000000000..13062bd47f1b96299445849ac73a0baa2dc674d1 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/impulse_noise_1.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65bca927ec1ae26bb6a059116a91a7126609bbccedfc4715fbb8f1dda3c8187c +size 30720445 diff --git a/analysis/robustness_eval/results/clipself/impulse_noise_1_results.pkl b/analysis/robustness_eval/results/clipself/impulse_noise_1_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..78db46954e3935fca0dee95b906a44d6f797d5bc --- /dev/null +++ b/analysis/robustness_eval/results/clipself/impulse_noise_1_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf3e8e69b72ba6ebd30b24765cbf3106297ab49c96a6666a93439b7aace19661 +size 364 diff --git a/analysis/robustness_eval/results/clipself/impulse_noise_2_results.pkl b/analysis/robustness_eval/results/clipself/impulse_noise_2_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..4e3009387dd1f6289604ecb18136a3ae8c549a64 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/impulse_noise_2_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:492fa2d7e8991e12dd9769c5c6cebc013aef4ab7583ab9f9043c7babc4c9f877 +size 364 diff --git a/analysis/robustness_eval/results/clipself/impulse_noise_3.pkl b/analysis/robustness_eval/results/clipself/impulse_noise_3.pkl new file mode 100644 index 0000000000000000000000000000000000000000..11bc504327d6da95ca9638834dd94a4c03332d88 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/impulse_noise_3.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8dc0064851ebcc927b719d6d7798a4ac1f0430ddd7838d342e06babd2606168 +size 30838735 diff --git a/analysis/robustness_eval/results/clipself/impulse_noise_3_results.pkl b/analysis/robustness_eval/results/clipself/impulse_noise_3_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..2aeaabd67836f46cf0e866684ea63c99b04bc7c6 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/impulse_noise_3_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fcfaefa4c7423b1661674b9df2f216cc204418c68f822dee417e391e99466fa9 +size 364 diff --git a/analysis/robustness_eval/results/clipself/impulse_noise_4.pkl b/analysis/robustness_eval/results/clipself/impulse_noise_4.pkl new file mode 100644 index 0000000000000000000000000000000000000000..50e2fb101466808d4ba5364d25270c2c320e0d9f --- /dev/null +++ b/analysis/robustness_eval/results/clipself/impulse_noise_4.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:957e59b3b487e935819d3fba3fffa9d7555c6b715311d99f9128996d2ce3daae +size 30948807 diff --git a/analysis/robustness_eval/results/clipself/impulse_noise_4_results.pkl b/analysis/robustness_eval/results/clipself/impulse_noise_4_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..f4e39fc60efc017906c89392ff07743e985eeda2 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/impulse_noise_4_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ce2524ae908ffd67ccc860890399284bbcabca51247586a545b613cafd395a0 +size 364 diff --git a/analysis/robustness_eval/results/clipself/impulse_noise_5.pkl b/analysis/robustness_eval/results/clipself/impulse_noise_5.pkl new file mode 100644 index 0000000000000000000000000000000000000000..7f9aef75231795b392217f94ce95ecf265c7e01e --- /dev/null +++ b/analysis/robustness_eval/results/clipself/impulse_noise_5.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:455303a07181697ca895d89089474fa07e6d55b68d43bf33a5fe344831999f1b +size 31091513 diff --git a/analysis/robustness_eval/results/clipself/impulse_noise_5_results.pkl b/analysis/robustness_eval/results/clipself/impulse_noise_5_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..d6c1cc6e6a5815516c276d06dc4b2161b984138f --- /dev/null +++ b/analysis/robustness_eval/results/clipself/impulse_noise_5_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c41aaff2e13a3fdab6f7ba2fea367696391f6af491cfbcee964681e572f39659 +size 364 diff --git a/analysis/robustness_eval/results/clipself/jpeg_compression_1.pkl b/analysis/robustness_eval/results/clipself/jpeg_compression_1.pkl new file mode 100644 index 0000000000000000000000000000000000000000..b7a4240e0ef37c366ca27bb19dbdba21ec1c09b3 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/jpeg_compression_1.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75f89d91e888fe1f7ecf15d9fb5aa319670bf8f3fa0b4b89ef95bb45356f2bf6 +size 30597673 diff --git a/analysis/robustness_eval/results/clipself/jpeg_compression_1_results.pkl b/analysis/robustness_eval/results/clipself/jpeg_compression_1_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..da4a6ae60f2d9b7e68214aa8ca7eda54027614de --- /dev/null +++ b/analysis/robustness_eval/results/clipself/jpeg_compression_1_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2c2b8e1139de5e3292bafa8a3f722cc5d5fba7e731de2fdd2253a66e9c59757 +size 367 diff --git a/analysis/robustness_eval/results/clipself/jpeg_compression_2.pkl b/analysis/robustness_eval/results/clipself/jpeg_compression_2.pkl new file mode 100644 index 0000000000000000000000000000000000000000..02c581af85f93a73f55cfca56caed0793d85d4ae --- /dev/null +++ b/analysis/robustness_eval/results/clipself/jpeg_compression_2.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edd2150a89609d976d90bf6278697b5d7263f05ca327418655fcf3b29bd593c0 +size 30629547 diff --git a/analysis/robustness_eval/results/clipself/jpeg_compression_2_results.pkl b/analysis/robustness_eval/results/clipself/jpeg_compression_2_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..51918cc9db16c073a523a01d07f75124da3ad8f8 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/jpeg_compression_2_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a8e33e93836c20f5ce37f1c2cf809e28042abb58fbee0ad6dc1a75e3cffc553 +size 367 diff --git a/analysis/robustness_eval/results/clipself/jpeg_compression_3.pkl b/analysis/robustness_eval/results/clipself/jpeg_compression_3.pkl new file mode 100644 index 0000000000000000000000000000000000000000..d7f0df0746d0ab8759462a6fe119535f4f551629 --- /dev/null +++ b/analysis/robustness_eval/results/clipself/jpeg_compression_3.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c5249e60321cc33165c7bb9631aab9b88df53adb72ad55f7b1f60a478661e17 +size 30668939 diff --git a/analysis/robustness_eval/results/clipself/jpeg_compression_3_results.pkl b/analysis/robustness_eval/results/clipself/jpeg_compression_3_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..7e95ea14b90d6d33185ab7581b4e24f36cf6f44b --- /dev/null +++ b/analysis/robustness_eval/results/clipself/jpeg_compression_3_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fac89ef6677f13b86a6ee37097faa7620df935515a0b2c16ad9b63f228cd0ff +size 367 diff --git a/analysis/robustness_eval/results/clipself/jpeg_compression_4_results.pkl b/analysis/robustness_eval/results/clipself/jpeg_compression_4_results.pkl new file mode 100644 index 0000000000000000000000000000000000000000..3f427edc3c89f56a933a97d608d273f4b8c8629b --- /dev/null +++ b/analysis/robustness_eval/results/clipself/jpeg_compression_4_results.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:078741672aef4c75287e05543bb1f00e64150e87878e5a83e307e640e9cd31b6 +size 367 diff --git a/third_party/ODISE/demo/examples/ade.jpg b/third_party/ODISE/demo/examples/ade.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bf2987bed1221f91296fb239a06365b78d5b41d5 --- /dev/null +++ b/third_party/ODISE/demo/examples/ade.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0201fc20dbfe186a48059591ce751664380e479766c0f5ee9e37478d773f4d27 +size 58364 diff --git a/third_party/ODISE/demo/examples/coco.jpg b/third_party/ODISE/demo/examples/coco.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1c57fa95979d63fea1b6a2d006f0ffb9b84e461d --- /dev/null +++ b/third_party/ODISE/demo/examples/coco.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8043630d9033bd8c58b57cf4faad1b2459c5341bfa487112479128f3ac80e4cd +size 266176 diff --git a/third_party/ODISE/demo/examples/ego4d.jpg b/third_party/ODISE/demo/examples/ego4d.jpg new file mode 100644 index 0000000000000000000000000000000000000000..580d7eb831942d6dc738d50fdbef4dbef6091b0b --- /dev/null +++ b/third_party/ODISE/demo/examples/ego4d.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a9ba476bbb584b2ca38468282049dd1c6b453d405292438163c5a1889a65651 +size 44606 diff --git a/third_party/ODISE/demo/examples/purse.jpeg b/third_party/ODISE/demo/examples/purse.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..3cfb5989352d00ef6623c5bacfb4be8c0ef0a739 --- /dev/null +++ b/third_party/ODISE/demo/examples/purse.jpeg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a3db8dc2a69e82280e948895a33bfb137edf00288b26a0db11dbc3fb377dbb3 +size 6728 diff --git a/third_party/ODISE/figs/github_arch.gif b/third_party/ODISE/figs/github_arch.gif new file mode 100644 index 0000000000000000000000000000000000000000..c0ee1a75a9a90730d9610a74eae84001bc17124c --- /dev/null +++ b/third_party/ODISE/figs/github_arch.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:741c1334f4a51594e544b0e1dd9f52907a66d11c8fd7908bf0bcafb112600820 +size 691982 diff --git a/third_party/ODISE/figs/github_vis_ade_0.gif b/third_party/ODISE/figs/github_vis_ade_0.gif new file mode 100644 index 0000000000000000000000000000000000000000..80528d31d516c399f122fc86c9a77be5df8f4656 --- /dev/null +++ b/third_party/ODISE/figs/github_vis_ade_0.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88df74e8d965cd448d646e3b8595bf86461bcf38e8c1025006653bff5417294c +size 2106770 diff --git a/third_party/ODISE/figs/github_vis_ade_1.gif b/third_party/ODISE/figs/github_vis_ade_1.gif new file mode 100644 index 0000000000000000000000000000000000000000..2950c85b9d2720042ec04dfca2a4c6732855b225 --- /dev/null +++ b/third_party/ODISE/figs/github_vis_ade_1.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e23d467e3911849513bcfbf402512d22e277608657be609a16c299b434c8b6a +size 1523757 diff --git a/third_party/ODISE/figs/github_vis_coco_0.gif b/third_party/ODISE/figs/github_vis_coco_0.gif new file mode 100644 index 0000000000000000000000000000000000000000..fb6a9feead26b6b6f8acb0726a36b22cb03ead7d --- /dev/null +++ b/third_party/ODISE/figs/github_vis_coco_0.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc4dce5d6bc8b7dc8ef748048c43aa144d50f343a5d43df699d65430c9d41606 +size 1664305 diff --git a/third_party/ODISE/figs/github_vis_coco_1.gif b/third_party/ODISE/figs/github_vis_coco_1.gif new file mode 100644 index 0000000000000000000000000000000000000000..099eb3d6a7583a2b9e3f75f0e7f8c31abe38731f --- /dev/null +++ b/third_party/ODISE/figs/github_vis_coco_1.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e42ba25e782cfb6ef15f2d308a554008671b55c623019feaa6ff65a5e16fc09 +size 2017314 diff --git a/third_party/ODISE/figs/github_vis_ego4d_0.gif b/third_party/ODISE/figs/github_vis_ego4d_0.gif new file mode 100644 index 0000000000000000000000000000000000000000..9bb3e03a62b8c81a140edefb4b25d5bde4069c33 --- /dev/null +++ b/third_party/ODISE/figs/github_vis_ego4d_0.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:23ebd1e06db93c3f83b67c435713e8d6d762aff10590b1e0b6a00f72a0e3eee6 +size 1701470 diff --git a/third_party/ODISE/figs/github_vis_ego4d_1.gif b/third_party/ODISE/figs/github_vis_ego4d_1.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e38c62a0e4a7ccc189e35f867cdc0033015741e --- /dev/null +++ b/third_party/ODISE/figs/github_vis_ego4d_1.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cde363dcd0132c3ba17697ace85fa6996770dde0ad937aa4033167d23524e248 +size 2943331 diff --git a/third_party/ODISE/figs/teaser.jpg b/third_party/ODISE/figs/teaser.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d85dbb19c5022b51ff65d3d873058d734ad7beb9 --- /dev/null +++ b/third_party/ODISE/figs/teaser.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ebf91aba99682a7c1d99398210fa548aa54f1b13efd00da21efce2e165d4033 +size 332149 diff --git a/third_party/TinyCLIP/figure/TinyCLIP.jpg b/third_party/TinyCLIP/figure/TinyCLIP.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1751b3854c79197979ebbe53c8cf1be042e74ebb --- /dev/null +++ b/third_party/TinyCLIP/figure/TinyCLIP.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:178a108eca80b664b199396ca5b750bc33b13f197c75100f35a1a219b2b8e29f +size 356005 diff --git a/third_party/TinyCLIP/figure/fig1.jpg b/third_party/TinyCLIP/figure/fig1.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7d0218b510f94d3c1ba9727d17513c443482faaf --- /dev/null +++ b/third_party/TinyCLIP/figure/fig1.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c513ee595b8f49650a04c6d8c9343395e060881952640d7d644a7477d95741b +size 124003 diff --git a/third_party/TinyCLIP/src/open_clip/bpe_simple_vocab_16e6.txt.gz b/third_party/TinyCLIP/src/open_clip/bpe_simple_vocab_16e6.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113 --- /dev/null +++ b/third_party/TinyCLIP/src/open_clip/bpe_simple_vocab_16e6.txt.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a +size 1356917 diff --git a/third_party/TinyCLIP/src/open_clip/model_configs/ViT-B-16.json b/third_party/TinyCLIP/src/open_clip/model_configs/ViT-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..9afeef0fbc807f130f2b2bc65c1dd85abc9eba72 --- /dev/null +++ b/third_party/TinyCLIP/src/open_clip/model_configs/ViT-B-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} diff --git a/third_party/TinyCLIP/src/open_clip/model_configs/ViT-B-32.json b/third_party/TinyCLIP/src/open_clip/model_configs/ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..07c8e28eb06fa1813ba932fe4eec668262d1c47f --- /dev/null +++ b/third_party/TinyCLIP/src/open_clip/model_configs/ViT-B-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/third_party/TinyCLIP/src/training/.gitignore b/third_party/TinyCLIP/src/training/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..333c1e910a3e2bef1b9d0d4587392627d8388974 --- /dev/null +++ b/third_party/TinyCLIP/src/training/.gitignore @@ -0,0 +1 @@ +logs/ diff --git a/third_party/TinyCLIP/src/training/__init__.py b/third_party/TinyCLIP/src/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third_party/TinyCLIP/src/training/data.py b/third_party/TinyCLIP/src/training/data.py new file mode 100644 index 0000000000000000000000000000000000000000..32c2f45cd4d28697e5e92baf44d6caf174196d86 --- /dev/null +++ b/third_party/TinyCLIP/src/training/data.py @@ -0,0 +1,590 @@ +import ast +import json +import logging +import math +import os +import random +import sys +import braceexpand +from dataclasses import dataclass +from multiprocessing import Value + +import numpy as np +import pandas as pd +import torch +import torchvision.datasets as datasets +import webdataset as wds +from PIL import Image +from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler, IterableDataset, get_worker_info +from torch.utils.data.distributed import DistributedSampler +from webdataset.filters import _shuffle +from webdataset.tariterators import base_plus_ext, url_opener, tar_file_expander, valid_sample + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + +try: + from timm.data import TimmDatasetTar +except ImportError: + # for higher version of timm + from timm.data import ImageDataset as TimmDatasetTar + + +class CsvDataset(Dataset): + def __init__(self, input_filename, transforms, img_key, caption_key, sep="\t", tokenizer=None): + logging.debug(f'Loading csv data from {input_filename}.') + df = pd.read_csv(input_filename, sep=sep) + + self.images = df[img_key].tolist() + self.captions = df[caption_key].tolist() + self.transforms = transforms + logging.debug('Done loading data.') + + self.tokenize = tokenizer + + def __len__(self): + return len(self.captions) + + def __getitem__(self, idx): + images = self.transforms(Image.open(str(self.images[idx]))) + texts = self.tokenize([str(self.captions[idx])])[0] + return images, texts + + +class SharedEpoch: + def __init__(self, epoch: int = 0): + self.shared_epoch = Value('i', epoch) + + def set_value(self, epoch): + self.shared_epoch.value = epoch + + def get_value(self): + return self.shared_epoch.value + + +@dataclass +class DataInfo: + dataloader: DataLoader + sampler: DistributedSampler = None + shared_epoch: SharedEpoch = None + + def set_epoch(self, epoch): + if self.shared_epoch is not None: + self.shared_epoch.set_value(epoch) + if self.sampler is not None and isinstance(self.sampler, DistributedSampler): + self.sampler.set_epoch(epoch) + + +def expand_urls(urls, weights=None): + if weights is None: + expanded_urls = wds.shardlists.expand_urls(urls) + return expanded_urls, None + if isinstance(urls, str): + urllist = urls.split("::") + weights = weights.split('::') + assert len(weights) == len(urllist), \ + f"Expected the number of data components ({len(urllist)}) and weights({len(weights)}) to match." + weights = [float(weight) for weight in weights] + all_urls, all_weights = [], [] + for url, weight in zip(urllist, weights): + expanded_url = list(braceexpand.braceexpand(url)) + expanded_weights = [weight for _ in expanded_url] + all_urls.extend(expanded_url) + all_weights.extend(expanded_weights) + return all_urls, all_weights + else: + all_urls = list(urls) + return all_urls, weights + + +def get_dataset_size(shards): + shards_list, _ = expand_urls(shards) + dir_path = os.path.dirname(shards_list[0]) + sizes_filename = os.path.join(dir_path, 'sizes.json') + len_filename = os.path.join(dir_path, '__len__') + if os.path.exists(sizes_filename): + sizes = json.load(open(sizes_filename, 'r')) + total_size = sum([int(sizes[os.path.basename(shard)]) + for shard in shards_list]) + elif os.path.exists(len_filename): + # FIXME this used to be eval(open(...)) but that seemed rather unsafe + total_size = ast.literal_eval(open(len_filename, 'r').read()) + else: + total_size = None # num samples undefined + # some common dataset sizes (at time of authors last download) + # CC3M (train): 2905954 + # CC12M: 10968539 + # LAION-400M: 407332084 + # LAION-2B (english): 2170337258 + num_shards = len(shards_list) + return total_size, num_shards + + +def get_imagenet(args, preprocess_fns, split): + assert split in ["train", "val", "v2"] + is_train = split == "train" + preprocess_train, preprocess_val = preprocess_fns + + if split == "v2": + from imagenetv2_pytorch import ImageNetV2Dataset + dataset = ImageNetV2Dataset( + location=args.imagenet_v2, transform=preprocess_val) + else: + if is_train: + data_path = args.imagenet_train + preprocess_fn = preprocess_train + else: + data_path = args.imagenet_val + preprocess_fn = preprocess_val + assert data_path + + data_dir = os.path.join(data_path, f'val.tar') + if os.path.exists(data_dir): + dataset = TimmDatasetTar(data_dir, transform=preprocess_fn) + else: + val_data_path = os.path.join(data_path, 'val') + if os.path.exists(val_data_path): + data_path = val_data_path + dataset = datasets.ImageFolder(data_path, transform=preprocess_fn) + + if is_train: + idxs = np.zeros(len(dataset.targets)) + target_array = np.array(dataset.targets) + k = 50 + for c in range(1000): + m = target_array == c + n = len(idxs[m]) + arr = np.zeros(n) + arr[:k] = 1 + np.random.shuffle(arr) + idxs[m] = arr + + idxs = idxs.astype('int') + sampler = SubsetRandomSampler(np.where(idxs)[0]) + else: + indices = np.arange(args.rank, len(dataset), args.world_size) + sampler = SubsetRandomSampler(indices) + + dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=args.batch_size, + num_workers=args.workers, + sampler=sampler, + ) + + return DataInfo(dataloader=dataloader, sampler=sampler) + + +def count_samples(dataloader): + os.environ["WDS_EPOCH"] = "0" + n_elements, n_batches = 0, 0 + for images, texts in dataloader: + n_batches += 1 + n_elements += len(images) + assert len(images) == len(texts) + return n_elements, n_batches + + +def filter_no_caption_or_no_image(sample): + has_caption = ('txt' in sample) + has_image = ( + 'png' in sample or 'jpg' in sample or 'jpeg' in sample or 'webp' in sample) + return has_caption and has_image + + +def log_and_continue(exn): + """Call in an exception handler to ignore any exception, issue a warning, and continue.""" + logging.warning(f'Handling webdataset error ({repr(exn)}). Ignoring.') + return True + + +def group_by_keys_nothrow(data, keys=base_plus_ext, lcase=True, suffixes=None, handler=None): + """Return function over iterator that groups key, value pairs into samples. + + :param keys: function that splits the key into key and extension (base_plus_ext) + :param lcase: convert suffixes to lower case (Default value = True) + """ + current_sample = None + for filesample in data: + assert isinstance(filesample, dict) + fname, value = filesample["fname"], filesample["data"] + prefix, suffix = keys(fname) + if prefix is None: + continue + if lcase: + suffix = suffix.lower() + # FIXME webdataset version throws if suffix in current_sample, but we have a potential for + # this happening in the current LAION400m dataset if a tar ends with same prefix as the next + # begins, rare, but can happen since prefix aren't unique across tar files in that dataset + if current_sample is None or prefix != current_sample["__key__"] or suffix in current_sample: + if valid_sample(current_sample): + yield current_sample + current_sample = dict( + __key__=prefix, __url__=filesample["__url__"]) + if suffixes is None or suffix in suffixes: + current_sample[suffix] = value + if valid_sample(current_sample): + yield current_sample + + +def tarfile_to_samples_nothrow(src, handler=log_and_continue): + # NOTE this is a re-impl of the webdataset impl with group_by_keys that doesn't throw + streams = url_opener(src, handler=handler) + files = tar_file_expander(streams, handler=handler) + samples = group_by_keys_nothrow(files, handler=handler) + return samples + + +def pytorch_worker_seed(increment=0): + """get dataloader worker seed from pytorch""" + worker_info = get_worker_info() + if worker_info is not None: + # favour using the seed already created for pytorch dataloader workers if it exists + seed = worker_info.seed + if increment: + # space out seed increments so they can't overlap across workers in different iterations + seed += increment * max(1, worker_info.num_workers) + return seed + # fallback to wds rank based seed + return wds.utils.pytorch_worker_seed() + + +_SHARD_SHUFFLE_SIZE = 2000 +_SHARD_SHUFFLE_INITIAL = 500 +_SAMPLE_SHUFFLE_SIZE = 5000 +_SAMPLE_SHUFFLE_INITIAL = 1000 + + +class detshuffle2(wds.PipelineStage): + def __init__( + self, + bufsize=1000, + initial=100, + seed=0, + epoch=-1, + ): + self.bufsize = bufsize + self.initial = initial + self.seed = seed + self.epoch = epoch + + def run(self, src): + if isinstance(self.epoch, SharedEpoch): + epoch = self.epoch.get_value() + else: + # NOTE: this is epoch tracking is problematic in a multiprocess (dataloader workers or train) + # situation as different workers may wrap at different times (or not at all). + self.epoch += 1 + epoch = self.epoch + rng = random.Random() + if self.seed < 0: + # If seed is negative, we use the worker's seed, this will be different across all nodes/workers + seed = pytorch_worker_seed(epoch) + else: + # This seed to be deterministic AND the same across all nodes/workers in each epoch + seed = self.seed + epoch + rng.seed(seed) + return _shuffle(src, self.bufsize, self.initial, rng) + + +class ResampledShards2(IterableDataset): + """An iterable dataset yielding a list of urls.""" + + def __init__( + self, + urls, + weights=None, + nshards=sys.maxsize, + worker_seed=None, + deterministic=False, + epoch=-1, + ): + """Sample shards from the shard list with replacement. + + :param urls: a list of URLs as a Python list or brace notation string + """ + super().__init__() + urls, weights = expand_urls(urls, weights) + self.urls = urls + self.weights = weights + if self.weights is not None: + assert len(self.urls) == len(self.weights), \ + f"Number of urls {len(self.urls)} and weights {len(self.weights)} should match." + assert isinstance(self.urls[0], str) + self.nshards = nshards + self.rng = random.Random() + self.worker_seed = worker_seed + self.deterministic = deterministic + self.epoch = epoch + + def __iter__(self): + """Return an iterator over the shards.""" + if isinstance(self.epoch, SharedEpoch): + epoch = self.epoch.get_value() + else: + # NOTE: this is epoch tracking is problematic in a multiprocess (dataloader workers or train) + # situation as different workers may wrap at different times (or not at all). + self.epoch += 1 + epoch = self.epoch + if self.deterministic: + # reset seed w/ epoch if deterministic + if self.worker_seed is None: + # pytorch worker seed should be deterministic due to being init by arg.seed + rank + worker id + seed = pytorch_worker_seed(epoch) + else: + seed = self.worker_seed() + epoch + self.rng.seed(seed) + for _ in range(self.nshards): + if self.weights is None: + yield dict(url=self.rng.choice(self.urls)) + else: + yield dict(url=self.rng.choices(self.urls, weights=self.weights, k=1)[0]) + + +def get_wds_dataset(args, preprocess_img, is_train, epoch=0, floor=False, tokenizer=None): + input_shards = args.train_data if is_train else args.val_data + assert input_shards is not None + resampled = getattr(args, 'dataset_resampled', False) and is_train + + num_shards = None + if is_train: + if args.train_num_samples is not None: + num_samples = args.train_num_samples + else: + num_samples, num_shards = get_dataset_size(input_shards) + if not num_samples: + raise RuntimeError( + 'Currently, the number of dataset samples must be specified for the training dataset. ' + 'Please specify it via `--train-num-samples` if no dataset length info is present.') + else: + # Eval will just exhaust the iterator if the size is not specified. + num_samples = args.val_num_samples or 0 + + # create a shared epoch store to sync epoch to dataloader worker proc + shared_epoch = SharedEpoch(epoch=epoch) + + if is_train and args.train_data_upsampling_factors is not None: + assert resampled, "--train_data_upsampling_factors is only supported when sampling with replacement (with --dataset-resampled)." + + if resampled: + pipeline = [ResampledShards2( + input_shards, + weights=args.train_data_upsampling_factors, + deterministic=True, + epoch=shared_epoch, + )] + else: + pipeline = [wds.SimpleShardList(input_shards)] + + # at this point we have an iterator over all the shards + if is_train: + if not resampled: + pipeline.extend([ + detshuffle2( + bufsize=_SHARD_SHUFFLE_SIZE, + initial=_SHARD_SHUFFLE_INITIAL, + seed=args.seed, + epoch=shared_epoch, + ), + wds.split_by_node, + wds.split_by_worker, + ]) + pipeline.extend([ + # at this point, we have an iterator over the shards assigned to each worker at each node + # wds.tarfile_to_samples(handler=log_and_continue), + tarfile_to_samples_nothrow, + wds.shuffle( + bufsize=_SAMPLE_SHUFFLE_SIZE, + initial=_SAMPLE_SHUFFLE_INITIAL, + ), + ]) + else: + pipeline.extend([ + wds.split_by_worker, + # at this point, we have an iterator over the shards assigned to each worker + wds.tarfile_to_samples(handler=log_and_continue), + ]) + pipeline.extend([ + wds.select(filter_no_caption_or_no_image), + wds.decode("pilrgb", handler=log_and_continue), + wds.rename(image="jpg;png;jpeg;webp", text="txt"), + wds.map_dict(image=preprocess_img, + text=lambda text: tokenizer(text)[0]), + wds.to_tuple("image", "text"), + wds.batched(args.batch_size, partial=not is_train) + ]) + + dataset = wds.DataPipeline(*pipeline) + + if is_train: + if not resampled: + num_shards = num_shards or len(expand_urls(input_shards)[0]) + assert num_shards >= args.workers * \ + args.world_size, 'number of shards must be >= total workers' + # roll over and repeat a few samples to get same number of full batches on each node + round_fn = math.floor if floor else math.ceil + global_batch_size = args.batch_size * args.world_size + num_batches = round_fn(num_samples / global_batch_size) + num_workers = max(1, args.workers) + num_worker_batches = round_fn( + num_batches / num_workers) # per dataloader worker + num_batches = num_worker_batches * num_workers + num_samples = num_batches * global_batch_size + # each worker is iterating over this + dataset = dataset.with_epoch(num_worker_batches) + else: + # last batches are partial, eval is done on single (master) node + num_batches = math.ceil(num_samples / args.batch_size) + + dataloader = wds.WebLoader( + dataset, + batch_size=None, + shuffle=False, + num_workers=args.workers, + persistent_workers=args.workers > 0, + ) + + # FIXME not clear which approach is better, with_epoch before vs after dataloader? + # hoping to resolve via https://github.com/webdataset/webdataset/issues/169 + # if is_train: + # # roll over and repeat a few samples to get same number of full batches on each node + # global_batch_size = args.batch_size * args.world_size + # num_batches = math.ceil(num_samples / global_batch_size) + # num_workers = max(1, args.workers) + # num_batches = math.ceil(num_batches / num_workers) * num_workers + # num_samples = num_batches * global_batch_size + # dataloader = dataloader.with_epoch(num_batches) + # else: + # # last batches are partial, eval is done on single (master) node + # num_batches = math.ceil(num_samples / args.batch_size) + + # add meta-data to dataloader instance for convenience + dataloader.num_batches = num_batches + dataloader.num_samples = num_samples + + return DataInfo(dataloader=dataloader, shared_epoch=shared_epoch) + + +def get_csv_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + input_filename = args.train_data if is_train else args.val_data + assert input_filename + dataset = CsvDataset( + input_filename, + preprocess_fn, + img_key=args.csv_img_key, + caption_key=args.csv_caption_key, + sep=args.csv_separator, + tokenizer=tokenizer + ) + num_samples = len(dataset) + sampler = DistributedSampler( + dataset) if args.distributed and is_train else None + shuffle = is_train and sampler is None + + dataloader = DataLoader( + dataset, + batch_size=args.batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) + + +class SyntheticDataset(Dataset): + + def __init__( + self, + transform=None, + image_size=(224, 224), + caption="Dummy caption", + dataset_size=100, + tokenizer=None, + ): + self.transform = transform + self.image_size = image_size + self.caption = caption + self.image = Image.new('RGB', image_size) + self.dataset_size = dataset_size + + self.preprocess_txt = lambda text: tokenizer(text)[0] + + def __len__(self): + return self.dataset_size + + def __getitem__(self, idx): + if self.transform is not None: + image = self.transform(self.image) + return image, self.preprocess_txt(self.caption) + + +def get_synthetic_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + image_size = preprocess_fn.transforms[0].size + dataset = SyntheticDataset( + transform=preprocess_fn, image_size=image_size, dataset_size=args.train_num_samples, tokenizer=tokenizer) + num_samples = len(dataset) + sampler = DistributedSampler( + dataset) if args.distributed and is_train else None + shuffle = is_train and sampler is None + + dataloader = DataLoader( + dataset, + batch_size=args.batch_size, + shuffle=shuffle, + num_workers=args.workers, + pin_memory=True, + sampler=sampler, + drop_last=is_train, + ) + dataloader.num_samples = num_samples + dataloader.num_batches = len(dataloader) + + return DataInfo(dataloader, sampler) + + +def get_dataset_fn(data_path, dataset_type): + if dataset_type == "webdataset": + return get_wds_dataset + elif dataset_type == "csv": + return get_csv_dataset + elif dataset_type == "synthetic": + return get_synthetic_dataset + elif dataset_type == "auto": + ext = data_path.split('.')[-1] + if ext in ['csv', 'tsv']: + return get_csv_dataset + elif ext in ['tar']: + return get_wds_dataset + else: + raise ValueError( + f"Tried to figure out dataset type, but failed for extension {ext}.") + else: + raise ValueError(f"Unsupported dataset type: {dataset_type}") + + +def get_data(args, preprocess_fns, epoch=0, tokenizer=None): + preprocess_train, preprocess_val = preprocess_fns + data = {} + + if args.train_data or args.dataset_type == "synthetic": + data["train"] = get_dataset_fn(args.train_data, args.dataset_type)( + args, preprocess_train, is_train=True, epoch=epoch, tokenizer=tokenizer) + + if args.val_data: + data["val"] = get_dataset_fn(args.val_data, args.dataset_type)( + args, preprocess_val, is_train=False, tokenizer=tokenizer) + + if args.imagenet_val is not None: + data["imagenet-val"] = get_imagenet(args, preprocess_fns, "val") + + if args.imagenet_v2 is not None: + data["imagenet-v2"] = get_imagenet(args, preprocess_fns, "v2") + + return data diff --git a/third_party/TinyCLIP/src/training/distributed.py b/third_party/TinyCLIP/src/training/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..34e32142c43bdc97eeba66be7a4aa1f951cf2281 --- /dev/null +++ b/third_party/TinyCLIP/src/training/distributed.py @@ -0,0 +1,120 @@ +import os + +import torch + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + + +def is_global_master(args): + return args.rank == 0 + + +def is_local_master(args): + return args.local_rank == 0 + + +def is_master(args, local=False): + return is_local_master(args) if local else is_global_master(args) + + +def is_using_horovod(): + # NOTE w/ horovod run, OMPI vars should be set, but w/ SLURM PMI vars will be set + # Differentiating between horovod and DDP use via SLURM may not be possible, so horovod arg still required... + ompi_vars = ["OMPI_COMM_WORLD_RANK", "OMPI_COMM_WORLD_SIZE"] + pmi_vars = ["PMI_RANK", "PMI_SIZE"] + if all([var in os.environ for var in ompi_vars]) or all([var in os.environ for var in pmi_vars]): + return True + else: + return False + + +def is_using_distributed(): + return True + if 'WORLD_SIZE' in os.environ: + return int(os.environ['WORLD_SIZE']) > 1 + if 'SLURM_NTASKS' in os.environ: + return int(os.environ['SLURM_NTASKS']) > 1 + return False + + +def world_info_from_env(): + local_rank = 0 + for v in ('LOCAL_RANK', 'MPI_LOCALRANKID', 'SLURM_LOCALID', 'OMPI_COMM_WORLD_LOCAL_RANK'): + if v in os.environ: + local_rank = int(os.environ[v]) + break + else: + raise Exception('local rank not found') + global_rank = 0 + for v in ('RANK', 'PMI_RANK', 'SLURM_PROCID', 'OMPI_COMM_WORLD_RANK'): + if v in os.environ: + global_rank = int(os.environ[v]) + break + else: + raise Exception('global rank not found') + world_size = 1 + for v in ('WORLD_SIZE', 'PMI_SIZE', 'SLURM_NTASKS', 'OMPI_COMM_WORLD_SIZE'): + if v in os.environ: + world_size = int(os.environ[v]) + break + else: + raise Exception('world size not found') + + return local_rank, global_rank, world_size + + +def init_distributed_device(args): + # Distributed training = training on more than one GPU. + # Works in both single and multi-node scenarios. + args.distributed = False + args.world_size = 1 + args.rank = 0 # global rank + args.local_rank = 0 + if args.horovod: + assert hvd is not None, "Horovod is not installed" + hvd.init() + args.local_rank = int(hvd.local_rank()) + args.rank = hvd.rank() + args.world_size = hvd.size() + args.distributed = True + os.environ['LOCAL_RANK'] = str(args.local_rank) + os.environ['RANK'] = str(args.rank) + os.environ['WORLD_SIZE'] = str(args.world_size) + elif is_using_distributed(): + if 'SLURM_PROCID' in os.environ: + # DDP via SLURM + args.local_rank, args.rank, args.world_size = world_info_from_env() + # SLURM var -> torch.distributed vars in case needed + os.environ['LOCAL_RANK'] = str(args.local_rank) + os.environ['RANK'] = str(args.rank) + os.environ['WORLD_SIZE'] = str(args.world_size) + torch.distributed.init_process_group( + backend=args.dist_backend, + init_method=args.dist_url, + world_size=args.world_size, + rank=args.rank, + ) + else: + # DDP via torchrun, torch.distributed.launch + args.local_rank, _, _ = world_info_from_env() + torch.distributed.init_process_group( + backend=args.dist_backend, + init_method=args.dist_url) + args.world_size = torch.distributed.get_world_size() + args.rank = torch.distributed.get_rank() + args.distributed = True + + if torch.cuda.is_available(): + if args.distributed and not args.no_set_device_rank: + device = 'cuda:%d' % args.local_rank + else: + device = 'cuda:0' + torch.cuda.set_device(device) + else: + device = 'cpu' + args.device = device + device = torch.device(device) + return device diff --git a/third_party/TinyCLIP/src/training/logger.py b/third_party/TinyCLIP/src/training/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..40cf6aa6cb59458e6b4833317a52d61faab1e57d --- /dev/null +++ b/third_party/TinyCLIP/src/training/logger.py @@ -0,0 +1,27 @@ +import logging + + +def setup_logging(log_file, level, include_host=False): + if include_host: + import socket + hostname = socket.gethostname() + formatter = logging.Formatter( + f'%(asctime)s | {hostname} | %(levelname)s | %(message)s', datefmt='%Y-%m-%d,%H:%M:%S') + else: + formatter = logging.Formatter( + '%(asctime)s | %(levelname)s | %(message)s', datefmt='%Y-%m-%d,%H:%M:%S') + + logging.root.setLevel(level) + loggers = [logging.getLogger(name) + for name in logging.root.manager.loggerDict] + for logger in loggers: + logger.setLevel(level) + + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + logging.root.addHandler(stream_handler) + + if log_file: + file_handler = logging.FileHandler(filename=log_file) + file_handler.setFormatter(formatter) + logging.root.addHandler(file_handler) diff --git a/third_party/TinyCLIP/src/training/loss_scaler.py b/third_party/TinyCLIP/src/training/loss_scaler.py new file mode 100644 index 0000000000000000000000000000000000000000..241ef15aa2d8518bed3d9cc0c1062daaa96a9056 --- /dev/null +++ b/third_party/TinyCLIP/src/training/loss_scaler.py @@ -0,0 +1,49 @@ +import torch +import numpy as np + + +def ampscaler_get_grad_norm(parameters, norm_type: float = 2.0) -> torch.Tensor: + if isinstance(parameters, torch.Tensor): + parameters = [parameters] + parameters = [p for p in parameters if p.grad is not None] + norm_type = float(norm_type) + if len(parameters) == 0: + return torch.tensor(0.) + device = parameters[0].grad.device + if norm_type == np.inf: + total_norm = max(p.grad.detach().abs().max().to(device) + for p in parameters) + else: + total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), + norm_type).to(device) for p in parameters]), norm_type) + return total_norm + + +class NativeScalerWithGradNormCount: + state_dict_key = "amp_scaler" + + def __init__(self, *args, **kwargs): + self._scaler = torch.cuda.amp.GradScaler(*args, **kwargs) + + def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True): + self._scaler.scale(loss).backward(create_graph=create_graph) + if update_grad: + if clip_grad is not None: + assert parameters is not None + # unscale the gradients of optimizer's assigned params in-place + self._scaler.unscale_(optimizer) + norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad) + else: + self._scaler.unscale_(optimizer) + norm = ampscaler_get_grad_norm(parameters) + self._scaler.step(optimizer) + self._scaler.update() + else: + norm = None + return norm + + def state_dict(self): + return self._scaler.state_dict() + + def load_state_dict(self, state_dict): + self._scaler.load_state_dict(state_dict) diff --git a/third_party/TinyCLIP/src/training/main.py b/third_party/TinyCLIP/src/training/main.py new file mode 100644 index 0000000000000000000000000000000000000000..baf80e1a2f4b87e65f71e389bb231c4216e27f32 --- /dev/null +++ b/third_party/TinyCLIP/src/training/main.py @@ -0,0 +1,564 @@ +import functools +import logging +import os +import json +import math +import random +from datetime import datetime + +import numpy as np +import torch +from torch import optim +import torch.nn.functional as F +from torch.cuda.amp import GradScaler + +from open_clip.model import convert_to_new_checkpoint, load_pruned_model +from open_clip.factory import load_model, get_tokenizer +import warnings +warnings.filterwarnings("ignore", category=UserWarning, module="torchvision") + +from open_clip.model import convert_to_new_checkpoint +from open_clip.weight_inherit import weight_inherit + +from training.optimizer import build_optimizer + + +try: + import wandb +except ImportError: + wandb = None + +try: + import torch.utils.tensorboard as tensorboard +except ImportError: + tensorboard = None + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + +from open_clip import create_model_and_transforms, trace_model +from training.data import get_data +from training.distributed import is_master, init_distributed_device, world_info_from_env +from training.logger import setup_logging +from training.params import parse_args +from training.scheduler import cosine_lr, cosine_lr_start, step_lr, cosine_lr_start_nowarmup +from training.train import train_one_epoch, evaluate + + +def random_seed(seed=42, rank=0): + torch.manual_seed(seed + rank) + np.random.seed(seed + rank) + random.seed(seed + rank) + + +def compute_params(model): + def _get_params(model): + if model is None: + return 0 + n_parameters = sum(p.numel() + for p in model.parameters() if p.requires_grad) + return n_parameters + + def _get_buffers(model): + if model is None: + return 0 + n_parameters = sum(p.numel() for p in model.buffers()) + return n_parameters + + n_parameters = _get_params(model) + num_params_image = _get_params(model.image_encoder_without_ddp.visual) + num_buffers_image = _get_buffers(model.image_encoder_without_ddp.visual) + num_params_text = _get_params(model.text_encoder_without_ddp.transformer) + num_token_emb = _get_params(model.text_encoder_without_ddp.token_embedding) if \ + model.text_encoder_without_ddp.transformer is not None else 0 + if model.text_encoder_without_ddp.transformer is not None and \ + sum(p.numel() for p in model.text_encoder_without_ddp.transformer.parameters()) > 0: + num_params_text += _get_params( + model.text_encoder_without_ddp.token_embedding) + num_params_text += _get_params(model.text_encoder_without_ddp.ln_final) + num_params_text += (model.text_encoder_without_ddp.positional_embedding.numel() + + model.text_encoder_without_ddp.text_projection.numel()) + return n_parameters, (num_params_image, num_buffers_image), num_params_text, num_token_emb + + +DEVICE = torch.device('cpu') + + +def _load_checkpoint(name): + global DEVICE + if '@' in name: + teacher_model_name, teacher_pretrained = name.split('@') + _model, _, _ = create_model_and_transforms( + teacher_model_name, pretrained=teacher_pretrained, device=DEVICE) + return _model.state_dict() + json_fname = os.path.join('exps', name + '.json') + if os.path.exists(json_fname): + model_info = json.load(open(json_fname)) + name = model_info['resume'] + state_dict = torch.load(name, map_location=DEVICE) + if 'state_dict' in state_dict: + state_dict = state_dict['state_dict'] + elif 'model' in state_dict: + state_dict = state_dict['model'] + return state_dict + + +def main(): + global DEVICE + args = parse_args() + + is_bf16_supported = torch.cuda.is_bf16_supported() + if not is_bf16_supported: + for name in ['precision', 'image_precision', 'text_precision', 'logit_precision']: + if getattr(args, name) == 'amp_bfloat16': + setattr(args, name, 'amp') + + if torch.cuda.is_available(): + # This enables tf32 on Ampere GPUs which is only 8% slower than + # float16 and almost as accurate as float32 + # This was a default in pytorch until 1.12 + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.benchmark = True + torch.backends.cudnn.deterministic = False + + # sanitize model name for filesystem / uri use, easier if we don't use / in name as a rule? + args.model = args.model.replace('/', '-') + + # get the name of the experiments + if args.name is None: + args.name = '-'.join([ + datetime.now().strftime("%Y_%m_%d-%H_%M_%S"), + f"model_{args.model}", + f"lr_{args.lr}", + f"b_{args.batch_size}", + f"j_{args.workers}", + f"p_{args.precision}", + ]) + + # discover initial world args early so we can log properly + args.distributed = False + args.local_rank, args.rank, args.world_size = world_info_from_env() + + args.log_path = None + if is_master(args, local=args.log_local): + log_base_path = os.path.join(args.logs, args.name) + os.makedirs(log_base_path, exist_ok=True) + log_filename = f'out-{args.rank}' if args.log_local else 'out.log' + args.log_path = os.path.join(log_base_path, log_filename) + if False and os.path.exists(args.log_path): + print( + "Error. Experiment already exists. Use --name {} to specify a new experiment." + ) + return -1 + + # Set logger + args.log_level = logging.DEBUG if args.debug else logging.INFO + setup_logging(args.log_path, args.log_level) + + # fully initialize distributed device environment + device = init_distributed_device(args) + DEVICE = device + + args.wandb = 'wandb' in args.report_to or 'all' in args.report_to + args.tensorboard = 'tensorboard' in args.report_to or 'all' in args.report_to + if is_master(args): + args.tensorboard_path = os.path.join( + args.logs, args.name, "tensorboard") if args.tensorboard else '' + args.checkpoint_path = os.path.join( + args.logs, args.name, "checkpoints") + for dirname in [args.tensorboard_path, args.checkpoint_path]: + if dirname: + os.makedirs(dirname, exist_ok=True) + else: + args.tensorboard_path = '' + args.checkpoint_path = '' + + assert args.precision in ['amp', 'amp_bfloat16', 'fp16', 'fp32'] + if args.precision == 'fp16': + logging.warning( + 'It is recommended to use AMP mixed-precision instead of FP16. ' + 'FP16 support needs further verification and tuning, especially for train.') + + if args.horovod: + logging.info( + f'Running in horovod mode with multiple processes / nodes. Device: {args.device}.' + f'Process (global: {args.rank}, local {args.local_rank}), total {args.world_size}.') + elif args.distributed: + logging.info( + f'Running in distributed mode with multiple processes. Device: {args.device}.' + f'Process (global: {args.rank}, local {args.local_rank}), total {args.world_size}.') + else: + logging.info(f'Running with a single process. Device {args.device}.') + + random_seed(args.seed, 0) + model, preprocess_train, preprocess_val = create_model_and_transforms( + args.model, + args.pretrained, + # the model will be converted to FP16 if args.precision is fp16 + precision=args.precision, + device=device, + jit=args.torchscript, + force_quick_gelu=args.force_quick_gelu, + pretrained_image=args.pretrained_image, + image_mean=args.image_mean, + image_std=args.image_std, + args=args, + ) + random_seed(args.seed, args.rank) + + if is_master(args, local=args.log_local): + logging.info('train: {}\n val: {}'.format( + preprocess_train, preprocess_val)) + + n_parameters, (num_params_image, + num_buffers_image), num_params_text, num_token_emb = compute_params(model) + if is_master(args): + logging.info(f"number of params: {n_parameters / 1e6}") + logging.info(f'number of params image: {num_params_image / 1e6}') + logging.info(f'number of buffers image: {num_buffers_image / 1e6}') + logging.info(f'number of params text: {num_params_text / 1e6}') + logging.info( + f'number of token embedding in text encoder : {num_token_emb / 1e6}') + + if args.distillation: + teacher_model = load_model(args.distillation_teacher, device=device) + + if args.grad_checkpointing: + teacher_model.set_grad_checkpointing() + teacher_model.eval() + teacher_model.cuda() + # frozen parameters + for p in teacher_model.parameters(): + p.requires_grad = False + + model.teacher = [teacher_model] + else: + teacher_model = None + + if args.trace: + model = trace_model(model, batch_size=args.batch_size, device=device) + + if args.lock_image: + # lock image tower as per LiT - https://arxiv.org/abs/2111.07991 + model.lock_image_tower( + unlocked_groups=args.lock_image_unlocked_groups, + freeze_bn_stats=args.lock_image_freeze_bn_stats) + logging.info('Locked image tower.') + + if args.lock_text: + model.lock_text_tower() + logging.info('Locked text tower.') + + model.cuda() + + if args.grad_checkpointing: + model.set_grad_checkpointing() + + if is_master(args): + logging.info("Model:") + logging.info(f"{str(model)}") + logging.info("Params:") + params_file = os.path.join(args.logs, args.name, "params.txt") + with open(params_file, "w") as f: + for name in sorted(vars(args)): + val = getattr(args, name) + logging.info(f" {name}: {val}") + f.write(f"{name}: {val}\n") + + model_without_ddp = model + + # create optimizer and scaler + optimizer = None + scaler = None + if args.train_data: + assert not args.trace, 'Cannot train with traced model' + + optimizer = build_optimizer(args, model) + assert not args.horovod + + use_loss_scale = any(map( + lambda x: x in ['amp', 'fp16'], + [args.precision, args.image_precision, args.text_precision, args.logit_precision])) + print(f'Use loss scale: {use_loss_scale}') + scaler = GradScaler(enabled=use_loss_scale) + + checkpoint_fname_list = [None] + if is_master(args): + if os.path.isdir(args.checkpoint_path): + ckpts_list = [] + for name in os.listdir(args.checkpoint_path): + if name.startswith('epoch_') and name.endswith('.pt'): + name = os.path.splitext(name)[0] + name = name[len('epoch_'):] + epoch, it = map(int, name.split('_iter_')) + ckpts_list.append((epoch, it)) + if len(ckpts_list) > 0: + ckpts_list.sort(reverse=True) + for epoch, it in ckpts_list: + checkpoint_fname = os.path.join( + args.checkpoint_path, f"epoch_{epoch}_iter_{it}.pt") + try: + # check valid + torch.load(checkpoint_fname, map_location='cpu') + checkpoint_fname_list[0] = checkpoint_fname + break + except Exception as e: + print(f'Load Ckpt Fail: {e}') + torch.distributed.broadcast_object_list(checkpoint_fname_list, src=0) + + if checkpoint_fname_list[0] is not None: + print( + f'overwrite checkpoint path: {checkpoint_fname_list[0]}, the original path is {args.resume}') + args.resume = checkpoint_fname_list[0] + + # determine if this worker should save logs and checkpoints. only do so if it is rank == 0 + start_epoch = 0 + + # optionally resume from a checkpoint + start_epoch = 0 + start_iter = 0 + if args.resume is not None: + # this part only suppots resume clip model without mask. [TODO]: support resume clip model with mask. + if os.path.isfile(args.resume): + checkpoint = torch.load(args.resume, map_location='cpu') + if args.prune_image and args.prune_text: + sd = checkpoint["state_dict"] + if not args.distributed and next(iter(sd.items()))[0].startswith('module'): + sd = {k[len('module.'):]: v for k, v in sd.items()} + sd = {k.replace('.module', ''): v for k, v in sd.items()} + logging.info('convert pruned model to base') + load_pruned_model(model, sd) + + if args.load_last_stage is False: + logging.info('=== FUSE MASK IMAGE ===') + num_params_before_fuse = sum( + p.numel() for p in model.image_encoder_without_ddp.parameters() if p.requires_grad) + with torch.no_grad(): + model.image_encoder_without_ddp.eval() + image = torch.randn((1, 3, 224, 224), device='cuda') + model.image_encoder_without_ddp(image) + model.image_encoder_without_ddp = model.image_encoder_without_ddp.prune() + assert hasattr( + model.image_encoder_without_ddp, 'l0_module') + model.image_encoder_without_ddp.l0_module = None + num_params_after_fuse = sum( + p.numel() for p in model.image_encoder_without_ddp.parameters() if p.requires_grad) + logging.info( + f'=> fuse MASK image: {num_params_before_fuse} -> {num_params_after_fuse}') + + logging.info('=== FUSE MASK TEXT ===') + num_params_before_fuse = sum( + p.numel() for p in model.text_encoder_without_ddp.parameters() if p.requires_grad) + with torch.no_grad(): + model.text_encoder_without_ddp.eval() + text = torch.randint(0, 100, (1, 77), device='cuda') + model.text_encoder_without_ddp(text) + model.text_encoder_without_ddp = model.text_encoder_without_ddp.prune() + assert hasattr(model.text_encoder_without_ddp, 'l0_module') + model.text_encoder_without_ddp.l0_module = None + num_params_after_fuse = sum( + p.numel() for p in model.text_encoder_without_ddp.parameters() if p.requires_grad) + logging.info( + f'=> fuse MASK text: {num_params_before_fuse} -> {num_params_after_fuse}') + args.save_logs = args.logs and args.logs.lower() != 'none' and is_master(args) + else: + sd = checkpoint["state_dict"] + new_state_dict = {} + for key, value in sd.items(): + if 'logit_scale' in key: + new_key = '_logit_scale.logit_scale' + elif key.startswith('module.visual'): + new_key = key.replace( + 'module.visual', '_image_encoder.visual') + elif key.startswith('module'): + new_key = key.replace('module', '_text_encoder') + else: + new_key = key + new_state_dict[new_key] = value + sd = new_state_dict + if not args.distributed and next(iter(sd.items()))[0].startswith('module'): + sd = {k[len('module.'):]: v for k, v in sd.items()} + model.load_state_dict(sd) + + if 'epoch' in checkpoint and args.load_last_stage is False: + # resuming a train checkpoint w/ epoch and optimizer state + start_epoch = checkpoint["epoch"] + + if optimizer is not None and 'optimizer' in checkpoint and args.load_last_stage is False: + if len(optimizer) == len(checkpoint['optimizer']): + for opt, v in zip(optimizer, checkpoint["optimizer"]): + assert len(opt.param_groups) == len(v['param_groups']), \ + f'number of param groups mismatch: {len(opt.param_groups)} vs {len(v["param_groups"])}' + opt.load_state_dict(v) + if scaler is not None and 'scaler' in checkpoint: + scaler.load_state_dict(checkpoint['scaler']) + else: + logging.info(f"optimizer load fails, use new one") + + if 'iter_in_epoch' in checkpoint and args.load_last_stage is False: + start_iter = checkpoint['iter_in_epoch'] + 1 + logging.info(f"fast_forward dataloader to iter {start_iter}") + + else: + raise FileNotFoundError(f'=> no checkpoint found at {args.resume}') + else: + + def remove_prefix_module(state_dict): + # remove the first or the second module + return convert_to_new_checkpoint(state_dict) + + def add_prefix_module(state_dict): + if all(map(lambda x: not x.startswith('module.'), state_dict.keys())): + return {'module.' + k: v for k, v in state_dict.items()} + return state_dict + + def model_load_checkpoint(model, state_dict): + if hasattr(model, 'module'): + state_dict = add_prefix_module(state_dict) + model.load_state_dict(state_dict, strict=True) + + def encoder_weight_inherit(student_state, teacher_state, encoder_prefix, head_dim): + def _filter_prefix(state, prefix): + return dict((k, v) for k, v in state.items() if k.startswith(prefix) and 'l0_module' not in k) + student_fs = _filter_prefix(student_state, encoder_prefix) + teacher_fs = _filter_prefix(teacher_state, encoder_prefix) + logging.info( + f' student: {len(student_fs)}, teacher: {len(teacher_fs)}') + weight_inherit(student_fs, teacher_fs, head_dim) + num = 0 + for k, v in student_fs.items(): + num += v.numel() + student_state[k] = v + return num + + if args.pretrained_image_file: + logging.info('=== INHERIT IMAGE ===') + # no resume, try to load image file + state_dict = remove_prefix_module(model.state_dict()) + # ckpt + image_checkpoint = remove_prefix_module( + _load_checkpoint(args.pretrained_image_file)) + num_inherit = encoder_weight_inherit( + state_dict, image_checkpoint, '_image_encoder.visual', head_dim=model.visual.head_dim) + # format: _image_encoder.xxxx + model_load_checkpoint(model, state_dict) + assert num_inherit == num_params_image + \ + num_buffers_image, (num_inherit, + num_params_image, num_buffers_image) + logging.info( + f'=> loaded image checkpoint {args.pretrained_image_file} ({num_inherit} image params)') + + if args.pretrained_text_file: + logging.info('=== INHERIT TEXT ===') + # student with ddp + state_dict = remove_prefix_module(model.state_dict()) + # teacher without ddp + text_checkpoint = remove_prefix_module( + _load_checkpoint(args.pretrained_text_file)) + # format: _text_encoder.xxxx + num_inherit = encoder_weight_inherit( + state_dict, text_checkpoint, '_text_encoder', head_dim=model.transformer.head_dim) + assert num_inherit == num_params_text, ( + num_inherit, num_params_text) + logging.info( + f'=> loaded text checkpoint {args.pretrained_text_file} ({num_inherit} text params)') + model_load_checkpoint(model, state_dict) + + if args.distributed and not args.horovod: + ddp_args = {} + if args.ddp_static_graph: + # this doesn't exist in older PyTorch, arg only added if enabled + ddp_args['static_graph'] = True + ddp_fn = functools.partial( + torch.nn.parallel.DistributedDataParallel, device_ids=[device], **ddp_args) + # re-ddpify + model.ddpify(ddp_fn) + + # initialize datasets + data = get_data(args, (preprocess_train, preprocess_val), + epoch=start_epoch, tokenizer=get_tokenizer(args.model)) + print(f"Dataset: {set(data.keys())}") + assert len(data), 'At least one train or eval dataset must be specified.' + + args.save_logs = args.logs and args.logs.lower() != 'none' and is_master(args) + writer = None + if args.save_logs and args.tensorboard: + assert tensorboard is not None, "Please install tensorboard." + writer = tensorboard.SummaryWriter(args.tensorboard_path) + + if args.wandb and is_master(args): + assert wandb is not None, 'Please install wandb.' + logging.debug('Starting wandb.') + args.train_sz = data["train"].dataloader.num_samples + if args.val_data is not None: + args.val_sz = data["val"].dataloader.num_samples + # you will have to configure this for your project! + wandb_output_path = args.checkpoint_path + wandb.init( + project="tinyclip", + name=args.name, + notes=args.wandb_notes, + tags=[], + config=vars(args), + dir=wandb_output_path, + ) + if args.debug: + wandb.watch(model, log='all') + wandb.save(params_file) + logging.debug('Finished loading wandb.') + + # create scheduler if train + scheduler = None + if 'train' in data and optimizer is not None: + total_steps = data["train"].dataloader.num_batches * args.epochs + if args.prune_image or args.prune_text: + scheduler = cosine_lr( + optimizer[0:3], args.lr, args.prune_step, total_steps) + scheduler_l0 = step_lr(optimizer[-1], args.prune_step) + else: + scheduler = cosine_lr(optimizer, args.lr, args.warmup, total_steps) + scheduler_l0 = None + + if 'train' not in data or args.eval: + results = evaluate(model, data, start_epoch, args, writer) + if is_master(args): + print(results) + return + + for epoch in range(start_epoch, math.ceil(args.epochs)): + if is_master(args): + logging.info(f'Start epoch {epoch}') + rtn = train_one_epoch(model, data, epoch, optimizer, scaler, + scheduler, scheduler_l0, args, writer, start_iter) + if isinstance(rtn, str) and rtn == 'non-finite loss': + break + else: + model, optimizer, scaler, scheduler, scheduler_l0, args = rtn + start_iter = 0 + + if args.wandb and is_master(args): + wandb.finish() + + +def copy_codebase(args): + from shutil import copytree, ignore_patterns + new_code_path = os.path.join(args.logs, args.name, "code") + if False and os.path.exists(new_code_path): + print( + f"Error. Experiment already exists at {new_code_path}. Use --name to specify a new experiment." + ) + return -1 + print(f"Copying codebase to {new_code_path}") + current_code_path = os.path.realpath(__file__) + for _ in range(3): + current_code_path = os.path.dirname(current_code_path) + copytree(current_code_path, new_code_path, + ignore=ignore_patterns('log', 'logs', 'wandb')) + print("Done copying code.") + return 1 + + +if __name__ == "__main__": + main() diff --git a/third_party/TinyCLIP/src/training/main_for_test.py b/third_party/TinyCLIP/src/training/main_for_test.py new file mode 100644 index 0000000000000000000000000000000000000000..a7ba56a084b9802245f13a37ef056f9d283bae1a --- /dev/null +++ b/third_party/TinyCLIP/src/training/main_for_test.py @@ -0,0 +1,415 @@ +import functools +import logging +import os +import json +import math +import random +from datetime import datetime + +import numpy as np +import torch +from torch import optim +import torch.nn.functional as F +from torch.cuda.amp import GradScaler + +from open_clip.model import convert_to_new_checkpoint, load_pruned_model +from open_clip.factory import load_model, get_tokenizer +import warnings +warnings.filterwarnings("ignore", category=UserWarning, module="torchvision") + +from open_clip.model import convert_to_new_checkpoint +from open_clip.weight_inherit import weight_inherit + + +try: + import wandb +except ImportError: + wandb = None + +try: + import torch.utils.tensorboard as tensorboard +except ImportError: + tensorboard = None + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + +from open_clip import create_model_and_transforms, trace_model +from training.data import get_data +from training.distributed import is_master, init_distributed_device, world_info_from_env +from training.params import parse_args +from training.train import evaluate + + +def random_seed(seed=42, rank=0): + torch.manual_seed(seed + rank) + np.random.seed(seed + rank) + random.seed(seed + rank) + + +def compute_params(model): + def _get_params(model): + if model is None: + return 0 + n_parameters = sum(p.numel() + for p in model.parameters() if p.requires_grad) + return n_parameters + + def _get_buffers(model): + if model is None: + return 0 + n_parameters = sum(p.numel() for p in model.buffers()) + return n_parameters + + n_parameters = _get_params(model) + num_params_image = _get_params(model.image_encoder_without_ddp.visual) + num_buffers_image = _get_buffers(model.image_encoder_without_ddp.visual) + num_params_text = _get_params(model.text_encoder_without_ddp.transformer) + num_token_emb = _get_params(model.text_encoder_without_ddp.token_embedding) if \ + model.text_encoder_without_ddp.transformer is not None else 0 + if model.text_encoder_without_ddp.transformer is not None and \ + sum(p.numel() for p in model.text_encoder_without_ddp.transformer.parameters()) > 0: + num_params_text += _get_params( + model.text_encoder_without_ddp.token_embedding) + num_params_text += _get_params(model.text_encoder_without_ddp.ln_final) + num_params_text += (model.text_encoder_without_ddp.positional_embedding.numel() + + model.text_encoder_without_ddp.text_projection.numel()) + return n_parameters, (num_params_image, num_buffers_image), num_params_text, num_token_emb + + +DEVICE = torch.device('cpu') + + +def _load_checkpoint(name): + global DEVICE + if '@' in name: + teacher_model_name, teacher_pretrained = name.split('@') + _model, _, _ = create_model_and_transforms( + teacher_model_name, pretrained=teacher_pretrained, device=DEVICE) + return _model.state_dict() + json_fname = os.path.join('exps', name + '.json') + if os.path.exists(json_fname): + model_info = json.load(open(json_fname)) + name = model_info['resume'] + state_dict = torch.load(name, map_location=DEVICE) + if 'state_dict' in state_dict: + state_dict = state_dict['state_dict'] + elif 'model' in state_dict: + state_dict = state_dict['model'] + return state_dict + + +def main(): + global DEVICE + args = parse_args() + + is_bf16_supported = torch.cuda.is_bf16_supported() + if not is_bf16_supported: + for name in ['precision', 'image_precision', 'text_precision', 'logit_precision']: + if getattr(args, name) == 'amp_bfloat16': + setattr(args, name, 'amp') + + if torch.cuda.is_available(): + # This enables tf32 on Ampere GPUs which is only 8% slower than + # float16 and almost as accurate as float32 + # This was a default in pytorch until 1.12 + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.benchmark = True + torch.backends.cudnn.deterministic = False + + # sanitize model name for filesystem / uri use, easier if we don't use / in name as a rule? + args.model = args.model.replace('/', '-') + + # get the name of the experiments + if args.name is None: + args.name = '-'.join([ + datetime.now().strftime("%Y_%m_%d-%H_%M_%S"), + f"model_{args.model}", + f"lr_{args.lr}", + f"b_{args.batch_size}", + f"j_{args.workers}", + f"p_{args.precision}", + ]) + + # discover initial world args early so we can log properly + args.distributed = False + args.local_rank, args.rank, args.world_size = world_info_from_env() + + # fully initialize distributed device environment + device = init_distributed_device(args) + DEVICE = device + + args.wandb = 'wandb' in args.report_to or 'all' in args.report_to + args.tensorboard = 'tensorboard' in args.report_to or 'all' in args.report_to + if is_master(args): + args.tensorboard_path = os.path.join( + args.logs, args.name, "tensorboard") if args.tensorboard else '' + args.checkpoint_path = os.path.join( + args.logs, args.name, "checkpoints") + for dirname in [args.tensorboard_path, args.checkpoint_path]: + if dirname: + os.makedirs(dirname, exist_ok=True) + else: + args.tensorboard_path = '' + args.checkpoint_path = '' + + assert args.precision in ['amp', 'amp_bfloat16', 'fp16', 'fp32'] + if args.precision == 'fp16': + logging.warning( + 'It is recommended to use AMP mixed-precision instead of FP16. ' + 'FP16 support needs further verification and tuning, especially for train.') + + if args.horovod: + logging.info( + f'Running in horovod mode with multiple processes / nodes. Device: {args.device}.' + f'Process (global: {args.rank}, local {args.local_rank}), total {args.world_size}.') + elif args.distributed: + logging.info( + f'Running in distributed mode with multiple processes. Device: {args.device}.' + f'Process (global: {args.rank}, local {args.local_rank}), total {args.world_size}.') + else: + logging.info(f'Running with a single process. Device {args.device}.') + + random_seed(args.seed, 0) + model, preprocess_train, preprocess_val = create_model_and_transforms( + args.model, + args.pretrained, + # the model will be converted to FP16 if args.precision is fp16 + precision=args.precision, + device=device, + jit=args.torchscript, + force_quick_gelu=args.force_quick_gelu, + pretrained_image=args.pretrained_image, + image_mean=args.image_mean, + image_std=args.image_std, + args=args, + ) + random_seed(args.seed, args.rank) + + if is_master(args, local=args.log_local): + logging.info('train: {}\n val: {}'.format( + preprocess_train, preprocess_val)) + + n_parameters, (num_params_image, + num_buffers_image), num_params_text, num_token_emb = compute_params(model) + if is_master(args): + logging.info(f"number of params: {n_parameters / 1e6}") + logging.info(f'number of params image: {num_params_image / 1e6}') + logging.info(f'number of buffers image: {num_buffers_image / 1e6}') + logging.info(f'number of params text: {num_params_text / 1e6}') + logging.info( + f'number of token embedding in text encoder : {num_token_emb / 1e6}') + + if args.distillation: + teacher_model = load_model(args.distillation_teacher, device=device) + + if args.grad_checkpointing: + teacher_model.set_grad_checkpointing() + teacher_model.eval() + teacher_model.cuda() + # frozen parameters + for p in teacher_model.parameters(): + p.requires_grad = False + + model.teacher = [teacher_model] + else: + teacher_model = None + + if args.trace: + model = trace_model(model, batch_size=args.batch_size, device=device) + + if args.lock_image: + # lock image tower as per LiT - https://arxiv.org/abs/2111.07991 + model.lock_image_tower( + unlocked_groups=args.lock_image_unlocked_groups, + freeze_bn_stats=args.lock_image_freeze_bn_stats) + logging.info('Locked image tower.') + + if args.lock_text: + model.lock_text_tower() + logging.info('Locked text tower.') + + model.cuda() + + if args.grad_checkpointing: + model.set_grad_checkpointing() + + if is_master(args): + logging.info("Model:") + logging.info(f"{str(model)}") + logging.info("Params:") + params_file = os.path.join(args.logs, args.name, "params.txt") + with open(params_file, "w") as f: + for name in sorted(vars(args)): + val = getattr(args, name) + logging.info(f" {name}: {val}") + f.write(f"{name}: {val}\n") + + model_without_ddp = model + + # determine if this worker should save logs and checkpoints. only do so if it is rank == 0 + start_epoch = 0 + data = get_data(args, (preprocess_train, preprocess_val), + epoch=start_epoch) + args.save_logs = args.logs and args.logs.lower() != 'none' and is_master(args) + writer = None + if args.save_logs and args.tensorboard: + assert tensorboard is not None, "Please install tensorboard." + writer = tensorboard.SummaryWriter(args.tensorboard_path) + + # optionally resume from a checkpoint + start_epoch = 0 + start_iter = 0 + if args.resume is not None: + # this part only suppots resume clip model without mask. [TODO]: support resume clip model with mask. + if os.path.isfile(args.resume): + checkpoint = torch.load(args.resume, map_location='cpu') + if args.prune_image and args.prune_text: + sd = checkpoint["state_dict"] + if not args.distributed and next(iter(sd.items()))[0].startswith('module'): + sd = {k[len('module.'):]: v for k, v in sd.items()} + sd = {k.replace('.module', ''): v for k, v in sd.items()} + logging.info('convert pruned model to base') + load_pruned_model(model, sd) + + if args.load_last_stage is False: + logging.info('=== FUSE MASK IMAGE ===') + num_params_before_fuse = sum( + p.numel() for p in model.image_encoder_without_ddp.parameters() if p.requires_grad) + with torch.no_grad(): + model.image_encoder_without_ddp.eval() + image = torch.randn((1, 3, 224, 224), device='cuda') + model.image_encoder_without_ddp(image) + model.image_encoder_without_ddp = model.image_encoder_without_ddp.prune() + assert hasattr( + model.image_encoder_without_ddp, 'l0_module') + model.image_encoder_without_ddp.l0_module = None + num_params_after_fuse = sum( + p.numel() for p in model.image_encoder_without_ddp.parameters() if p.requires_grad) + logging.info( + f'=> fuse MASK image: {num_params_before_fuse} -> {num_params_after_fuse}') + + logging.info('=== FUSE MASK TEXT ===') + num_params_before_fuse = sum( + p.numel() for p in model.text_encoder_without_ddp.parameters() if p.requires_grad) + with torch.no_grad(): + model.text_encoder_without_ddp.eval() + text = torch.randint(0, 100, (1, 77), device='cuda') + model.text_encoder_without_ddp(text) + model.text_encoder_without_ddp = model.text_encoder_without_ddp.prune() + assert hasattr(model.text_encoder_without_ddp, 'l0_module') + model.text_encoder_without_ddp.l0_module = None + num_params_after_fuse = sum( + p.numel() for p in model.text_encoder_without_ddp.parameters() if p.requires_grad) + logging.info( + f'=> fuse MASK text: {num_params_before_fuse} -> {num_params_after_fuse}') + args.save_logs = args.logs and args.logs.lower() != 'none' and is_master(args) + else: + sd = checkpoint["state_dict"] + new_state_dict = {} + for key, value in sd.items(): + if 'logit_scale' in key: + new_key = '_logit_scale.logit_scale' + elif key.startswith('module.visual'): + new_key = key.replace( + 'module.visual', '_image_encoder.visual') + elif key.startswith('module'): + new_key = key.replace('module', '_text_encoder') + else: + new_key = key + new_state_dict[new_key] = value + sd = new_state_dict + if not args.distributed and next(iter(sd.items()))[0].startswith('module'): + sd = {k[len('module.'):]: v for k, v in sd.items()} + model.load_state_dict(sd) + + if 'epoch' in checkpoint and args.load_last_stage is False: + # resuming a train checkpoint w/ epoch and optimizer state + start_epoch = checkpoint["epoch"] + + else: + raise FileNotFoundError(f'=> no checkpoint found at {args.resume}') + else: + + def remove_prefix_module(state_dict): + # remove the first or the second module + return convert_to_new_checkpoint(state_dict) + + def add_prefix_module(state_dict): + if all(map(lambda x: not x.startswith('module.'), state_dict.keys())): + return {'module.' + k: v for k, v in state_dict.items()} + return state_dict + + def model_load_checkpoint(model, state_dict): + if hasattr(model, 'module'): + state_dict = add_prefix_module(state_dict) + model.load_state_dict(state_dict, strict=True) + + def encoder_weight_inherit(student_state, teacher_state, encoder_prefix, head_dim): + def _filter_prefix(state, prefix): + return dict((k, v) for k, v in state.items() if k.startswith(prefix) and 'l0_module' not in k) + student_fs = _filter_prefix(student_state, encoder_prefix) + teacher_fs = _filter_prefix(teacher_state, encoder_prefix) + logging.info( + f' student: {len(student_fs)}, teacher: {len(teacher_fs)}') + weight_inherit(student_fs, teacher_fs, head_dim) + num = 0 + for k, v in student_fs.items(): + num += v.numel() + student_state[k] = v + return num + + if args.pretrained_image_file: + logging.info('=== INHERIT IMAGE ===') + # no resume, try to load image file + state_dict = remove_prefix_module(model.state_dict()) + # ckpt + image_checkpoint = remove_prefix_module( + _load_checkpoint(args.pretrained_image_file)) + num_inherit = encoder_weight_inherit( + state_dict, image_checkpoint, '_image_encoder.visual', head_dim=model.visual.transformer.head_dim) + # format: _image_encoder.xxxx + model_load_checkpoint(model, state_dict) + assert num_inherit == num_params_image + \ + num_buffers_image, (num_inherit, + num_params_image, num_buffers_image) + logging.info( + f'=> loaded image checkpoint {args.pretrained_image_file} ({num_inherit} image params)') + + if args.pretrained_text_file: + logging.info('=== INHERIT TEXT ===') + # student with ddp + state_dict = remove_prefix_module(model.state_dict()) + # teacher without ddp + text_checkpoint = remove_prefix_module( + _load_checkpoint(args.pretrained_text_file)) + # format: _text_encoder.xxxx + num_inherit = encoder_weight_inherit( + state_dict, text_checkpoint, '_text_encoder', head_dim=model.transformer.head_dim) + assert num_inherit == num_params_text, ( + num_inherit, num_params_text) + logging.info( + f'=> loaded text checkpoint {args.pretrained_text_file} ({num_inherit} text params)') + model_load_checkpoint(model, state_dict) + + if args.distributed and not args.horovod: + ddp_args = {} + if args.ddp_static_graph: + # this doesn't exist in older PyTorch, arg only added if enabled + ddp_args['static_graph'] = True + ddp_fn = functools.partial( + torch.nn.parallel.DistributedDataParallel, device_ids=[device], **ddp_args) + # re-ddpify + model.ddpify(ddp_fn) + + if 'train' not in data or args.eval: + results = evaluate(model, data, start_epoch, args, writer) + if is_master(args): + print(results) + return + + +if __name__ == "__main__": + main() diff --git a/third_party/TinyCLIP/src/training/my_meter.py b/third_party/TinyCLIP/src/training/my_meter.py new file mode 100644 index 0000000000000000000000000000000000000000..40ba12d24dc727eaee426976ed201d3abc7c389b --- /dev/null +++ b/third_party/TinyCLIP/src/training/my_meter.py @@ -0,0 +1,72 @@ +# -------------------------------------------------------- +# TinyViT Utils +# Copyright (c) 2022 Microsoft +# -------------------------------------------------------- + +import torch +import torch.distributed as dist + + +def reduce_tensor(tensor, n=None): + if n is None: + n = dist.get_world_size() + rt = tensor.clone() + dist.all_reduce(rt, op=dist.ReduceOp.SUM) + rt = rt / n + return rt + + +class AverageMeter: + """Computes and stores the average and current value""" + + def __init__(self): + self.reset() + + def reset(self): + # local + self._val = 0 + self._sum = 0 + self._count = 0 + # global + self._history_avg = 0 + self._history_count = 0 + self._avg = None + + def update(self, val, n=1): + self._val = val + self._sum += val * n + self._count += n + self._avg = None + + @property + def val(self): + return self._val + + @property + def count(self): + return self._count + self._history_count + + @property + def avg(self): + if self._avg is None: + # compute avg + r = self._history_count / max(1, self._history_count + self._count) + _avg = self._sum / max(1, self._count) + self._avg = r * self._history_avg + (1.0 - r) * _avg + return self._avg + + def sync(self): + buf = torch.tensor([self._sum, self._count], + dtype=torch.float32).cuda() + buf = reduce_tensor(buf, 1) + _sum, _count = buf.tolist() + _avg = _sum / max(1, _count) + r = self._history_count / max(1, self._history_count + _count) + + self._history_avg = r * self._history_avg + (1.0 - r) * _avg + self._history_count += _count + + self._sum = 0 + self._count = 0 + + self._avg = None diff --git a/third_party/TinyCLIP/src/training/optimizer.py b/third_party/TinyCLIP/src/training/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..ff9bee6fa766e16b10a6d9961baf629ac40abbbe --- /dev/null +++ b/third_party/TinyCLIP/src/training/optimizer.py @@ -0,0 +1,101 @@ +from torch import optim +import logging + + +class EmptyOptimizer: + def __init__(self): + self.param_groups = [] + + def step(self, *args, **kwargs): + pass + + def state_dict(self): + return dict() + + def load_state_dict(self, *args, **kwargs): + pass + + def zero_grad(self): + pass + + +def build_optimizer(args, model): + def exclude( + n, p): return p.ndim < 2 or "bn" in n or "ln" in n or "bias" in n or 'logit_scale' in n + + def include(n, p): return not exclude(n, p) + + named_parameters = list(model.named_parameters()) + # we create three optimizer for image encode, text encoder, and jointly part + model_parts = [ + list(model.image_named_params()), + list(model.text_named_params()), + list(model.joint_named_params()), + ] + + cnt1 = sum(v.numel() for k, v in named_parameters if v.requires_grad) + cnt2 = sum(sum(v.numel() for k, v in part if v.requires_grad) + for part in model_parts) + assert cnt1 == cnt2, f"cnt1 {cnt1} != cnt2 {cnt2}" + + optimizer = [] + part_names = ['image', 'text', 'joint'] + assert len(model_parts) == len(part_names) + for name, named_parameters in zip(part_names, model_parts): + gain_or_bias_params = [p for n, p in named_parameters if exclude( + n, p) and p.requires_grad and "l0_module" not in n] + rest_params = [p for n, p in named_parameters if include( + n, p) and p.requires_grad and "l0_module" not in n] + params_groups = [ + {"params": gain_or_bias_params, "weight_decay": 0.}, + {"params": rest_params, "weight_decay": args.wd}, + ] + + num_opt_params = 0 + for pg in params_groups: + num_opt_params += sum(p.numel() for p in pg['params']) + + logging.info(f'number of optimizer ({name}) params: {num_opt_params}') + + if num_opt_params > 0: + optimizer_i = optim.AdamW( + params_groups, + lr=args.lr, + betas=(args.beta1, args.beta2), + eps=args.eps, + ) + else: + optimizer_i = EmptyOptimizer() + optimizer.append(optimizer_i) + + if args.prune_image or args.prune_text: + lr_l0 = 0.02 + lr_lamda = args.l0lr + l0_params = [] + # add l0 optimizer + if args.prune_image: + l0_params.extend([ + { + "params": [p for n, p in model.image_named_params() if p.requires_grad and "lambda" not in n and "l0_module" in n], + "weight_decay": 0.0, + "lr": lr_l0 + }, { + "params": [p for n, p in model.image_named_params() if p.requires_grad and "lambda" in n and "l0_module" in n], + "weight_decay": 0.0, + "lr": lr_lamda + }]) + if args.prune_text: + l0_params.extend([ + { + "params": [p for n, p in model.text_named_params() if p.requires_grad and "lambda" not in n and "l0_module" in n], + "weight_decay": 0.0, + "lr": lr_l0 + }, { + "params": [p for n, p in model.text_named_params() if p.requires_grad and "lambda" in n and "l0_module" in n], + "weight_decay": 0.0, + "lr": lr_lamda + }]) + l0_optimizer = optim.AdamW(l0_params) + optimizer.append(l0_optimizer) + + return optimizer diff --git a/third_party/TinyCLIP/src/training/params.py b/third_party/TinyCLIP/src/training/params.py new file mode 100644 index 0000000000000000000000000000000000000000..406257eac71f9a6f3a208e9aac5588c8786fe659 --- /dev/null +++ b/third_party/TinyCLIP/src/training/params.py @@ -0,0 +1,437 @@ +import argparse + + +def get_default_params(model_name): + # Params from paper (https://arxiv.org/pdf/2103.00020.pdf) + model_name = model_name.lower() + if "vit" in model_name: + return {"lr": 5.0e-4, "beta1": 0.9, "beta2": 0.98, "eps": 1.0e-6} + else: + return {"lr": 5.0e-4, "beta1": 0.9, "beta2": 0.999, "eps": 1.0e-8} + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--train-data", + type=str, + default=None, + help="Path to csv filewith training data", + ) + parser.add_argument( + "--val-data", + type=str, + default=None, + help="Path to csv file with validation data", + ) + parser.add_argument( + "--train-num-samples", + type=int, + default=None, + help="Number of samples in dataset. Required for webdataset if not available in info file.", + ) + parser.add_argument( + "--val-num-samples", + type=int, + default=None, + help="Number of samples in dataset. Useful for webdataset if not available in info file.", + ) + parser.add_argument( + "--dataset-type", + choices=["webdataset", "csv", "auto", "tsv", "blobchunk", "synthetic"], + default="auto", + help="Which type of dataset to process." + ) + parser.add_argument( + "--dataset-resampled", + default=False, + action="store_true", + help="Whether to use sampling with replacement for webdataset shard selection." + ) + parser.add_argument( + "--csv-separator", + type=str, + default="\t", + help="For csv-like datasets, which separator to use." + ) + parser.add_argument( + "--csv-img-key", + type=str, + default="filepath", + help="For csv-like datasets, the name of the key for the image paths." + ) + parser.add_argument( + "--csv-caption-key", + type=str, + default="title", + help="For csv-like datasets, the name of the key for the captions." + ) + parser.add_argument( + "--imagenet-val", + type=str, + default=None, + help="Path to imagenet val set for conducting zero shot evaluation.", + ) + parser.add_argument( + "--imagenet-v2", + type=str, + default=None, + help="Path to imagenet v2 for conducting zero shot evaluation.", + ) + parser.add_argument( + "--logs", + type=str, + default="./logs/", + help="Where to store tensorboard logs. Use None to avoid storing logs.", + ) + parser.add_argument( + "--log-local", + action="store_true", + default=False, + help="log files on local master, otherwise global master only.", + ) + parser.add_argument( + "--name", + type=str, + default=None, + help="Optional identifier for the experiment when storing logs. Otherwise use current time.", + ) + parser.add_argument( + "--workers", type=int, default=1, help="Number of dataloader workers per GPU." + ) + parser.add_argument( + "--batch-size", type=int, default=64, help="Batch size per GPU." + ) + parser.add_argument( + "--epochs", type=float, default=32, help="Number of epochs to train for." + ) + parser.add_argument("--lr", type=float, default=None, + help="Learning rate.") + parser.add_argument("--beta1", type=float, + default=None, help="Adam beta 1.") + parser.add_argument("--beta2", type=float, + default=None, help="Adam beta 2.") + parser.add_argument("--eps", type=float, default=None, + help="Adam epsilon.") + parser.add_argument("--wd", type=float, default=0.2, help="Weight decay.") + parser.add_argument( + "--warmup", type=int, default=10000, help="Number of steps to warmup for." + ) + parser.add_argument( + "--use-bn-sync", + default=False, + action="store_true", + help="Whether to use batch norm sync.") + parser.add_argument( + "--skip-scheduler", + action="store_true", + default=False, + help="Use this flag to skip the learning rate decay.", + ) + parser.add_argument( + "--save-frequency", type=int, default=1, help="How often to save checkpoints." + ) + parser.add_argument( + "--save-most-recent", + action="store_true", + default=False, + help="Always save the most recent model trained to epoch_latest.pt.", + ) + parser.add_argument( + "--zeroshot-frequency", type=int, default=1, help="How often to run zero shot." + ) + parser.add_argument( + "--val-frequency", type=int, default=1, help="How often to run evaluation with val data." + ) + parser.add_argument( + "--resume", + default=None, + type=str, + help="path to latest checkpoint (default: none)", + ) + parser.add_argument( + "--precision", + choices=["amp", "amp_bfloat16", "fp16", "fp32"], + default="amp", + help="Floating point precision." + ) + parser.add_argument( + "--image-precision", + type=str, + help="Floating point precision for image encoder" + ) + parser.add_argument( + "--text-precision", + type=str, + help="Floating point precision for text encoder" + ) + parser.add_argument( + "--logit-precision", + type=str, + help="Floating point precision for logit scale" + ) + parser.add_argument( + "--model", + type=str, + default="RN50", + help="Name of the vision backbone to use.", + ) + parser.add_argument( + "--pretrained", + default='', + type=str, + help="Use a pretrained CLIP model weights with the specified tag or file path.", + ) + parser.add_argument( + "--pretrained-image-file", + default='', + type=str, + help="Use a pretrained CLIP image model weights with the specified tag or file path.", + ) + parser.add_argument( + "--pretrained-text-file", + default='', + type=str, + help="Use a pretrained CLIP text model weights with the specified tag or file path.", + ) + parser.add_argument( + "--pretrained-image", + default=False, + action='store_true', + help="Load imagenet pretrained weights for image tower backbone if available.", + ) + parser.add_argument( + "--lock-image", + default=False, + action='store_true', + help="Lock full image tower by disabling gradients.", + ) + parser.add_argument( + "--lock-text", + default=False, + action='store_true', + help="Lock full text tower by disabling gradients.", + ) + parser.add_argument( + "--use-teacher-image", + default=False, + action='store_true', + help="Use teacher image encoder", + ) + parser.add_argument( + "--use-teacher-text", + default=False, + action='store_true', + help="Use teacher text encoder", + ) + parser.add_argument( + "--lock-image-unlocked-groups", + type=int, + default=0, + help="Leave last n image tower layer groups unlocked.", + ) + parser.add_argument( + "--lock-image-freeze-bn-stats", + default=False, + action='store_true', + help="Freeze BatchNorm running stats in image tower for any locked layers.", + ) + parser.add_argument( + '--image-mean', type=float, nargs='+', default=None, metavar='MEAN', + help='Override default image mean value of dataset') + parser.add_argument( + '--image-std', type=float, nargs='+', default=None, metavar='STD', + help='Override default image std deviation of of dataset') + parser.add_argument( + "--grad-checkpointing", + default=False, + action='store_true', + help="Enable gradient checkpointing.", + ) + parser.add_argument( + "--grad-cache-times", + type=int, + default=1, + help="Gradient cache times.", + ) + parser.add_argument( + "--local-loss", + default=False, + action="store_true", + help="calculate loss w/ local features @ global (instead of realizing full global @ global matrix)" + ) + parser.add_argument( + "--gather-with-grad", + default=False, + action="store_true", + help="enable full distributed gradient for feature gather" + ) + parser.add_argument( + "--force-quick-gelu", + default=False, + action='store_true', + help="Force use of QuickGELU activation for non-OpenAI transformer models.", + ) + parser.add_argument( + "--torchscript", + default=False, + action='store_true', + help="torch.jit.script the model, also uses jit version of OpenAI models if pretrained=='openai'", + ) + parser.add_argument( + "--trace", + default=False, + action='store_true', + help="torch.jit.trace the model for inference / eval only", + ) + # arguments for distributed training + parser.add_argument( + "--dist-url", + default="env://", + type=str, + help="url used to set up distributed training", + ) + parser.add_argument( + "--dist-backend", default="nccl", type=str, help="distributed backend" + ) + parser.add_argument( + "--report-to", + default='', + type=str, + help="Options are ['wandb', 'tensorboard', 'wandb,tensorboard']" + ) + parser.add_argument( + "--wandb-notes", + default='', + type=str, + help="Notes if logging with wandb" + ) + parser.add_argument( + "--debug", + default=False, + action="store_true", + help="If true, more information is logged." + ) + parser.add_argument( + "--prune-image", + default=False, + action="store_true", + help="If true, use Image mask." + ) + parser.add_argument( + "--prune-text", + default=False, + action="store_true", + help="If true, use text mask." + ) + parser.add_argument( + "--prune-step", + type=int, default=3000, + help="prune model step, stop mask learn, warmup step." + ) + parser.add_argument( + "--sparsity-warmup", + type=int, default=1000, + help="number of steps that mask sparsity reaches target sparsity." + ) + parser.add_argument( + "--target-sparsity", + type=float, default=0.25, + help="target sparsity of this training stage." + ) + parser.add_argument( + "--start-sparsity", + type=float, default=0, + help="start sparsity of this training stage." + ) + parser.add_argument( + "--total-loss-flag", + default=False, + action="store_true", + help="use image and text branch to calculate overall sparsity" + ) + parser.add_argument( + "--load-last-stage", + default=False, + action="store_true", + help="use image and text branch to calculate overall sparsity" + ) + parser.add_argument( + "--l0lr", type=float, default=-0.02, help="mask Learning rate." + ) + parser.add_argument( + "--copy-codebase", + default=False, + action="store_true", + help="If true, we copy the entire base on the log diretory, and execute from there." + ) + parser.add_argument( + "--horovod", + default=False, + action="store_true", + help="Use horovod for distributed training." + ) + parser.add_argument( + "--ddp-static-graph", + default=False, + action='store_true', + help="Enable static graph optimization for DDP in PyTorch >= 1.11.", + ) + parser.add_argument( + "--no-set-device-rank", + default=False, + action="store_true", + help="Don't set device index from local rank (when CUDA_VISIBLE_DEVICES restricted to one per proc)." + ) + parser.add_argument( + "--seed", type=int, default=0, help="Default random seed." + ) + + parser.add_argument( + "--norm_gradient_clip", type=float, default=None, help="Gradient clip." + ) + + parser.add_argument( + "--distillation", + default=False, + action="store_true", + ) + parser.add_argument( + "--distillation-weight", # for soft label + type=float, + default=1.0, + help="Weight for distillation.", + ) + parser.add_argument( + "--distillation-alpha", # for soft label + type=float, + default=1.0, + help="Alpha for distillation.", + ) + parser.add_argument( + "--distillation-teacher", + type=str, + help='Teacher model for distillation.', + ) + parser.add_argument( + "--eval", + default=False, + action="store_true", + ) + parser.add_argument( + "--logit-scale", + type=float, + help="both student and teacher's logit scale, basic: 100" + ) + args = parser.parse_args() + + if args.distillation_teacher is not None: + args.distillation = True + + # If some params are not passed, we use the default values based on model name. + default_params = get_default_params(args.model) + for name, val in default_params.items(): + if getattr(args, name) is None: + setattr(args, name, val) + + return args diff --git a/third_party/TinyCLIP/src/training/precision.py b/third_party/TinyCLIP/src/training/precision.py new file mode 100644 index 0000000000000000000000000000000000000000..4f456ea8bd87e0c81631358bcc2d3ab37dfbd2fb --- /dev/null +++ b/third_party/TinyCLIP/src/training/precision.py @@ -0,0 +1,15 @@ +import torch +from contextlib import suppress + +# amp_bfloat16 is more stable than amp float16 for clip training + + +def get_autocast(precision): + if precision == 'amp': + return torch.cuda.amp.autocast + elif precision == 'amp_bfloat16': + return lambda: torch.cuda.amp.autocast(dtype=torch.bfloat16) + elif precision == 'fp32': + return lambda: torch.cuda.amp.autocast(enabled=False) + else: + return suppress diff --git a/third_party/TinyCLIP/src/training/scheduler.py b/third_party/TinyCLIP/src/training/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..cfdbfb9411dd606f65b2b1d7f00479124f891617 --- /dev/null +++ b/third_party/TinyCLIP/src/training/scheduler.py @@ -0,0 +1,83 @@ +import numpy as np + + +def assign_learning_rate(optimizer, new_lr): + if isinstance(optimizer, list): + for opt in optimizer: + assign_learning_rate(opt, new_lr) + else: + for param_group in optimizer.param_groups: + param_group["lr"] = new_lr + + +def _warmup_lr(base_lr, warmup_length, step): + return base_lr * (step + 1) / warmup_length + + +def cosine_lr(optimizer, base_lr, warmup_length, steps): + def _lr_adjuster(step): + if step < warmup_length: + lr = _warmup_lr(base_lr, warmup_length, step) + else: + e = step - warmup_length + es = steps - warmup_length + lr = 0.5 * (1 + np.cos(np.pi * e / es)) * base_lr + assign_learning_rate(optimizer, lr) + return lr + return _lr_adjuster + + +def cosine_lr_start(optimizer, base_lr, warmup_length, steps, start_steps): + def _lr_adjuster(step): + if step < start_steps: + # lr = 0.0001 + lr = 0.00005 + elif step < warmup_length + start_steps: + lr = _warmup_lr(base_lr, warmup_length, step - start_steps) + else: + e = step - warmup_length - start_steps + es = steps - warmup_length - start_steps + lr = 0.5 * (1 + np.cos(np.pi * e / es)) * base_lr + assign_learning_rate(optimizer, lr) + return lr + return _lr_adjuster + + +def cosine_lr_start_nowarmup(optimizer, base_lr, steps, start_steps): + def _lr_adjuster(step): + if step < start_steps: + lr = 0.0001 + else: + e = step - start_steps + es = steps - start_steps + lr = 0.5 * (1 + np.cos(np.pi * e / es)) * base_lr + assign_learning_rate(optimizer, lr) + return lr + return _lr_adjuster + + +def step_lr(optimizer, start_steps): + def _lr_adjuster(step): + if step > start_steps: + lr = 0 + assign_learning_rate(optimizer, lr) + return lr + else: + return None + return _lr_adjuster + + +def exponential_lr(optimizer, base_lr, warmup_length, steps, gamma, w): + def _lr_adjuster(step): + if step < warmup_length: + lr = _warmup_lr(base_lr, warmup_length, step) + else: + e = step - warmup_length + es = steps - warmup_length + # lr = base_lr * gamma ** (e / es * w) + # min_lr = base_lr * gamma ** (w) + # w = np.log(min_lr / base_lr) / np.log(gamma) + lr = base_lr * gamma ** (e / es * w) + assign_learning_rate(optimizer, lr) + return lr + return _lr_adjuster diff --git a/third_party/TinyCLIP/src/training/train.py b/third_party/TinyCLIP/src/training/train.py new file mode 100644 index 0000000000000000000000000000000000000000..8f685a298df4046dbd274efc8ed36a5cea1961f6 --- /dev/null +++ b/third_party/TinyCLIP/src/training/train.py @@ -0,0 +1,773 @@ +import json +import logging +import math +import os +import psutil +import functools +import time +from collections import defaultdict + +import numpy as np +import torch +from torch import optim +import torch.nn.functional as F +from timm.utils import get_state_dict +from torch.utils.data._utils.collate import default_collate +from collections import UserDict + +try: + import wandb +except ImportError: + wandb = None + +from open_clip import ClipLoss +from open_clip.clip_soft_loss import ClipSoftLoss +from timm.utils.model import unwrap_model +from .distributed import is_master +from .zero_shot import zero_shot_eval +from .precision import get_autocast +from training.optimizer import build_optimizer +from training.scheduler import cosine_lr, cosine_lr_start, step_lr, cosine_lr_start_nowarmup +import torch.distributed as dist +from training.my_meter import AverageMeter, reduce_tensor + + +def _stack2cat(items): + if isinstance(items, torch.Tensor): + shape = items.shape + shape = (shape[0] * shape[1],) + shape[2:] + return items.view(shape) + elif isinstance(items, (list, tuple)): + return [_stack2cat(e) for e in items] + elif isinstance(items, (dict, UserDict)): + return {k: _stack2cat(v) for k, v in items.items()} + else: + raise TypeError(f'Unsupported type {type(items)}') + + +def cat_items(items): + # items: [Tensor, Tensor, ...] -> Tensor, + # [(Tensor, Tensor), (Tensor, Tensor)] -> (Tensor, Tensor) + # [(Tensor, [Tensor, Tensor]), (Tensor, [Tensor, Tensor])] -> (Tensor, [Tensor, Tensor]) + items = default_collate(items) # stack of items + # stack -> cat + items = _stack2cat(items) + return items + + +def infer_chunks(fn, x, times): + if times == 1: + return fn(x) + ys = [] + for e in x.chunk(times): + ys.append(fn(e)) + return cat_items(ys) + + +def check_last_batch(it): + ''' + input: iterator + return: (item, is_last_batch) + ''' + last = None + for x in it: + if last is not None: + yield last, False + last = x + if last is not None: + yield last, True + + +NAN_LOSS_CNT = 0 + + +def train_one_epoch(model, data, epoch, optimizer, scaler, scheduler, scheduler_l0, args, tb_writer=None, start_iter=0, zs=None): + + global NAN_LOSS_CNT + + device = torch.device(args.device) + autocast = get_autocast(args.precision) + + image_autocast = get_autocast(args.image_precision) + text_autocast = get_autocast(args.text_precision) + logit_autocast = get_autocast(args.logit_precision) + + model.set_autocast( + image_autocast=image_autocast, + text_autocast=text_autocast, + logit_autocast=logit_autocast) + + teacher_autocast = torch.cuda.amp.autocast + + model_without_ddp = unwrap_model(model) + + distillation = args.distillation + if distillation: + teacher_model = model_without_ddp.teacher[0] + + model.train() + loss_kwargs = dict( + local_loss=args.local_loss, + gather_with_grad=args.gather_with_grad, + cache_labels=True, + rank=args.rank, + world_size=args.world_size, + use_horovod=args.horovod) + + if start_iter == 0: + # set epoch in process safe manner via sampler or shared_epoch + data['train'].set_epoch(epoch) + dataloader = data['train'].dataloader + + dataloader.device = args.device + if distillation: + soft_loss_fn = ClipSoftLoss(**loss_kwargs) # , ignore_diag=True) + else: + soft_loss_fn = None + + hard_loss_fn = ClipLoss(**loss_kwargs) + + dataloader, sampler = data['train'].dataloader, data['train'].sampler + if args.distributed and sampler is not None and start_iter == 0: + # [DO NOT REMOVE IT] it will call set_epoch even if sampler is not a DistributedSampler. + sampler.set_epoch(epoch) + + num_batches_per_epoch = dataloader.num_batches + sample_digits = math.ceil(math.log(dataloader.num_samples + 1, 10)) + + loss_m = AverageMeter() + metrics = defaultdict(AverageMeter) + end = time.time() + batch_size = dataloader.batch_size + samples_per_epoch = dataloader.num_samples + total_batch_size = batch_size * args.world_size + num_feed_images = samples_per_epoch * epoch + start_iter * total_batch_size + num_feed_images_after_epoch = samples_per_epoch * (epoch + 1) + all_num_feed_images = ( + int(samples_per_epoch * args.epochs) // total_batch_size * total_batch_size) + + # for float epoch + is_last_epoch = (epoch + 1 >= args.epochs) + samples_per_epoch_r = samples_per_epoch if not is_last_epoch else all_num_feed_images - \ + epoch * samples_per_epoch + num_batches_per_epoch_r = samples_per_epoch_r // total_batch_size + + eval_freq = int(os.getenv('EVAL_FREQ', 1000)) + save_freq = int(os.getenv('SAVE_FREQ', 1000)) + + # define model_fn and loss_fn + infer_teacher_image = True + + def loss_fn(student_outputs, + teacher_outputs): + image_features = student_outputs['image_features'] + text_features = student_outputs['text_features'] + logit_scale = student_outputs['logit_scale'] + + teacher_image_features = teacher_outputs['image_features'] + teacher_text_features = teacher_outputs['text_features'] + teacher_logit_scale = teacher_outputs['logit_scale'] + labels = teacher_outputs['labels'] + + losses = dict() + if distillation: + if args.distillation_alpha > 0.0 and args.distillation_weight > 0.0: + soft_loss_weight = args.distillation_alpha * args.distillation_weight + img2text_loss, text2img_loss = soft_loss_fn(image_features, text_features, logit_scale, + teacher_image_features, teacher_text_features, teacher_logit_scale, + labels=labels, + average_two_losses=False, + ) + + img2text_loss *= 0.5 * soft_loss_weight + text2img_loss *= 0.5 * soft_loss_weight + soft_loss = img2text_loss + text2img_loss + + losses['soft_loss'] = soft_loss + + metrics['soft_img2text_loss'].update(img2text_loss.item()) + metrics['soft_text2img_loss'].update(text2img_loss.item()) + + # Hard Loss + if args.distillation_alpha < 1.0 and args.distillation_weight > 0.0: + hard_loss = hard_loss_fn(image_features, text_features, logit_scale) *\ + ((1.0 - args.distillation_alpha) * args.distillation_weight) + losses['hard_loss'] = hard_loss + else: + losses['loss'] = hard_loss_fn( + image_features, text_features, logit_scale) + + total_loss = 0 + for k, v in losses.items(): + metrics[k].update(v.item()) + assert v.requires_grad, k + total_loss += v + return total_loss + + def grad_cache_loss_fn(student_outputs, teacher_outputs): + image_features, text_features, logit_scale = student_outputs + student_outputs = dict( + image_features=image_features, + text_features=text_features, + logit_scale=logit_scale, + ) + return loss_fn(student_outputs, teacher_outputs) + + gpu_mem_info = torch.cuda.mem_get_info() + gpu_memory_used = (gpu_mem_info[1] - gpu_mem_info[0]) / (1024 ** 3) + metrics['gpu_memory'].update(gpu_memory_used) + + cpu_mem_info = psutil.virtual_memory() + cpu_memory_used = cpu_mem_info.used / (1024 ** 3) + metrics['cpu_memory'].update(cpu_memory_used) + + rest_shm = psutil.disk_usage('/dev/shm').free / (1024 ** 3) + metrics['rest_shm'].update(rest_shm) + + def forward_backward_fn(model, images, texts, outputs_no_grad): + image_feat_no_grad, text_feat_no_grad, logit_scale_no_grad = outputs_no_grad + if args.lock_image: + images = None + if args.lock_text: + texts = None + + with autocast(): + image_feat, text_feat, logit_scale = model( + images, texts, normalized=True) + + if image_feat is None: + image_feat = image_feat_no_grad + if text_feat is None: + text_feat = text_feat_no_grad + return image_feat, text_feat, logit_scale + + def naive_model_fn(student_inputs, teacher_outputs, total_loss_flag=True): + images, texts = student_inputs + with autocast(): + + # clean outputs first to avoid the error when using MXS + outputs_no_grad = [None, None, None] + student_outputs = forward_backward_fn( + model, images, texts, outputs_no_grad) + del images, texts, student_inputs + + loss = grad_cache_loss_fn(student_outputs, teacher_outputs) + + use_image_mask = getattr( + model.image_encoder_without_ddp, 'l0_module', None) is not None + use_text_mask = getattr( + model.text_encoder_without_ddp, 'l0_module', None) is not None + if total_loss_flag and use_image_mask and use_text_mask: + img_mask = model.image_encoder_without_ddp.l0_module + txt_mask = model.text_encoder_without_ddp.l0_module + all_para_txt = txt_mask.prunable_model_size + all_para_img = img_mask.prunable_model_size + remain_para_txt = txt_mask.get_num_parameters_and_constraint( + "hidden" in txt_mask.types) + remain_para_img = img_mask.get_num_parameters_and_constraint( + "hidden" in img_mask.types) + expected_sparsity = 1 - \ + (remain_para_txt + remain_para_img) / \ + (all_para_txt + all_para_img) + target_sparsity_img = img_mask.get_target_sparsity( + step) if img_mask.lagrangian_warmup > 0 else img_mask.target_sparsity + target_sparsity_txt = txt_mask.get_target_sparsity( + step) if txt_mask.lagrangian_warmup > 0 else txt_mask.target_sparsity + target_sparsity = (target_sparsity_img + + target_sparsity_txt) / 2 + lambda_1_ = (img_mask.lambda_1 + txt_mask.lambda_1) / 2 + lambda_2_ = (img_mask.lambda_2 + txt_mask.lambda_2) / 2 + zero = torch.tensor(0.0, device=expected_sparsity.device) + total_lagrangian_loss = ( + lambda_1_ * torch.maximum(target_sparsity - expected_sparsity, zero) + + lambda_2_ * + torch.maximum(target_sparsity - + expected_sparsity, zero).square() + ) + loss = loss + total_lagrangian_loss + metrics['all_expected_sparsity'].update(expected_sparsity) + metrics['vision_expected_sparsity'].update( + 1 - remain_para_img / all_para_img) + metrics['text_expected_sparsity'].update( + 1 - remain_para_txt / all_para_txt) + metrics['all_target_sparsity'].update(target_sparsity) + metrics['all_lagran_loss'].update(total_lagrangian_loss) + else: + if use_image_mask: + lagran_loss, expected_sparsity, target_sparsity = \ + model.image_encoder_without_ddp.l0_module.lagrangian_regularization( + step) + loss = loss + lagran_loss + metrics['vision_expected_sparsity'].update( + expected_sparsity) + metrics['vision_target_sparsity'].update(target_sparsity) + metrics['vision_lagran_loss'].update(lagran_loss) + if use_text_mask: + lagran_loss, expected_sparsity, target_sparsity = \ + model.text_encoder_without_ddp.l0_module.lagrangian_regularization( + step) + loss = loss + lagran_loss + metrics['text_expected_sparsity'].update(expected_sparsity) + metrics['text_target_sparsity'].update(target_sparsity) + metrics['text_lagran_loss'].update(lagran_loss) + + scaler.scale(loss).backward() + return loss + + grad_cache = naive_model_fn + + def teacher_image_fn(images): + feat = teacher_model.encode_image(images) + outputs = torch.tensor([]) + return F.normalize(feat, dim=-1), outputs + + def teacher_text_fn(texts): + feat = teacher_model.encode_text(texts) + outputs = torch.tensor([]) + return F.normalize(feat, dim=-1), outputs + + for (i, batch), is_last_batch in check_last_batch(enumerate(dataloader, start=start_iter)): + step = num_batches_per_epoch * epoch + i + num_feed_images += total_batch_size + + if step == args.prune_step and model.image_encoder_without_ddp.l0_module is not None and model.text_encoder_without_ddp.l0_module is not None: + logging.info('=== FUSE MASK IMAGE ===') + num_params_before_fuse = sum( + p.numel() for p in model.image_encoder_without_ddp.parameters() if p.requires_grad) + with torch.no_grad(): + model.image_encoder_without_ddp.eval() + image = torch.randn((1, 3, 224, 224), device='cuda') + model.image_encoder_without_ddp(image) + model.image_encoder_without_ddp = model.image_encoder_without_ddp.prune() + assert hasattr(model.image_encoder_without_ddp, 'l0_module') + model.image_encoder_without_ddp.l0_module = None + num_params_after_fuse = sum( + p.numel() for p in model.image_encoder_without_ddp.parameters() if p.requires_grad) + logging.info( + f'=> fuse MASK image: {num_params_before_fuse} -> {num_params_after_fuse}') + + logging.info('=== FUSE MASK TEXT ===') + num_params_before_fuse = sum( + p.numel() for p in model.text_encoder_without_ddp.parameters() if p.requires_grad) + with torch.no_grad(): + model.text_encoder_without_ddp.eval() + text = torch.randint(0, 100, (1, 77), device='cuda') + model.text_encoder_without_ddp(text) + model.text_encoder_without_ddp = model.text_encoder_without_ddp.prune() + assert hasattr(model.text_encoder_without_ddp, 'l0_module') + model.text_encoder_without_ddp.l0_module = None + num_params_after_fuse = sum( + p.numel() for p in model.text_encoder_without_ddp.parameters() if p.requires_grad) + logging.info( + f'=> fuse MASK text: {num_params_before_fuse} -> {num_params_after_fuse}') + + # results = evaluate(model, data, epoch, args) + if args.distributed and not args.horovod: + if args.use_bn_sync: + model = torch.nn.SyncBatchNorm.convert_sync_batchnorm( + model) + ddp_args = {} + if args.ddp_static_graph: + # this doesn't exist in older PyTorch, arg only added if enabled + ddp_args['static_graph'] = True + ddp_fn = functools.partial( + torch.nn.parallel.DistributedDataParallel, device_ids=[device], **ddp_args) + model.ddpify(ddp_fn) + model_without_ddp = model + + args.prune_image = False + args.prune_text = False + use_mask = False + + optimizer = build_optimizer(args, model) + scheduler = cosine_lr_start_nowarmup( + optimizer[0:3], args.lr, num_batches_per_epoch * args.epochs, args.prune_step) + + scheduler(step) + if scheduler_l0 != None: + scheduler_l0(step) + + if len(batch) == 2: + images, texts = batch + images = images.to(device, non_blocking=True) + texts = texts.to(device, non_blocking=True) + labels = None + else: + images, texts, labels = batch + images = images.to(device, non_blocking=True) + texts = texts.to(device, non_blocking=True) + labels = labels.to(device, non_blocking=True) + + metrics['data_time'].update(time.time() - end) + for opt in optimizer: + opt.zero_grad() + + if distillation: + # infer teacher + + if args.logit_scale is not None: + teacher_model.logit_scale.fill_(math.log(args.logit_scale)) + + with teacher_autocast(): + with torch.no_grad(): + if infer_teacher_image: + teacher_image_features, teacher_image_outputs = infer_chunks( + teacher_image_fn, images, 1) + else: + teacher_image_features = teacher_image_outputs = None + teacher_text_features, teacher_text_outputs = infer_chunks( + teacher_text_fn, texts, 1) + teacher_logit_scale = teacher_model.logit_scale.exp() + + else: + teacher_image_features = teacher_image_outputs = None + teacher_text_features = teacher_text_outputs = None + teacher_logit_scale = None + + grad_norm = None + # detach and it has been backwarded + infer_student_image = not args.use_teacher_image + infer_student_text = not args.use_teacher_text + + student_inputs = [] + for x, used in zip([images, texts], [infer_student_image, infer_student_text]): + if used: + student_inputs.append(x) + else: + student_inputs.append(None) + + use_mask = args.prune_image or args.prune_text + used_optimizer = [] + for opt, used in zip(optimizer, [ + infer_student_image and not args.lock_image, + infer_student_text and not args.lock_text, + True, + use_mask + ]): + if used: + used_optimizer.append(opt) + + # append optimizer + + teacher_outputs = dict( + image_features=teacher_image_features, + text_features=teacher_text_features, + logit_scale=teacher_logit_scale, + image_outputs=teacher_image_outputs, + text_outputs=teacher_text_outputs, + labels=labels, + ) + + total_loss = grad_cache( + student_inputs, teacher_outputs=teacher_outputs, total_loss_flag=args.total_loss_flag) + skip_this_step = False + + # check nan loss + if not torch.isfinite(total_loss): + NAN_LOSS_CNT += 1 + if NAN_LOSS_CNT > 100: + print( + f'WARNING: non-finite loss, ending training loss: {total_loss}') + return 'non-finite loss' + skip_this_step = True + print( + f'WARNING: non-finite loss, skip this step. loss: {total_loss}, nan_loss_cnt: {NAN_LOSS_CNT}') + else: + NAN_LOSS_CNT = 0 + + ''' + a potential bug: + there are three branches: image, text, logit + each optimizer has its own `found_inf_per_device`. + The three `found_inf_per_device` should be synced, otherwise a branch will be updated with wrong gradients? + ''' + # check loss + for opt in used_optimizer: + scaler.unscale_(opt) + + # sync found_inf_per_device + found_inf = sum( + sum(v.item() for v in scaler._per_optimizer_states[id( + opt)]['found_inf_per_device'].values()) + for opt in used_optimizer + ) + if found_inf > 0: + for opt in used_optimizer: + for v in scaler._per_optimizer_states[id(opt)]['found_inf_per_device'].values(): + v.fill_(True) + + if args.norm_gradient_clip is not None: + grad_norm = torch.nn.utils.clip_grad_norm_( + model.parameters(), args.norm_gradient_clip, norm_type=2.0) + + # evaluate(model, data, epoch, args, tb_writer, step=step, num_feed_images=num_feed_images) + if not skip_this_step: + for opt in used_optimizer: + scaler.step(opt) + scaler.update() + + if getattr(model.image_encoder_without_ddp, 'l0_module', None) is not None: + model._image_encoder.module.l0_module.constrain_parameters() + metrics['vision_lambda1'].update( + model._image_encoder.module.l0_module.lambda_1.detach().item()) + metrics['vision_lambda2'].update( + model._image_encoder.module.l0_module.lambda_2.detach().item()) + if getattr(model.text_encoder_without_ddp, 'l0_module', None) is not None: + model._text_encoder.module.l0_module.constrain_parameters() + metrics['text_lambda1'].update( + model._text_encoder.module.l0_module.lambda_1.detach().item()) + metrics['text_lambda2'].update( + model._text_encoder.module.l0_module.lambda_2.detach().item()) + + loss_scale = scaler.state_dict()["scale"] + metrics['loss_scale'].update(loss_scale) + + # Note: we clamp to 4.6052 = ln(100), as in the original paper. + with torch.no_grad(): + if args.logit_scale is not None: + model_without_ddp.logit_scale.fill_(math.log(args.logit_scale)) + else: + model_without_ddp.logit_scale.clamp_(0, math.log(100)) + + batch_time_cost = time.time() - end + metrics['batch_time'].update(batch_time_cost) + end = time.time() + + if batch_time_cost > 0: + metrics['throughput'].update(total_batch_size / batch_time_cost) + + batch_count = i + 1 + if is_master(args) and (i % 10 == 0 or is_last_batch): + + num_samples = batch_count * total_batch_size + percent_complete = 100.0 * batch_count / num_batches_per_epoch + + # NOTE loss is coarsely sampled, just master node and per log update + loss_m.update(total_loss.item(), batch_size) + logit_scale_scalar = model_without_ddp.logit_scale.exp().item() + metrics_str = '' + for k, v in metrics.items(): + metrics_str += '{}: {:.4f} ({:.4f})\t'.format(k, v.val, v.avg) + logging.info( + f"Train Epoch: {epoch} [{batch_count}/{num_batches_per_epoch_r}] [{num_samples:>{sample_digits}}/{samples_per_epoch_r} ({percent_complete:.0f}%)] " + f"Loss: {loss_m.val:#.5g} ({loss_m.avg:#.4g}) " + f"{metrics_str} " + f"LR: {optimizer[0].param_groups[0]['lr']:5f} " + f"Logit Scale: {logit_scale_scalar:.3f}" + ) + + # Save train loss / etc. Using non avg meter values as loggers have their own smoothing + log_data = { + "loss": loss_m.val, + "scale": logit_scale_scalar, + "lr": optimizer[0].param_groups[0]["lr"], + "lr_l0": optimizer[-1].param_groups[0]["lr"] + } + + for k, v in metrics.items(): + log_data[k] = v.val + for name, val in log_data.items(): + name = "train/" + name + if tb_writer is not None: + tb_writer.add_scalar(name, val, step) + if args.wandb: + assert wandb is not None, 'Please install wandb.' + wandb.log({name: val, 'step': step, + 'num_feed_images': num_feed_images}, step=step) + + if i > 2000: + eval_freq = 500 + do_evaluate = ((i + 1) % eval_freq == 0 or is_last_batch) + do_save_checkpoint = ((i + 1) % save_freq == 0 or is_last_batch) + use_mask = args.prune_image or args.prune_text + if step == 0 and use_mask: + do_evaluate = True + + if ((i + 1) % eval_freq == 0 or is_last_batch) or step == 0: + from training.viz import plot + if args.prune_image: + model.eval() + layers = model._image_encoder.module.l0_module.num_hidden_layers + hidden_size = model._image_encoder.module.l0_module.hidden_size + heads = model._image_encoder.module.l0_module.num_attention_heads + l0device = model._image_encoder.module.l0_module.z_logas[ + model._image_encoder.module.l0_module.types[0]].device + zs_img = model._image_encoder.module.l0_module() + sparsity_img = model._image_encoder.module.l0_module.calculate_model_size(zs_img)[ + 'pruned_sparsity'] + if 'mha_z' not in zs_img.keys(): + zs_img['mha_z'] = torch.ones([layers]).to(l0device) + if 'ffn_z' not in zs_img.keys(): + zs_img['ffn_z'] = torch.ones([layers]).to(l0device) + if 'hidden_z' not in zs_img.keys(): + zs_img['hidden_z'] = torch.ones([hidden_size]).to(l0device) + if 'heads_z' not in zs_img.keys(): + zs_img['heads_z'] = torch.ones( + [layers, 1, heads, 1, 1]).to(l0device) + if 'intermediate_z' not in zs_img.keys(): + zs_img['intermediate_z'] = torch.ones( + [layers, 1, 1, hidden_size * 4]).to(l0device) + hidden_img = zs_img['hidden_z'].detach( + ).cpu().squeeze().numpy() + heads_img = zs_img['mha_z'].detach().cpu().squeeze().numpy( + ).reshape(-1, 1) * zs_img['heads_z'].detach().cpu().squeeze().numpy() + intermediates_img = zs_img['ffn_z'].detach().cpu().squeeze().numpy( + ).reshape(-1, 1) * zs_img['intermediate_z'].detach().cpu().squeeze().numpy() + fig_img = plot(heads_img, intermediates_img, + f"Sparsity_img: {sparsity_img:.2%}") + if dist.get_rank() == 0 and args.wandb: + wandb.log({ + "test/sparsity_img": sparsity_img, + "pruned_structure_img": fig_img + }, step=step) + model.train() + + if args.prune_text: + model.eval() + layers = model._text_encoder.module.l0_module.num_hidden_layers + hidden_size = model._text_encoder.module.l0_module.hidden_size + heads = model._text_encoder.module.l0_module.num_attention_heads + l0device = model._text_encoder.module.l0_module.z_logas[ + model._text_encoder.module.l0_module.types[0]].device + zs_txt = model._text_encoder.module.l0_module() + sparsity_txt = model._text_encoder.module.l0_module.calculate_model_size(zs_txt)[ + 'pruned_sparsity'] + if 'mha_z' not in zs_txt.keys(): + zs_txt['mha_z'] = torch.ones([layers]).to(l0device) + if 'ffn_z' not in zs_txt.keys(): + zs_txt['ffn_z'] = torch.ones([layers]).to(l0device) + if 'hidden_z' not in zs_txt.keys(): + zs_txt['hidden_z'] = torch.ones([hidden_size]).to(l0device) + if 'heads_z' not in zs_txt.keys(): + zs_txt['heads_z'] = torch.ones( + [layers, 1, heads, 1, 1]).to(l0device) + if 'intermediate_z' not in zs_txt.keys(): + zs_txt['intermediate_z'] = torch.ones( + [layers, 1, 1, hidden_size * 4]).to(l0device) + hidden_txt = zs_txt['hidden_z'].detach( + ).cpu().squeeze().numpy() + heads_txt = zs_txt['mha_z'].detach().cpu().squeeze().numpy( + ).reshape(-1, 1) * zs_txt['heads_z'].detach().cpu().squeeze().numpy() + intermediates_txt = zs_txt['ffn_z'].detach().cpu().squeeze().numpy( + ).reshape(-1, 1) * zs_txt['intermediate_z'].detach().cpu().squeeze().numpy() + fig_txt = plot(heads_txt, intermediates_txt, + f"Sparsity_txt: {sparsity_txt:.2%}") + if dist.get_rank() == 0 and args.wandb: + wandb.log({ + "test/sparsity_txt": sparsity_txt, + "pruned_structure_txt": fig_txt + }, step=step) + model.train() + + if do_evaluate: + if any(v in data for v in ('val', 'imagenet-val', 'imagenet-v2')): + evaluate(model, data, epoch, args, tb_writer, + step=step, num_feed_images=num_feed_images) + model.train() + + if do_save_checkpoint and is_master(args): + # Saving checkpoints. + if args.save_logs: + num_batches = len(dataloader) + samples_per_epoch = dataloader.num_samples + checkpoint_dict = { + "args": args, + "epoch": epoch, + "iter_in_epoch": i, + "num_batches": num_batches, + "samples_per_epoch": samples_per_epoch, + "name": args.name, + "state_dict": model.state_dict(), + "optimizer": [opt.state_dict() for opt in optimizer], + } + if scaler is not None: + checkpoint_dict["scaler"] = scaler.state_dict() + # Model EMA + if hasattr(model_without_ddp, '_model_ema'): + ema_models_state = [get_state_dict( + model_ema) for model_ema in model_without_ddp._model_ema] + checkpoint_dict['model_emas'] = ema_models_state + + checkpoint_fname = os.path.join( + args.checkpoint_path, f"epoch_{epoch}_iter_{i}.pt") + torch.save( + checkpoint_dict, + checkpoint_fname, + ) + print(f"Save checkpoint to {checkpoint_fname}") + + if num_feed_images >= all_num_feed_images: + break + + print( + f'Feed ALL Data: {num_feed_images}/{num_feed_images_after_epoch}/{all_num_feed_images}') + return model, optimizer, scaler, scheduler, scheduler_l0, args + # end for + + +def evaluate(model, data, epoch, args, tb_writer=None, step=None, num_feed_images=None): + metrics = {} + models = [model] + names = [''] + assert len(names) == len(models) + for name, model_i in zip(names, models): + model_i.eval() + zero_shot_metrics = zero_shot_eval(model_i, data, epoch, args) + zero_shot_metrics = dict((name + k, v) + for k, v in zero_shot_metrics.items()) + metrics.update(zero_shot_metrics) + + if not metrics: + return metrics + + if not is_master(args): + return metrics + + logging.info( + f"Eval Epoch: {epoch} " + + "\t".join([f"{k}: {round(v, 4):.4f}" for k, v in metrics.items()]) + ) + + if args.save_logs: + for name, val in metrics.items(): + if tb_writer is not None: + tb_writer.add_scalar(f"val/{name}", val, epoch) + + with open(os.path.join(args.checkpoint_path, "results.jsonl"), "a+") as f: + f.write(json.dumps(metrics)) + f.write("\n") + + if args.wandb: + assert wandb is not None, 'Please install wandb.' + for name, val in metrics.items(): + log = {f"val/{name}": val, 'epoch': epoch} + extra_kwargs = dict() + if step is not None: + log['step'] = step + extra_kwargs['step'] = step + if num_feed_images is not None: + log['num_feed_images'] = num_feed_images + wandb.log(log, **extra_kwargs) + return metrics + + +def get_metrics(image_features, text_features, logit_scale): + metrics = {} + logits_per_image = (logit_scale * image_features @ + text_features.t()).detach().cpu() + logits_per_text = logits_per_image.t().detach().cpu() + + logits = {"image_to_text": logits_per_image, + "text_to_image": logits_per_text} + ground_truth = torch.arange(len(text_features)).view(-1, 1) + + for name, logit in logits.items(): + ranking = torch.argsort(logit, descending=True) + preds = torch.where(ranking == ground_truth)[1] + preds = preds.detach().cpu().numpy() + metrics[f"{name}_mean_rank"] = preds.mean() + 1 + metrics[f"{name}_median_rank"] = np.floor(np.median(preds)) + 1 + for k in [1, 5, 10]: + metrics[f"{name}_R@{k}"] = np.mean(preds < k) + + return metrics diff --git a/third_party/TinyCLIP/src/training/viz.py b/third_party/TinyCLIP/src/training/viz.py new file mode 100644 index 0000000000000000000000000000000000000000..3b09d1fffb2fa49f19f344be89e3794b2402e9bb --- /dev/null +++ b/third_party/TinyCLIP/src/training/viz.py @@ -0,0 +1,66 @@ +# -------------------------------------------------------- +# reference: https://github.com/crj1998/pruning/tree/master +# -------------------------------------------------------- +import matplotlib.pyplot as plt +import matplotlib.patches as mpatches +import matplotlib.cm as cm +from matplotlib.colors import LinearSegmentedColormap + +import numpy as np + + +color_list = ['pink', 'deepskyblue'] + +my_cmap = LinearSegmentedColormap.from_list('custom', color_list) + +cm.register_cmap(cmap=my_cmap) + + +def plot(heads, intermediates, name): + fig, ax = plt.subplots(1, 2, facecolor='white', figsize=( + 10, 4), dpi=120, gridspec_kw={'width_ratios': [1.15, 3]}) + + heads_num = heads.shape[1] + ax[0].matshow(heads, cmap="custom", vmin=0.0, vmax=1.0) + ax[0].set_xlabel("Heads") + ax[0].set_ylabel("Layer") + ax[0].set_xticks([i for i in range(heads_num)], [str(i + 1) + for i in range(heads_num)]) + ax[0].set_yticks([i for i in range(12)], [str(i + 1) for i in range(12)]) + # Minor ticks + ax[0].set_xticks([i - 0.5 for i in range(heads_num)], minor=True) + ax[0].set_yticks([i - 0.5 for i in range(12)], minor=True) + ax[0].xaxis.tick_bottom() + ax[0].tick_params('both', length=0, width=0, which='both') + + # Gridlines based on minor ticks + ax[0].grid(which='minor', color='w', linestyle='-', linewidth=1) + ax[0].set_title('MHAs') + + channel = intermediates.shape[1] / 4 + intermediates = intermediates.repeat(100, axis=0) + ax[1].matshow(intermediates, cmap="custom", vmin=0.0, vmax=1.0) + ax[1].set_xlabel("FFNs channels") + + ax[1].set_xticks([i * channel for i in range(1, 5)], + [f'{i}.0x' for i in range(1, 5)]) + ax[1].set_yticks([i * 100 + 50 for i in range(12)], + [str(i + 1) for i in range(12)]) + ax[1].set_yticks([i * 100 for i in range(12)], minor=True) + + # Minor ticks + + ax[1].xaxis.tick_bottom() + ax[1].yaxis.tick_right() + + ax[1].tick_params('both', length=0, width=0, which='both') + + # Gridlines based on minor ticks + ax[1].grid(which='minor', axis='y', color='w', linestyle='-', linewidth=1) + ax[1].set_title('FFNs') + + fig.tight_layout() + + fig.suptitle(name) + + return fig diff --git a/third_party/TinyCLIP/src/training/zero_shot.py b/third_party/TinyCLIP/src/training/zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..82eacacccaf7df2b86f7b3b182a9730176db7b0c --- /dev/null +++ b/third_party/TinyCLIP/src/training/zero_shot.py @@ -0,0 +1,162 @@ +import os +import copy +import logging + +import torch +import torch.nn.functional as F +import torch.distributed as dist +from tqdm import tqdm + +from open_clip import tokenize +from .precision import get_autocast +from timm.utils.model import unwrap_model +from open_clip.imagenet_zeroshot_data import imagenet_classnames, openai_imagenet_template + + +def all_gather(tensor, group, return_tensor=False, args=None): + """Perform an all-gather operation.""" + world_size = args.world_size + tensor_list = [ + torch.empty_like(tensor) for _ in range(world_size) + ] + dist.all_gather(tensor_list, tensor, group=group) + if return_tensor: + return torch.stack(tensor_list, dim=0) + else: + return tensor_list + + +def zero_shot_classifier(model, classnames, templates, args): + # templates = templates + [lambda c: f'{c}.'] + model = unwrap_model(model) + rank = args.rank + world_size = args.world_size + padding_classnames = copy.deepcopy(classnames) + mod = len(classnames) % world_size + if mod > 0: + padding_classnames += padding_classnames[:world_size - mod] + + def _get_classname_emb(classname): + texts = [template.format(classname) if isinstance(template, str) else template( + classname) for template in templates] # format with class + texts = tokenize(texts).cuda(non_blocking=True) # tokenize + class_embeddings = model.encode_text(texts) + class_embedding = F.normalize(class_embeddings, dim=-1).mean(dim=0) + class_embedding /= class_embedding.norm() + return class_embedding + + with torch.no_grad(): + zeroshot_weights = [] + part_size = len(padding_classnames) // world_size + for classname in (padding_classnames[part_size * rank:part_size * (rank + 1)]): + class_embedding = _get_classname_emb(classname) + zeroshot_weights.append(class_embedding) + zeroshot_weights = torch.stack(zeroshot_weights, dim=1) + + tensor_list = [ + torch.empty_like(zeroshot_weights) for _ in range(world_size) + ] + dist.all_gather(tensor_list, zeroshot_weights) + zeroshot_weights = tensor_list + zeroshot_weights = torch.cat(zeroshot_weights, dim=1) + zeroshot_weights = zeroshot_weights[:, :len(classnames)] + + return zeroshot_weights + + +def accuracy(output, target, topk=(1,)): + pred = output.topk(max(topk), 1, True, True)[1].t() + correct = pred.eq(target.view(1, -1).expand_as(pred)) + return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) for k in topk] + + +def run(model, classifier, dataloader, args): + autocast = get_autocast(args.precision) + model = unwrap_model(model) + total_batch_size = dataloader.batch_size * args.world_size + with torch.no_grad(): + top1, top5, n = 0., 0., 0. + bar = tqdm(dataloader, unit_scale=total_batch_size) + for images, target in bar: + images = images.to(args.device) + target = target.to(args.device) + batch_size = images.size(0) + + with autocast(): + # predict + image_features = model.encode_image(images) + image_features = F.normalize(image_features, dim=-1) + logits = 100. * image_features @ classifier + + # measure accuracy + acc1, acc5 = accuracy(logits, target, topk=(1, 5)) + bar.set_description( + f'Acc@1 {acc1 / batch_size:.3f} Acc@5 {acc5 / batch_size:.3f}') + top1 += acc1 + top5 += acc5 + n += batch_size + del images, target, logits + + # sync top1, top5 and n + data = torch.tensor([top1, top5, n]).cuda() + dist.all_reduce(data, op=dist.ReduceOp.SUM) + top1, top5, n = data.tolist() + + top1 = (top1 / n) + top5 = (top5 / n) + return top1, top5 + + +def zero_shot_eval(model, data, epoch, args): + results = {} + + if 'imagenet-val' not in data and 'imagenet-v2' not in data: + return {} + if args.zeroshot_frequency == 0: + return {} + if (epoch % args.zeroshot_frequency) != 0 and epoch != args.epochs: + return {} + + logging.info('Starting zero-shot imagenet.') + + model_without_ddp = unwrap_model(model) + + classifier_fname = os.getenv("EVAL_EMB", None) + if classifier_fname is None or not os.path.exists(classifier_fname): + logging.info(f'Building new zero-shot classifier: {classifier_fname}') + text_classifier_name = 'text_classifier' + classifier = None + + # if the text encoder is frozen + enabled_saved_classifier = args.lock_text + + if enabled_saved_classifier: + if hasattr(model_without_ddp, text_classifier_name): + classifier = getattr(model_without_ddp, text_classifier_name) + if classifier is None: + classifier = zero_shot_classifier( + model, imagenet_classnames, openai_imagenet_template, args) + if enabled_saved_classifier: + setattr(model_without_ddp, text_classifier_name, classifier) + + if classifier_fname is not None and args.local_rank == 0: + torch.save(classifier.detach().T.cpu(), classifier_fname) + else: + logging.info(f'Apply saved zero-shot classifier, {classifier_fname}') + classifier = torch.load(classifier_fname).T.cuda() + + logging.info('Using classifier') + if 'imagenet-val' in data: + top1, top5 = run(model, classifier, + data['imagenet-val'].dataloader, args) + results['imagenet-zeroshot-val-top1'] = top1 + results['imagenet-zeroshot-val-top5'] = top5 + if 'imagenet-v2' in data: + top1, top5 = run(model, classifier, + data['imagenet-v2'].dataloader, args) + results['imagenetv2-zeroshot-val-top1'] = top1 + results['imagenetv2-zeroshot-val-top5'] = top5 + + logging.info('Finished zero-shot imagenet.') + + return results diff --git a/third_party/utils/logger.py b/third_party/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..2a130b52093c15c961e0d029333dd2e06296db52 --- /dev/null +++ b/third_party/utils/logger.py @@ -0,0 +1,12 @@ +import sys +import os +from loguru import logger + +def get_logger(output_file): + log_format = "[{time:YYYY-MM-DD HH:mm:ss}] {message}" + logger.configure(handlers=[{"sink": sys.stderr, "format": log_format}]) + while os.path.exists(output_file): + output_file = output_file.replace('.log', '1.log') + if output_file: + logger.add(output_file, enqueue=True, format=log_format) + return logger \ No newline at end of file diff --git a/third_party/utils/utils_correspondence.py b/third_party/utils/utils_correspondence.py new file mode 100644 index 0000000000000000000000000000000000000000..499e9dbd499395cf4c909c8f8d663a6083d32480 --- /dev/null +++ b/third_party/utils/utils_correspondence.py @@ -0,0 +1,665 @@ +import torch +import torch.nn.functional as F +import numpy as np +from PIL import Image +import matplotlib.pyplot as plt +from matplotlib.colors import ListedColormap +from typing import List, Tuple +import faiss +import cv2 +import os +from matplotlib.patches import ConnectionPatch + +def resize(img, target_res, resize=True, to_pil=True, edge=False): + original_width, original_height = img.size + original_channels = len(img.getbands()) + if not edge: + canvas = np.zeros([target_res, target_res, 3], dtype=np.uint8) + if original_channels == 1: + canvas = np.zeros([target_res, target_res], dtype=np.uint8) + if original_height <= original_width: + if resize: + img = img.resize((target_res, int(np.around(target_res * original_height / original_width))), Image.LANCZOS) + width, height = img.size + img = np.asarray(img) + canvas[(width - height) // 2: (width + height) // 2] = img + else: + if resize: + img = img.resize((int(np.around(target_res * original_width / original_height)), target_res), Image.LANCZOS) + width, height = img.size + img = np.asarray(img) + canvas[:, (height - width) // 2: (height + width) // 2] = img + else: + if original_height <= original_width: + if resize: + img = img.resize((target_res, int(np.around(target_res * original_height / original_width))), Image.LANCZOS) + width, height = img.size + img = np.asarray(img) + top_pad = (target_res - height) // 2 + bottom_pad = target_res - height - top_pad + img = np.pad(img, pad_width=[(top_pad, bottom_pad), (0, 0), (0, 0)], mode='edge') + else: + if resize: + img = img.resize((int(np.around(target_res * original_width / original_height)), target_res), Image.LANCZOS) + width, height = img.size + img = np.asarray(img) + left_pad = (target_res - width) // 2 + right_pad = target_res - width - left_pad + img = np.pad(img, pad_width=[(0, 0), (left_pad, right_pad), (0, 0)], mode='edge') + canvas = img + if to_pil: + canvas = Image.fromarray(canvas) + return canvas + + +def find_nearest_patchs(mask1, mask2, image1, image2, features1, features2, mask=False, resolution=None, edit_image=None): + def polar_color_map(image_shape): + h, w = image_shape[:2] + x = np.linspace(-1, 1, w) + y = np.linspace(-1, 1, h) + xx, yy = np.meshgrid(x, y) + + # Find the center of the mask + mask=mask2.cpu() + mask_center = np.array(np.where(mask > 0)) + mask_center = np.round(np.mean(mask_center, axis=1)).astype(int) + mask_center_y, mask_center_x = mask_center + + # Calculate distance and angle based on mask_center + xx_shifted, yy_shifted = xx - x[mask_center_x], yy - y[mask_center_y] + max_radius = np.sqrt(h**2 + w**2) / 2 + radius = np.sqrt(xx_shifted**2 + yy_shifted**2) * max_radius + angle = np.arctan2(yy_shifted, xx_shifted) / (2 * np.pi) + 0.5 + + angle = 0.2 + angle * 0.6 # Map angle to the range [0.25, 0.75] + radius = np.where(radius <= max_radius, radius, max_radius) # Limit radius values to the unit circle + radius = 0.2 + radius * 0.6 / max_radius # Map radius to the range [0.1, 1] + + return angle, radius + + if resolution is not None: # resize the feature map to the resolution + features1 = F.interpolate(features1, size=resolution, mode='bilinear') + features2 = F.interpolate(features2, size=resolution, mode='bilinear') + + # resize the image to the shape of the feature map + resized_image1 = resize(image1, features1.shape[2], resize=True, to_pil=False) + resized_image2 = resize(image2, features2.shape[2], resize=True, to_pil=False) + + if mask: # mask the features + resized_mask1 = F.interpolate(mask1.cuda().unsqueeze(0).unsqueeze(0).float(), size=features1.shape[2:], mode='nearest') + resized_mask2 = F.interpolate(mask2.cuda().unsqueeze(0).unsqueeze(0).float(), size=features2.shape[2:], mode='nearest') + features1 = features1 * resized_mask1.repeat(1, features1.shape[1], 1, 1) + features2 = features2 * resized_mask2.repeat(1, features2.shape[1], 1, 1) + # set where mask==0 a very large number + features1[(features1.sum(1)==0).repeat(1, features1.shape[1], 1, 1)] = 100000 + features2[(features2.sum(1)==0).repeat(1, features2.shape[1], 1, 1)] = 100000 + + features1_2d = features1.reshape(features1.shape[1], -1).permute(1, 0).cpu().detach().numpy() + features2_2d = features2.reshape(features2.shape[1], -1).permute(1, 0).cpu().detach().numpy() + + features1_2d = torch.tensor(features1_2d).to("cuda") + features2_2d = torch.tensor(features2_2d).to("cuda") + resized_image1 = torch.tensor(resized_image1).to("cuda").float() + resized_image2 = torch.tensor(resized_image2).to("cuda").float() + + mask1 = F.interpolate(mask1.cuda().unsqueeze(0).unsqueeze(0).float(), size=resized_image1.shape[:2], mode='nearest').squeeze(0).squeeze(0) + mask2 = F.interpolate(mask2.cuda().unsqueeze(0).unsqueeze(0).float(), size=resized_image2.shape[:2], mode='nearest').squeeze(0).squeeze(0) + + # Mask the images + resized_image1 = resized_image1 * mask1.unsqueeze(-1).repeat(1, 1, 3) + resized_image2 = resized_image2 * mask2.unsqueeze(-1).repeat(1, 1, 3) + # Normalize the images to the range [0, 1] + resized_image1 = (resized_image1 - resized_image1.min()) / (resized_image1.max() - resized_image1.min()) + resized_image2 = (resized_image2 - resized_image2.min()) / (resized_image2.max() - resized_image2.min()) + + angle, radius = polar_color_map(resized_image2.shape) + + angle_mask = angle * mask2.cpu().numpy() + radius_mask = radius * mask2.cpu().numpy() + + hsv_mask = np.zeros(resized_image2.shape, dtype=np.float32) + hsv_mask[:, :, 0] = angle_mask + hsv_mask[:, :, 1] = radius_mask + hsv_mask[:, :, 2] = 1 + + rainbow_mask2 = cv2.cvtColor((hsv_mask * 255).astype(np.uint8), cv2.COLOR_HSV2BGR) / 255 + + if edit_image is not None: + rainbow_mask2 = cv2.imread(edit_image, cv2.IMREAD_COLOR) + rainbow_mask2 = cv2.cvtColor(rainbow_mask2, cv2.COLOR_BGR2RGB) / 255 + rainbow_mask2 = cv2.resize(rainbow_mask2, (resized_image2.shape[1], resized_image2.shape[0])) + + # Apply the rainbow mask to image2 + rainbow_image2 = rainbow_mask2 * mask2.cpu().numpy()[:, :, None] + + # Create a white background image + background_color = np.array([1, 1, 1], dtype=np.float32) + background_image = np.ones(resized_image2.shape, dtype=np.float32) * background_color + + # Apply the rainbow mask to image2 only in the regions where mask2 is 1 + rainbow_image2 = np.where(mask2.cpu().numpy()[:, :, None] == 1, rainbow_mask2, background_image) + + nearest_patches = [] + + distances = torch.cdist(features1_2d, features2_2d) + nearest_patch_indices = torch.argmin(distances, dim=1) + nearest_patches = torch.index_select(torch.tensor(rainbow_mask2).cuda().reshape(-1, 3), 0, nearest_patch_indices) + + nearest_patches_image = nearest_patches.reshape(resized_image1.shape) + rainbow_image2 = torch.tensor(rainbow_image2).to("cuda") + + # TODO: upsample the nearest_patches_image to the resolution of the original image + # nearest_patches_image = F.interpolate(nearest_patches_image.permute(2,0,1).unsqueeze(0), size=256, mode='bilinear').squeeze(0).permute(1,2,0) + # rainbow_image2 = F.interpolate(rainbow_image2.permute(2,0,1).unsqueeze(0), size=256, mode='bilinear').squeeze(0).permute(1,2,0) + + nearest_patches_image = (nearest_patches_image).cpu().numpy() + resized_image2 = (rainbow_image2).cpu().numpy() + + return nearest_patches_image, resized_image2 + + +def find_nearest_patchs_replace(mask1, mask2, image1, image2, features1, features2, mask=False, resolution=128, draw_gif=False, save_path=None, gif_reverse=False): + + if resolution is not None: # resize the feature map to the resolution + features1 = F.interpolate(features1, size=resolution, mode='bilinear') + features2 = F.interpolate(features2, size=resolution, mode='bilinear') + + # resize the image to the shape of the feature map + resized_image1 = resize(image1, features1.shape[2], resize=True, to_pil=False) + resized_image2 = resize(image2, features2.shape[2], resize=True, to_pil=False) + + if mask: # mask the features + resized_mask1 = F.interpolate(mask1.cuda().unsqueeze(0).unsqueeze(0).float(), size=features1.shape[2:], mode='nearest') + resized_mask2 = F.interpolate(mask2.cuda().unsqueeze(0).unsqueeze(0).float(), size=features2.shape[2:], mode='nearest') + features1 = features1 * resized_mask1.repeat(1, features1.shape[1], 1, 1) + features2 = features2 * resized_mask2.repeat(1, features2.shape[1], 1, 1) + # set where mask==0 a very large number + features1[(features1.sum(1)==0).repeat(1, features1.shape[1], 1, 1)] = 100000 + features2[(features2.sum(1)==0).repeat(1, features2.shape[1], 1, 1)] = 100000 + + features1_2d = features1.reshape(features1.shape[1], -1).permute(1, 0) + features2_2d = features2.reshape(features2.shape[1], -1).permute(1, 0) + + resized_image1 = torch.tensor(resized_image1).to("cuda").float() + resized_image2 = torch.tensor(resized_image2).to("cuda").float() + + mask1 = F.interpolate(mask1.cuda().unsqueeze(0).unsqueeze(0).float(), size=resized_image1.shape[:2], mode='nearest').squeeze(0).squeeze(0) + mask2 = F.interpolate(mask2.cuda().unsqueeze(0).unsqueeze(0).float(), size=resized_image2.shape[:2], mode='nearest').squeeze(0).squeeze(0) + + # Mask the images + resized_image1 = resized_image1 * mask1.unsqueeze(-1).repeat(1, 1, 3) + resized_image2 = resized_image2 * mask2.unsqueeze(-1).repeat(1, 1, 3) + # Normalize the images to the range [0, 1] + resized_image1 = (resized_image1 - resized_image1.min()) / (resized_image1.max() - resized_image1.min()) + resized_image2 = (resized_image2 - resized_image2.min()) / (resized_image2.max() - resized_image2.min()) + + distances = torch.cdist(features1_2d, features2_2d) + nearest_patch_indices = torch.argmin(distances, dim=1) + nearest_patches = torch.index_select(resized_image2.cuda().clone().detach().reshape(-1, 3), 0, nearest_patch_indices) + + nearest_patches_image = nearest_patches.reshape(resized_image1.shape) + + if draw_gif: + assert save_path is not None, "save_path must be provided when draw_gif is True" + img_1 = resize(image1, features1.shape[2], resize=True, to_pil=True) + img_2 = resize(image2, features2.shape[2], resize=True, to_pil=True) + mapping = torch.zeros((img_1.size[1], img_1.size[0], 2)) + for i in range(len(nearest_patch_indices)): + mapping[i // img_1.size[0], i % img_1.size[0]] = torch.tensor([nearest_patch_indices[i] // img_2.size[0], nearest_patch_indices[i] % img_2.size[0]]) + animate_image_transfer(img_1, img_2, mapping, save_path) if gif_reverse else animate_image_transfer_reverse(img_1, img_2, mapping, save_path) + + # TODO: upsample the nearest_patches_image to the resolution of the original image + # nearest_patches_image = F.interpolate(nearest_patches_image.permute(2,0,1).unsqueeze(0), size=256, mode='bilinear').squeeze(0).permute(1,2,0) + # resized_image2 = F.interpolate(resized_image2.permute(2,0,1).unsqueeze(0), size=256, mode='bilinear').squeeze(0).permute(1,2,0) + + nearest_patches_image = (nearest_patches_image).cpu().numpy() + resized_image2 = (resized_image2).cpu().numpy() + + return nearest_patches_image, resized_image2 + +def chunk_cosine_sim(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + """ Computes cosine similarity between all possible pairs in two sets of vectors. + Operates on chunks so no large amount of GPU RAM is required. + :param x: an tensor of descriptors of shape Bx1x(t_x)xd' where d' is the dimensionality of the descriptors and t_x + is the number of tokens in x. + :param y: a tensor of descriptors of shape Bx1x(t_y)xd' where d' is the dimensionality of the descriptors and t_y + is the number of tokens in y. + :return: cosine similarity between all descriptors in x and all descriptors in y. Has shape of Bx1x(t_x)x(t_y) """ + result_list = [] + num_token_x = x.shape[2] + for token_idx in range(num_token_x): + token = x[:, :, token_idx, :].unsqueeze(dim=2) # Bx1x1xd' + result_list.append(torch.nn.CosineSimilarity(dim=3)(token, y)) # Bx1xt + return torch.stack(result_list, dim=2) # Bx1x(t_x)x(t_y) + +def pairwise_sim(x: torch.Tensor, y: torch.Tensor, p=2, normalize=False) -> torch.Tensor: + # compute similarity based on euclidean distances + if normalize: + x = torch.nn.functional.normalize(x, dim=-1) + y = torch.nn.functional.normalize(y, dim=-1) + result_list=[] + num_token_x = x.shape[2] + for token_idx in range(num_token_x): + token = x[:, :, token_idx, :].unsqueeze(dim=2) + result_list.append(torch.nn.PairwiseDistance(p=p)(token, y)*(-1)) + return torch.stack(result_list, dim=2) + +def draw_correspondences_gathered(points1: List[Tuple[float, float]], points2: List[Tuple[float, float]], + image1: Image.Image, image2: Image.Image) -> plt.Figure: + """ + draw point correspondences on images. + :param points1: a list of (y, x) coordinates of image1, corresponding to points2. + :param points2: a list of (y, x) coordinates of image2, corresponding to points1. + :param image1: a PIL image. + :param image2: a PIL image. + :return: a figure of images with marked points. + """ + assert len(points1) == len(points2), f"points lengths are incompatible: {len(points1)} != {len(points2)}." + num_points = len(points1) + + if num_points > 15: + cmap = plt.get_cmap('tab10') + else: + cmap = ListedColormap(["red", "yellow", "blue", "lime", "magenta", "indigo", "orange", "cyan", "darkgreen", + "maroon", "black", "white", "chocolate", "gray", "blueviolet"]) + colors = np.array([cmap(x) for x in range(num_points)]) + radius1, radius2 = 0.03*max(image1.size), 0.01*max(image1.size) + + # plot a subfigure put image1 in the top, image2 in the bottom + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8)) + ax1.axis('off') + ax2.axis('off') + ax1.imshow(image1) + ax2.imshow(image2) + + for point1, point2, color in zip(points1, points2, colors): + y1, x1 = point1 + circ1_1 = plt.Circle((x1, y1), radius1, facecolor=color, edgecolor='white', alpha=0.5) + circ1_2 = plt.Circle((x1, y1), radius2, facecolor=color, edgecolor='white') + ax1.add_patch(circ1_1) + ax1.add_patch(circ1_2) + y2, x2 = point2 + circ2_1 = plt.Circle((x2, y2), radius1, facecolor=color, edgecolor='white', alpha=0.5) + circ2_2 = plt.Circle((x2, y2), radius2, facecolor=color, edgecolor='white') + ax2.add_patch(circ2_1) + ax2.add_patch(circ2_2) + + return fig + +def draw_correspondences_lines(points1: List[Tuple[float, float]], points2: List[Tuple[float, float]], + gt_points2: List[Tuple[float, float]], image1: Image.Image, + image2: Image.Image, threshold=None) -> plt.Figure: + """ + draw point correspondences on images. + :param points1: a list of (y, x) coordinates of image1, corresponding to points2. + :param points2: a list of (y, x) coordinates of image2, corresponding to points1. + :param gt_points2: a list of ground truth (y, x) coordinates of image2. + :param image1: a PIL image. + :param image2: a PIL image. + :param threshold: distance threshold to determine correct matches. + :return: a figure of images with marked points and lines between them showing correspondence. + """ + + points2=points2.cpu().numpy() + gt_points2=gt_points2.cpu().numpy() + + def compute_correct(): + alpha = torch.tensor([0.1, 0.05, 0.01]) + correct = torch.zeros(len(alpha)) + err = (torch.tensor(points2) - torch.tensor(gt_points2)).norm(dim=-1) + err = err.unsqueeze(0).repeat(len(alpha), 1) + correct = err < threshold.unsqueeze(-1) if len(threshold.shape)==1 else err < threshold + return correct + + correct = compute_correct()[0] + # print(correct.shape, len(points1)) + + assert len(points1) == len(points2), f"points lengths are incompatible: {len(points1)} != {len(points2)}." + num_points = len(points1) + + if num_points > 15: + cmap = plt.get_cmap('tab10') + else: + cmap = ListedColormap(["red", "yellow", "blue", "lime", "magenta", "indigo", "orange", "cyan", "darkgreen", + "maroon", "black", "white", "chocolate", "gray", "blueviolet"]) + colors = np.array([cmap(x) for x in range(num_points)]) + radius1, radius2 = 0.03*max(image1.size), 0.01*max(image1.size) + + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8)) + ax1.axis('off') + ax2.axis('off') + ax1.imshow(image1) + ax2.imshow(image2) + ax1.set_xlim(0, image1.size[0]) + ax1.set_ylim(image1.size[1], 0) + ax2.set_xlim(0, image2.size[0]) + ax2.set_ylim(image2.size[1], 0) + + for i, (point1, point2) in enumerate(zip(points1, points2)): + y1, x1 = point1 + circ1_1 = plt.Circle((x1, y1), radius1, facecolor=colors[i], edgecolor='white', alpha=0.5) + circ1_2 = plt.Circle((x1, y1), radius2, facecolor=colors[i], edgecolor='white') + ax1.add_patch(circ1_1) + ax1.add_patch(circ1_2) + y2, x2 = point2 + circ2_1 = plt.Circle((x2, y2), radius1, facecolor=colors[i], edgecolor='white', alpha=0.5) + circ2_2 = plt.Circle((x2, y2), radius2, facecolor=colors[i], edgecolor='white') + ax2.add_patch(circ2_1) + ax2.add_patch(circ2_2) + + # Draw lines + color = 'blue' if correct[i].item() else 'red' + con = ConnectionPatch(xyA=(x2, y2), xyB=(x1, y1), coordsA="data", coordsB="data", + axesA=ax2, axesB=ax1, color=color, linewidth=1.5) + ax2.add_artist(con) + + return fig + +def co_pca(features1, features2, dim=[128,128,128]): + processed_features1 = {} + processed_features2 = {} + s5_size = features1['s5'].shape[-1] + s4_size = features1['s4'].shape[-1] + s3_size = features1['s3'].shape[-1] + + # Get the feature tensors + s5_1 = features1['s5'].reshape(features1['s5'].shape[0], features1['s5'].shape[1], -1) + s4_1 = features1['s4'].reshape(features1['s4'].shape[0], features1['s4'].shape[1], -1) + s3_1 = features1['s3'].reshape(features1['s3'].shape[0], features1['s3'].shape[1], -1) + + s5_2 = features2['s5'].reshape(features2['s5'].shape[0], features2['s5'].shape[1], -1) + s4_2 = features2['s4'].reshape(features2['s4'].shape[0], features2['s4'].shape[1], -1) + s3_2 = features2['s3'].reshape(features2['s3'].shape[0], features2['s3'].shape[1], -1) + # Define the target dimensions + target_dims = {'s5': dim[0], 's4': dim[1], 's3': dim[2]} + + # Compute the PCA + for name, tensors in zip(['s5', 's4', 's3'], [[s5_1, s5_2], [s4_1, s4_2], [s3_1, s3_2]]): + target_dim = target_dims[name] + + # Concatenate the features + features = torch.cat(tensors, dim=-1) # along the spatial dimension + features = features.permute(0, 2, 1) # Bx(t_x+t_y)x(d) + + # Compute the PCA + # pca = faiss.PCAMatrix(features.shape[-1], target_dim) + + # Train the PCA + # pca.train(features[0].cpu().numpy()) + + # Apply the PCA + # features = pca.apply(features[0].cpu().numpy()) # (t_x+t_y)x(d) + + # convert to tensor + # features = torch.tensor(features, device=features1['s5'].device).unsqueeze(0).permute(0, 2, 1) # Bx(d)x(t_x+t_y) + + + # equivalent to the above, pytorch implementation + mean = torch.mean(features[0], dim=0, keepdim=True) + centered_features = features[0] - mean + + U, S, V = torch.pca_lowrank(centered_features, q=target_dim) + reduced_features = torch.matmul(centered_features, V[:, :target_dim]) # (t_x+t_y)x(d) + features = reduced_features.unsqueeze(0).permute(0, 2, 1) # Bx(d)x(t_x+t_y) + + # Split the features + processed_features1[name] = features[:, :, :features.shape[-1] // 2] # Bx(d)x(t_x) + processed_features2[name] = features[:, :, features.shape[-1] // 2:] # Bx(d)x(t_y) + + # reshape the features + processed_features1['s5']=processed_features1['s5'].reshape(processed_features1['s5'].shape[0], -1, s5_size, s5_size) + processed_features1['s4']=processed_features1['s4'].reshape(processed_features1['s4'].shape[0], -1, s4_size, s4_size) + processed_features1['s3']=processed_features1['s3'].reshape(processed_features1['s3'].shape[0], -1, s3_size, s3_size) + + processed_features2['s5']=processed_features2['s5'].reshape(processed_features2['s5'].shape[0], -1, s5_size, s5_size) + processed_features2['s4']=processed_features2['s4'].reshape(processed_features2['s4'].shape[0], -1, s4_size, s4_size) + processed_features2['s3']=processed_features2['s3'].reshape(processed_features2['s3'].shape[0], -1, s3_size, s3_size) + + # Upsample s5 spatially by a factor of 2 + processed_features1['s5'] = F.interpolate(processed_features1['s5'], size=(processed_features1['s4'].shape[-2:]), mode='bilinear', align_corners=False) + processed_features2['s5'] = F.interpolate(processed_features2['s5'], size=(processed_features2['s4'].shape[-2:]), mode='bilinear', align_corners=False) + + # Concatenate upsampled_s5 and s4 to create a new s5 + processed_features1['s5'] = torch.cat([processed_features1['s4'], processed_features1['s5']], dim=1) + processed_features2['s5'] = torch.cat([processed_features2['s4'], processed_features2['s5']], dim=1) + + # Set s3 as the new s4 + processed_features1['s4'] = processed_features1['s3'] + processed_features2['s4'] = processed_features2['s3'] + + # Remove s3 from the features dictionary + processed_features1.pop('s3') + processed_features2.pop('s3') + + # current order are layer 8, 5, 2 + features1_gether_s4_s5 = torch.cat([processed_features1['s4'], F.interpolate(processed_features1['s5'], size=(processed_features1['s4'].shape[-2:]), mode='bilinear')], dim=1) + features2_gether_s4_s5 = torch.cat([processed_features2['s4'], F.interpolate(processed_features2['s5'], size=(processed_features2['s4'].shape[-2:]), mode='bilinear')], dim=1) + + return features1_gether_s4_s5, features2_gether_s4_s5 + +def animate_image_transfer(image1, image2, mapping, output_path): + import numpy as np + from PIL import Image + import matplotlib.pyplot as plt + import matplotlib.animation as animation + + # # Load your two images + # image1 = Image.open(image1_path) + # image2 = Image.open(image2_path) + + # Ensure the two images are the same size + assert image1.size == image2.size, "Images must be the same size." + rec_size = 2 + # Convert the images into numpy arrays + image1_array = np.array(image1) + image2_array = np.array(image2) + + # Retrieve the width and height of the images + height, width, _ = image1_array.shape + + # Assume we have a mapping list + mapping = mapping.cpu().numpy() + + # We add a column of white pixels between the two images + gap = width // 10 + + # Create a canvas with a width that is the sum of the widths of the two images and the gap. + # The height is the same as the height of the images. + fig, ax = plt.subplots(figsize=((2 * width + gap) / 200, height / 200), dpi=300) + + # Remove the axes + ax.axis('off') + + # Create an image object, initializing it as entirely white + combined_image = np.ones((height, 2 * width + gap, 3), dtype=np.uint8) * 255 + + # Place image1 on the left, image2 on the right, with a gap in the middle + combined_image[:, :width] = image1_array + combined_image[:, width + gap:] = image2_array + + img_obj = ax.imshow(combined_image) + + # For each frame of the computation and animation, we need to know the start and target positions of each pixel + starts = np.mgrid[:height, :width].reshape(2, -1).T + targets = np.array([mapping[i, j] for i in range(height) for j in range(width)]) + [0, width + gap] + + # To better display the animation, we divide the pixel movement into several frames + num_frames = 30 + + def calculate_path(start, target, num_frames): + """Calculate the path of a pixel from start to target over num_frames.""" + # Generate linear values from 0 to 1 + t = np.linspace(0, 1, num_frames) + + # Apply the quadratic easing out function (starts fast, then slows down) + t = 1 - (1 - t) ** 2 + + # Calculate the path + path = start + t[:, np.newaxis] * (target - start) + + return path + + def update(frame): + # At the start of each frame, we initialize the canvas with image1 on the left, image2 on the right, and white in the middle + combined_image.fill(255) + combined_image[:, :width] = image1_array + combined_image[:, width + gap:] = image2_array + # In each frame, we move a small portion of pixels from the left image to the right image + # This gives a better view of how the pixels move + if frame >= num_frames - 1: + frame = num_frames - 1 + for i in range(height): + for j in range(width): + # Calculate the current pixel's position + start = starts[i * width + j] + target = targets[i * width + j] + # If the mapped target position is greater than 0, move the pixel, otherwise keep it the same + if target[0] > 0 and target[1] > 0: + position = calculate_path(start, target, num_frames)[frame] + # Copy the current pixel's color to the new position + combined_image[int(position[0])-rec_size//2:int(position[0])-rec_size//2+rec_size, int(position[1])-rec_size//2:int(position[1])-rec_size//2+rec_size] = image1_array[i, j] + img_obj.set_array(combined_image) # Update the displayed image + return img_obj, + + # Create the animation + ani = animation.FuncAnimation(fig, update, frames=num_frames + 30, blit=True) + if not os.path.exists(os.path.dirname(output_path)): + os.makedirs(os.path.dirname(output_path)) + # Save the animation + ani.save(output_path, writer='pillow', fps=30) + # save mapping + np.save(output_path[:-4]+'.npy', mapping) + + +def animate_image_transfer_reverse(image1, image2, mapping, output_path): + import numpy as np + from PIL import Image + import matplotlib.pyplot as plt + import matplotlib.animation as animation + + # # Load your two images + # image1 = Image.open(image1_path) + # image2 = Image.open(image2_path) + + # Ensure the two images are the same size + assert image1.size == image2.size, "Images must be the same size." + # rec_size = 2 + # Convert the images into numpy arrays + image1_array = np.array(image1) + image2_array = np.array(image2) + + # Retrieve the width and height of the images + height, width, _ = image1_array.shape + + # Assume we have a mapping list + mapping = mapping.cpu().numpy() + + # We add a column of white pixels between the two images + gap = width // 10 + + # Create a canvas with a width that is the sum of the widths of the two images and the gap. + # The height is the same as the height of the images. + fig, ax = plt.subplots(figsize=((2 * width + gap) / 200, height / 200), dpi=300) + + # Remove the axes + ax.axis('off') + + # Create an image object, initializing it as entirely white + combined_image = np.ones((height, 2 * width + gap, 3), dtype=np.uint8) * 255 + + # Place image1 on the left, image2 on the right, with a gap in the middle + combined_image[:, :width] = image2_array + combined_image[:, width + gap:] = image1_array + + img_obj = ax.imshow(combined_image) + + # For each frame of the computation and animation, we need to know the start and target positions of each pixel + starts = np.mgrid[:height, :width].reshape(2, -1).T + [0, width + gap] + targets = np.array([mapping[i, j] for i in range(height) for j in range(width)]) + + # To better display the animation, we divide the pixel movement into several frames + num_frames = 30 + + def calculate_path(start, target, num_frames): + """Calculate the path of a pixel from start to target over num_frames.""" + # Generate linear values from 0 to 1 + t = np.linspace(1, 0, num_frames) + + # Apply the quadratic easing out function (starts fast, then slows down) + t = 1 - (1 - t) ** 2 + + # Calculate the path + path = start + t[:, np.newaxis] * (target - start) + + return path + + def update(frame): + # At the start of each frame, we initialize the canvas with image1 on the left, image2 on the right, and white in the middle + combined_image.fill(255) + combined_image[:, :width] = image2_array + combined_image[:, width + gap:] = image1_array + # In each frame, we move a small portion of pixels from the left image to the right image + # This gives a better view of how the pixels move + if frame >= num_frames - 1: + frame = num_frames - 1 + if frame >= num_frames // 6 * 5: + rec_size = 1 + else: + rec_size = 2 + for i in range(height): + for j in range(width): + # Calculate the current pixel's position + start = starts[i * width + j] + target = targets[i * width + j] + # If the mapped target position is greater than 0, move the pixel, otherwise keep it the same + if target[0] > 0 and target[1] > 0: + position = calculate_path(start, target, num_frames)[frame] + # Copy the current pixel's color to the new position + combined_image[int(position[0])-rec_size//2:int(position[0])-rec_size//2+rec_size, int(position[1])-rec_size//2:int(position[1])-rec_size//2+rec_size] = image2_array[int(mapping[i, j][0]), int(mapping[i, j][1])] + img_obj.set_array(combined_image) # Update the displayed image + return img_obj, + + # Create the animation + ani = animation.FuncAnimation(fig, update, frames=num_frames + 30, blit=True) + if not os.path.exists(os.path.dirname(output_path)): + os.makedirs(os.path.dirname(output_path)) + # Save the animation + ani.save(output_path, writer='pillow', fps=30) + # save the maping + np.save(output_path[:-4]+'.npy', mapping) + + + + +def pca_reduce_features(features: torch.Tensor, target_dim: int) -> torch.Tensor: + """ + 对输入特征做mean-center和PCA降维,自动处理float16到float32兼容。 + + Args: + features: [bs, c, h, w] 的输入特征 + target_dim: 降维后的特征数 + + Returns: + [bs, target_dim, h, w] 的PCA降维特征 + """ + orig_dtype = features.dtype + if features.dtype != torch.float32: + features = features.float() # 转为float32 + + bs, c, h, w = features.shape + reduced_list = [] + for i in range(bs): + # [c, h, w] -> [h*w, c] + single = features[i].reshape(c, h * w).transpose(0, 1) + mean = single.mean(dim=0, keepdim=True) + centered = single - mean + U, S, V = torch.pca_lowrank(centered, q=target_dim) + reduced = torch.matmul(centered, V[:, :target_dim]) # [h*w, target_dim] + reduced = reduced.transpose(0, 1).reshape(target_dim, h, w) # [target_dim, h, w] + reduced_list.append(reduced) + reduced_features = torch.stack(reduced_list, dim=0) # [bs, target_dim, h, w] + + # 如果输入是fp16则转回 + if orig_dtype != torch.float32: + reduced_features = reduced_features.to(orig_dtype) + return reduced_features \ No newline at end of file diff --git a/third_party/utils/utils_flow.py b/third_party/utils/utils_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..8b69f6aafaaab4c3ffb4dab3066331d20f531424 --- /dev/null +++ b/third_party/utils/utils_flow.py @@ -0,0 +1,622 @@ +import numpy as np +import cv2 +from functools import wraps +from matplotlib import pyplot as plt +import torch + +MAX_VALUES_BY_DTYPE = { + np.dtype('uint8'): 255, + np.dtype('uint16'): 65535, + np.dtype('uint32'): 4294967295, + np.dtype('float32'): 1.0, +} + + + +UNKNOWN_FLOW_THRESH = 1e7 +SMALLFLOW = 0.0 +LARGEFLOW = 1e8 + + +def flow2rgb(flow_map, max_value): + if isinstance(flow_map,np.ndarray): + if flow_map.shape[2] == 2: + flow_map = flow_map.transpose(2,0, 1) + flow_map_np = flow_map + else: + if flow_map.shape[2] == 2: + # shape is HxWx2 + flow_map = flow_map.permute(2, 0, 1) + flow_map_np = flow_map.detach().cpu().numpy() + _, h, w = flow_map_np.shape + flow_map_np[:,(flow_map_np[0] == 0) & (flow_map_np[1] == 0)] = float('nan') + rgb_map = np.ones((3,h,w)).astype(np.float32) + if max_value is not None: + normalized_flow_map = flow_map_np / max_value + else: + normalized_flow_map = flow_map_np / (np.abs(flow_map_np).max()) + rgb_map[0] += normalized_flow_map[0] + rgb_map[1] -= 0.5*(normalized_flow_map[0] + normalized_flow_map[1]) + rgb_map[2] += normalized_flow_map[1] + return rgb_map.clip(0,1) + + +def flow_to_image(flow, maxrad=None): + """ + Convert flow into middlebury color code image + :param flow: optical flow map + :return: optical flow image in middlebury color + """ + h,w, _ = flow.shape + u = flow[:, :, 0] + v = flow[:, :, 1] + + maxu = -999. + maxv = -999. + minu = 999. + minv = 999. + + idxUnknow = (abs(u) > UNKNOWN_FLOW_THRESH) | (abs(v) > UNKNOWN_FLOW_THRESH) + u[idxUnknow] = 0 + v[idxUnknow] = 0 + + if maxrad is None: + rad = np.sqrt(u ** 2 + v ** 2) + maxrad = max(-1, np.max(rad)) + + #print("max flow: %.4f\nflow range:\nu = %.3f .. %.3f\nv = %.3f .. %.3f" % (maxrad, minu,maxu, minv, maxv)) + + u = u/(maxrad + np.finfo(float).eps) + v = v/(maxrad + np.finfo(float).eps) + + img = compute_color(u, v) + + idx = np.repeat(idxUnknow[:, :, np.newaxis], 3, axis=2) + img[idx] = 0 + valid = np.ones((h,w), np.uint8) + valid[np.logical_and(u == 0 , v == 0)] = 0 + return np.uint8(img)*np.expand_dims(valid, axis=2) + + +def show_flow(flow): + """ + visualize optical flow map using matplotlib + :param filename: optical flow file + :return: None + """ + img = flow_to_image(flow) + plt.imshow(img) + plt.show() + + +def visualize_flow(flow, mode='Y'): + """ + this function visualize the input flow + :param flow: input flow in array + :param mode: choose which color mode to visualize the flow (Y: Ccbcr, RGB: RGB color) + :return: None + """ + if mode == 'Y': + # Ccbcr color wheel + img = flow_to_image(flow) + plt.imshow(img) + plt.show() + elif mode == 'RGB': + (h, w) = flow.shape[0:2] + du = flow[:, :, 0] + dv = flow[:, :, 1] + valid = flow[:, :, 2] + max_flow = max(np.max(du), np.max(dv)) + img = np.zeros((h, w, 3), dtype=np.float64) + # angle layer + img[:, :, 0] = np.arctan2(dv, du) / (2 * np.pi) + # magnitude layer, normalized to 1 + img[:, :, 1] = np.sqrt(du * du + dv * dv) * 8 / max_flow + # phase layer + img[:, :, 2] = 8 - img[:, :, 1] + # clip to [0,1] + small_idx = img[:, :, 0:3] < 0 + large_idx = img[:, :, 0:3] > 1 + img[small_idx] = 0 + img[large_idx] = 1 + # convert to rgb + img = cl.hsv_to_rgb(img) + # remove invalid point + img[:, :, 0] = img[:, :, 0] * valid + img[:, :, 1] = img[:, :, 1] * valid + img[:, :, 2] = img[:, :, 2] * valid + # show + plt.imshow(img) + plt.show() + + +def compute_color(u, v): + """ + compute optical flow color map + :param u: optical flow horizontal map + :param v: optical flow vertical map + :return: optical flow in color code + """ + [h, w] = u.shape + img = np.zeros([h, w, 3]) + nanIdx = np.isnan(u) | np.isnan(v) + u[nanIdx] = 0 + v[nanIdx] = 0 + + colorwheel = make_color_wheel() + ncols = np.size(colorwheel, 0) + + rad = np.sqrt(u**2+v**2) + + a = np.arctan2(-v, -u) / np.pi + + fk = (a+1) / 2 * (ncols - 1) + 1 + + k0 = np.floor(fk).astype(int) + + k1 = k0 + 1 + k1[k1 == ncols+1] = 1 + f = fk - k0 + + for i in range(0, np.size(colorwheel,1)): + tmp = colorwheel[:, i] + col0 = tmp[k0-1] / 255 + col1 = tmp[k1-1] / 255 + col = (1-f) * col0 + f * col1 + + idx = rad <= 1 + col[idx] = 1-rad[idx]*(1-col[idx]) + notidx = np.logical_not(idx) + + col[notidx] *= 0.75 + img[:, :, i] = np.uint8(np.floor(255 * col*(1-nanIdx))) + + return img + + +def make_color_wheel(): + """ + Generate color wheel according Middlebury color code + :return: Color wheel + """ + RY = 15 + YG = 6 + GC = 4 + CB = 11 + BM = 13 + MR = 6 + + ncols = RY + YG + GC + CB + BM + MR + + colorwheel = np.zeros([ncols, 3]) + + col = 0 + + # RY + colorwheel[0:RY, 0] = 255 + colorwheel[0:RY, 1] = np.transpose(np.floor(255*np.arange(0, RY) / RY)) + col += RY + + # YG + colorwheel[col:col+YG, 0] = 255 - np.transpose(np.floor(255*np.arange(0, YG) / YG)) + colorwheel[col:col+YG, 1] = 255 + col += YG + + # GC + colorwheel[col:col+GC, 1] = 255 + colorwheel[col:col+GC, 2] = np.transpose(np.floor(255*np.arange(0, GC) / GC)) + col += GC + + # CB + colorwheel[col:col+CB, 1] = 255 - np.transpose(np.floor(255*np.arange(0, CB) / CB)) + colorwheel[col:col+CB, 2] = 255 + col += CB + + # BM + colorwheel[col:col+BM, 2] = 255 + colorwheel[col:col+BM, 0] = np.transpose(np.floor(255*np.arange(0, BM) / BM)) + col += + BM + + # MR + colorwheel[col:col+MR, 2] = 255 - np.transpose(np.floor(255 * np.arange(0, MR) / MR)) + colorwheel[col:col+MR, 0] = 255 + + return colorwheel + + +def show_flow(disp_x, disp_y): + norm_flow=np.sqrt(np.power(disp_x,2) + np.power(disp_y,2) ) + return norm_flow + + +def diff_neighboring_OF(disp_x, disp_y): + diff=np.zeros((disp_x.shape[0], disp_x.shape[1],5), dtype=np.float32) + print(disp_x.shape[0]) + for y in range(2, disp_x.shape[0]-2): + for x in range(2, disp_x.shape[1]-2): + diff[y, x, 0] = np.sqrt((disp_x[y, x] - disp_x[y+1, x])**2 + (disp_y[y,x]-disp_y[y+1, x])**2) + diff[y, x, 1] = np.sqrt((disp_x[y, x] - disp_x[y - 1, x]) ** 2 + (disp_y[y, x] - disp_y[y - 1, x]) ** 2 ) + diff[y, x, 2] = np.sqrt((disp_x[y, x] - disp_x[y, x+1]) ** 2 + (disp_y[y, x] - disp_y[y, x+1]) ** 2 ) + diff[y, x, 3] = np.sqrt((disp_x[y, x] - disp_x[y, x-1]) ** 2 + (disp_y[y, x] - disp_y[y, x-1]) ** 2 ) + diff[y,x,4]=1/4*(diff[y, x, 1]+diff[y, x, 2]+diff[y, x, 3]+diff[y, x, 0]) + return diff + + +def preserve_shape(func): + """Preserve shape of the image.""" + @wraps(func) + def wrapped_function(img, *args, **kwargs): + shape = img.shape + result = func(img, *args, **kwargs) + result = result.reshape(shape) + return result + + return wrapped_function + + +def preserve_channel_dim(func): + """Preserve dummy channel dim.""" + @wraps(func) + def wrapped_function(img, *args, **kwargs): + shape = img.shape + result = func(img, *args, **kwargs) + if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2: + result = np.expand_dims(result, axis=-1) + return result + + return wrapped_function + + +def center_crop(img, size): + """ + Get the center crop of the input image + Args: + img: input image [BxCxHxW] + size: size of the center crop (tuple) + Output: + img_pad: center crop + x, y: coordinates of the crop + """ + + if not isinstance(size, tuple): + size = (size, size) + + img = img.copy() + #w, h = img.shape[1::-1] + w, h=img.shape[:2] + + pad_w = 0 + pad_h = 0 + if w < size[0]: + pad_w = np.uint16((size[0] - w) / 2) + if h < size[1]: + pad_h = np.uint16((size[1] - h) / 2) + img_pad = cv2.copyMakeBorder(img, + pad_h, + pad_h, + pad_w, + pad_w, + cv2.BORDER_CONSTANT, + value=[0, 0, 0]) + w, h = img_pad.shape[1::-1] + + x1 = w // 2 - size[0] // 2 + y1 = h // 2 - size[1] // 2 + + img_pad = img_pad[y1:y1 + size[1], x1:x1 + size[0], :] + + return img_pad, x1, y1 + + +def crop_images_and_rescale_OF(I, I_prime, map_x, map_y, size): + I_cropped, x1, y1=center_crop(I, size) + I_prime_cropped, x1, y1=center_crop(I_prime, size) + + map_x=map_x-x1 # warped image starts at a new index x1 in horizontal direction + map_y=map_y-y1 + map_x_modified=map_x[y1:y1 + size[1], x1:x1 + size[0]] + map_y_modified = map_y[y1:y1 + size[1], x1:x1 + size[0]] + return I_cropped, I_prime_cropped, map_x_modified, map_y_modified + + +@preserve_channel_dim +def pad(img, min_height, min_width, border_mode=cv2.BORDER_REFLECT_101, value=None): + height, width = img.shape[:2] + + if height < min_height: + h_pad_top = int((min_height - height) / 2.0) + h_pad_bottom = min_height - height - h_pad_top + else: + h_pad_top = 0 + h_pad_bottom = 0 + + if width < min_width: + w_pad_left = int((min_width - width) / 2.0) + w_pad_right = min_width - width - w_pad_left + else: + w_pad_left = 0 + w_pad_right = 0 + + img = pad_with_params(img, h_pad_top, h_pad_bottom, w_pad_left, w_pad_right, border_mode, value) + + assert img.shape[0] == max(min_height, height) + assert img.shape[1] == max(min_width, width) + + return img + + +@preserve_channel_dim +def pad_with_params(img, h_pad_top, h_pad_bottom, w_pad_left, w_pad_right, border_mode=cv2.BORDER_REFLECT_101, + value=None): + img = cv2.copyMakeBorder(img, h_pad_top, h_pad_bottom, w_pad_left, w_pad_right, border_mode, value=value) + return img + + +def crop(img, x_min, y_min, x_max, y_max): + height, width = img.shape[:2] + if x_max <= x_min or y_max <= y_min: + raise ValueError( + 'We should have x_min < x_max and y_min < y_max. But we got' + ' (x_min = {x_min}, y_min = {y_min}, x_max = {x_max}, y_max = {y_max})'.format( + x_min=x_min, + x_max=x_max, + y_min=y_min, + y_max=y_max + ) + ) + + if x_min < 0 or x_max > width or y_min < 0 or y_max > height: + raise ValueError( + 'Values for crop should be non negative and equal or smaller than image sizes' + '(x_min = {x_min}, y_min = {y_min}, x_max = {x_max}, y_max = {y_max}' + 'height = {height}, width = {width})'.format( + x_min=x_min, + x_max=x_max, + y_min=y_min, + y_max=y_max, + height=height, + width=width + ) + ) + + return img[y_min:y_max, x_min:x_max] + + +def get_center_crop_coords(height, width, crop_height, crop_width): + y1 = (height - crop_height) // 2 + y2 = y1 + crop_height + x1 = (width - crop_width) // 2 + x2 = x1 + crop_width + return x1, y1, x2, y2 + + +def center_crop(img, crop_height, crop_width): + height, width = img.shape[:2] + if height < crop_height or width < crop_width: + raise ValueError( + 'Requested crop size ({crop_height}, {crop_width}) is ' + 'larger than the image size ({height}, {width})'.format( + crop_height=crop_height, + crop_width=crop_width, + height=height, + width=width, + ) + ) + x1, y1, x2, y2 = get_center_crop_coords(height, width, crop_height, crop_width) + img = img[y1:y2, x1:x2] + return img + + +def get_random_crop_coords(height, width, crop_height, crop_width, h_start, w_start): + y1 = int((height - crop_height) * h_start) + y2 = y1 + crop_height + x1 = int((width - crop_width) * w_start) + x2 = x1 + crop_width + return x1, y1, x2, y2 + + +def random_crop(img, crop_height, crop_width, h_start, w_start): + height, width = img.shape[:2] + if height < crop_height or width < crop_width: + raise ValueError( + 'Requested crop size ({crop_height}, {crop_width}) is ' + 'larger than the image size ({height}, {width})'.format( + crop_height=crop_height, + crop_width=crop_width, + height=height, + width=width, + ) + ) + x1, y1, x2, y2 = get_random_crop_coords(height, width, crop_height, crop_width, h_start, w_start) + img = img[y1:y2, x1:x2] + return img + + +def clamping_crop(img, x_min, y_min, x_max, y_max): + h, w = img.shape[:2] + if x_min < 0: + x_min = 0 + if y_min < 0: + y_min = 0 + if y_max >= h: + y_max = h - 1 + if x_max >= w: + x_max = w - 1 + return img[int(y_min):int(y_max), int(x_min):int(x_max)] + + +def convert_flow_to_mapping(flow, output_channel_first=True): + if not isinstance(flow, np.ndarray): + # torch tensor + if len(flow.shape) == 4: + if flow.shape[1] != 2: + # size is BxHxWx2 + flow = flow.permute(0, 3, 1, 2) + + B, C, H, W = flow.size() + + xx = torch.arange(0, W).view(1, -1).repeat(H, 1) + yy = torch.arange(0, H).view(-1, 1).repeat(1, W) + xx = xx.view(1, 1, H, W).repeat(B, 1, 1, 1) + yy = yy.view(1, 1, H, W).repeat(B, 1, 1, 1) + grid = torch.cat((xx, yy), 1).float() + + if flow.is_cuda: + grid = grid.cuda() + mapping = flow + grid # here also channel first + if not output_channel_first: + mapping = mapping.permute(0,2,3,1) + else: + if flow.shape[0] != 2: + # size is HxWx2 + flow = flow.permute(2, 0, 1) + + C, H, W = flow.size() + + xx = torch.arange(0, W).view(1, -1).repeat(H, 1) + yy = torch.arange(0, H).view(-1, 1).repeat(1, W) + xx = xx.view(1, H, W) + yy = yy.view(1, H, W) + grid = torch.cat((xx, yy), 0).float() # attention, concat axis=0 here + + if flow.is_cuda: + grid = grid.cuda() + mapping = flow + grid # here also channel first + if not output_channel_first: + mapping = mapping.permute(1,2,0).float() + return mapping.float() + else: + # here numpy arrays + if len(flow.shape) == 4: + if flow.shape[3] != 2: + # size is Bx2xHxW + flow = flow.transpose(0, 2, 3, 1) + # BxHxWx2 + b, h_scale, w_scale = flow.shape[:3] + mapping = np.copy(flow) + X, Y = np.meshgrid(np.linspace(0, w_scale - 1, w_scale), + np.linspace(0, h_scale - 1, h_scale)) + for i in range(b): + mapping[i, :, :, 0] = flow[i, :, :, 0] + X + mapping[i, :, :, 1] = flow[i, :, :, 1] + Y + if output_channel_first: + mapping = mapping.transpose(0,3,1,2) + else: + if flow.shape[0] == 2: + # size is 2xHxW + flow = flow.transpose(1,2,0) + # HxWx2 + h_scale, w_scale = flow.shape[:2] + mapping = np.copy(flow) + X, Y = np.meshgrid(np.linspace(0, w_scale - 1, w_scale), + np.linspace(0, h_scale - 1, h_scale)) + + mapping[:, :, 0] = flow[:, :, 0] + X + mapping[:, :, 1] = flow[:, :, 1] + Y + if output_channel_first: + mapping = mapping.transpose(2, 0, 1) + return mapping.astype(np.float32) + +def remap_using_flow_fields(image, disp_x, disp_y, interpolation=cv2.INTER_LINEAR, + border_mode=cv2.BORDER_CONSTANT): + """ + Opencv remap + map_x contains the index of the matching horizontal position of each pixel [i,j] while map_y contains the + index of the matching vertical position of each pixel [i,j] + + All arrays are numpy + args: + image: image to remap, HxWxC + disp_x: displacement in the horizontal direction to apply to each pixel. must be float32. HxW + disp_y: displacement in the vertical direction to apply to each pixel. must be float32. HxW + interpolation + border_mode + output: + remapped image. HxWxC + """ + h_scale, w_scale=disp_x.shape[:2] + + # estimate the grid + X, Y = np.meshgrid(np.linspace(0, w_scale - 1, w_scale), + np.linspace(0, h_scale - 1, h_scale)) + map_x = (X+disp_x).astype(np.float32) + map_y = (Y+disp_y).astype(np.float32) + remapped_image = cv2.remap(image, map_x, map_y, interpolation=interpolation, borderMode=border_mode) + + return remapped_image + + +def _pascal_color_map(N=256, normalized=False): + """ + Python implementation of the color map function for the PASCAL VOC data set. + Official Matlab version can be found in the PASCAL VOC devkit + http://host.robots.ox.ac.uk/pascal/VOC/voc2012/index.html#devkit + """ + + def bitget(byteval, idx): + return (byteval & (1 << idx)) != 0 + + dtype = 'float32' if normalized else 'uint8' + cmap = np.zeros((N, 3), dtype=dtype) + for i in range(N): + r = g = b = 0 + c = i + for j in range(8): + r = r | (bitget(c, 0) << 7 - j) + g = g | (bitget(c, 1) << 7 - j) + b = b | (bitget(c, 2) << 7 - j) + c = c >> 3 + + cmap[i] = np.array([r, g, b]) + + cmap = cmap / 255 if normalized else cmap + return cmap + + +def overlay_with_colored_mask(im, mask, alpha=0.5): + fg = im * alpha + (1 - alpha) * mask + return fg + + +def overlay_semantic_mask(im, ann, alpha=0.5, mask=None, colors=None, color=[255, 218, 185], contour_thickness=1): + """ + example usage: + image_overlaid = overlay_semantic_mask(im.astype(np.uint8), 255 - mask.astype(np.uint8) * 255, color=[255, 102, 51]) + """ + im, ann = np.asarray(im, dtype=np.uint8), np.asarray(ann, dtype=int) + if im.shape[:-1] != ann.shape: + raise ValueError('First two dimensions of `im` and `ann` must match') + if im.shape[-1] != 3: + raise ValueError('im must have three channels at the 3 dimension') + + colors = colors or _pascal_color_map() + colors = np.asarray(colors, dtype=np.uint8) + colors[-1, :] = color + + if mask is None: + mask = colors[ann] + + fg = im * alpha + (1 - alpha) * mask + + img = im.copy() + img[ann > 0] = fg[ann > 0] # where the mask is zero (where object is), shoudlnt be any color + + if contour_thickness: # pragma: no cover + import cv2 + for obj_id in np.unique(ann[ann > 0]): + contours = cv2.findContours((ann == obj_id).astype( + np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:] + cv2.drawContours(img, contours[0], -1, color, + contour_thickness) + return img + + +def replace_area(im, ann, replace, alpha=0.5, color=None, thickness=1): + img_warped_overlay_on_target = np.copy(replace) + img_warped_overlay_on_target[ann > 0] = im[ann > 0] + for obj_id in np.unique(ann[ann > 0]): + contours = cv2.findContours((ann == obj_id).astype( + np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:] + cv2.drawContours(img_warped_overlay_on_target, contours[0], -1, color, + thickness) + return img_warped_overlay_on_target \ No newline at end of file diff --git a/third_party/utils/utils_tss.py b/third_party/utils/utils_tss.py new file mode 100644 index 0000000000000000000000000000000000000000..b08789f720853b4d7ab2fcf8d00269bcdb88f89b --- /dev/null +++ b/third_party/utils/utils_tss.py @@ -0,0 +1,213 @@ +from __future__ import division +import os.path +import numpy as np +import torch.utils.data as data +import cv2 +from packaging import version +import torch + +def load_flo(path): + with open(path, 'rb') as f: + magic = np.fromfile(f, np.float32, count=1) + assert(202021.25 == magic),'Magic number incorrect. Invalid .flo file' + w = np.fromfile(f, np.int32, count=1)[0] + h = np.fromfile(f, np.int32, count=1)[0] + data = np.fromfile(f, np.float32, count=2*w*h) + + # Reshape data into 3D array (columns, rows, bands) + data2D = np.resize(data, (h, w, 2)) + return data2D + + +def pad_to_same_shape(im1, im2, flow, mask): + # pad to same shape + if len(im1.shape) == 2: + im1 = np.dstack([im1,im1,im1]) + + if len(im2.shape) == 2: + im2 = np.dstack([im2,im2,im2]) + + if im1.shape[0] <= im2.shape[0]: + pad_y_1 = im2.shape[0] - im1.shape[0] + pad_y_2 = 0 + else: + pad_y_1 = 0 + pad_y_2 = im1.shape[0] - im2.shape[0] + if im1.shape[1] <= im2.shape[1]: + pad_x_1 = im2.shape[1] - im1.shape[1] + pad_x_2 = 0 + else: + pad_x_1 = 0 + pad_x_2 = im1.shape[1] - im2.shape[1] + + # images are padded to the right and bottom so it does not change values of the flow estimated. + im1 = cv2.copyMakeBorder(im1, 0, pad_y_1, 0, pad_x_1, cv2.BORDER_CONSTANT) + im2 = cv2.copyMakeBorder(im2, 0, pad_y_2, 0, pad_x_2, cv2.BORDER_CONSTANT) + # value so that they are not represented when plottung gt (value of 0 would + # represent them), nan when interpolating is not good + flow = cv2.copyMakeBorder(flow, 0, pad_y_2, 0, pad_x_2, cv2.BORDER_REPLICATE) + mask = cv2.copyMakeBorder(mask, 0, pad_y_2, 0, pad_x_2, cv2.BORDER_CONSTANT) + return im1, im2, flow, mask + + +def make_dataset(dir): + """For TSS""" + images = [] + dir_list = [f for f in os.listdir(os.path.join(dir)) if + os.path.isdir(os.path.join(dir, f))] + for image_dir in sorted(dir_list): + # print(image_dir) + if image_dir in ['FG3DCar', 'JODS', 'PASCAL']: + folders_list = [f for f in os.listdir(os.path.join(dir, image_dir)) if + os.path.isdir(os.path.join(dir, image_dir, f))] + for folders in sorted(folders_list): + img_dir = os.path.join(image_dir, folders) + cat = None + if 'Car' in img_dir: + cat = 'car' + else: + cat = folders.split('_')[0].lower() + cat_match_dict={ + 'busd': 'bus', + 'bike': 'bicycle', + 'plane': 'aeroplane', + 'suv': 'car', + } + if cat in cat_match_dict.keys(): + cat = cat_match_dict[cat] + # the flow is taken both ways ! + img1 = os.path.join(img_dir, 'image1.png') + img2 = os.path.join(img_dir, 'image2.png') + flow_map = os.path.join(img_dir, 'flow2.flo') + images.append([[img1, img2], flow_map, cat]) + + img1 = os.path.join(img_dir, 'image2.png') + img2 = os.path.join(img_dir, 'image1.png') # target + flow_map = os.path.join(img_dir, 'flow1.flo') + images.append([[img1, img2], flow_map, cat]) + else: + if 'Car' in dir: + cat = 'car' + else: + cat = image_dir.split('_')[0].lower() + if cat in ['busd', 'bike', 'plane', 'suv']: + cat_match_dict = { + 'busd': 'bus', + 'bike': 'bicycle', + 'plane': 'aeroplane', + 'suv': 'car', + } + cat = cat_match_dict[cat] + img_dir = image_dir + # the flow is taken both ways + img1 = os.path.join(img_dir, 'image1.png') # path to image_1 + img2 = os.path.join(img_dir, 'image2.png') # path to image_3, they say image 10 is the reference + flow_map = os.path.join(img_dir, 'flow2.flo') + images.append([[img1, img2], flow_map, cat]) + + img1 = os.path.join(img_dir, 'image2.png') + img2 = os.path.join(img_dir, 'image1.png') + flow_map = os.path.join(img_dir, 'flow1.flo') + images.append([[img1, img2], flow_map, cat]) + + return images + + +def flow_loader(root, path_imgs, path_flo): + imgs = [os.path.join(root, path) for path in path_imgs] + + flo = os.path.join(root, path_flo) + flow = load_flo(flo) + base_path = os.path.dirname(path_flo) + image_number = path_flo[-5] # getting the mask number, either 1 or 2 depending which image is the target ! + path_mask = os.path.join(root, base_path, 'mask{}.png'.format(image_number)) + mask = cv2.imread(path_mask, 0)/255 # before it was 255, we want mask in range 0,1 + images = [cv2.imread(img)[:,:,::-1].astype(np.uint8) for img in imgs] + source_size = images[0].shape # threshold is max size of source image for pck + im1, im2, flow, mask = pad_to_same_shape(images[0], images[1], flow, mask) + return [im1, im2], flow, mask.astype(np.uint8), source_size + + +def flow_loader_with_paths(root, path_imgs, path_flo): + imgs = [os.path.join(root, path) for path in path_imgs] + + flo = os.path.join(root, path_flo) + flow = load_flo(flo) + base_path = os.path.dirname(path_flo) + image_number = path_flo[-5] # getting the mask number, either 1 or 2 depending which image is the target ! + path_mask = os.path.join(root, base_path, 'mask{}.png'.format(image_number)) + mask = cv2.imread(path_mask, 0)/255 # before it was 255, we want mask in range 0,1 + images = [cv2.imread(img)[:, :, ::-1].astype(np.uint8) for img in imgs] + source_size = images[0].shape # threshold is max size of source image for pck + target_size = images[1].shape + im1, im2, flow, mask = pad_to_same_shape(images[0], images[1], flow, mask) + return [im1, im2], flow, mask.astype(np.uint8), source_size, target_size, path_flo + + +class TSSDataset(data.Dataset): + """TSS dataset. Builds the dataset of TSS image pairs and corresponding ground-truth flow fields.""" + def __init__(self, root, source_image_transform=None, target_image_transform=None, flow_transform=None, + co_transform=None, num_samples=None): + """ + Args: + root: path to root folder + source_image_transform: image transformations to apply to source images + target_image_transform: image transformations to apply to target images + flow_transform: flow transformations to apply to ground-truth flow fields + co_transform: transformations to apply to both images and ground-truth flow fields + split: split (float) between training and testing, 0 means all pairs are in test_dataset + Output in __getittem__: + source_image + target_image + flow_map + correspondence_mask: valid correspondences (only on foreground objects here) + source_image_size + target_image_size + """ + test_list = make_dataset(root) + self.root = root + if num_samples is not None: + test_list = test_list[:num_samples] + self.path_list = test_list + self.first_image_transform = source_image_transform + self.second_image_transform = target_image_transform + self.target_transform = flow_transform + self.co_transform = co_transform + self.loader = flow_loader + + def __getitem__(self, index): + """ + Args: + index: + + Returns: Dictionary with fieldnames: + source_image + target_image + flow_map + correspondence_mask: valid correspondences (only on foreground objects here) + source_image_size + target_image_size + """ + inputs, target, cat = self.path_list[index] + inputs, target, mask, source_size, target_size, path_flo = flow_loader_with_paths(self.root, inputs, target) + + if self.first_image_transform is not None: + inputs[0] = self.first_image_transform(inputs[0]) + if self.second_image_transform is not None: + inputs[1] = self.second_image_transform(inputs[1]) + if self.target_transform is not None: + target = self.target_transform(target) + L_pck = float(max(source_size)) + return {'source_image': inputs[0], + 'target_image': inputs[1], + 'flow_map': target, + 'correspondence_mask': mask.astype(np.bool_) if version.parse(torch.__version__) >= version.parse("1.1") + else mask.astype(np.uint8), + 'source_image_size': np.array(source_size), + 'target_image_size': np.array(target_size), + 'pckthres': L_pck, + 'category': cat + } + + def __len__(self): + return len(self.path_list) \ No newline at end of file diff --git a/tools/__init__.py b/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tools/generate_embedding_39m.sh b/tools/generate_embedding_39m.sh new file mode 100644 index 0000000000000000000000000000000000000000..414f1011834d31f5f8c2c094592f92aef479814c --- /dev/null +++ b/tools/generate_embedding_39m.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +# Generate text embeddings for TinyCLIP-ViT-39M-16-Text-19M model + +data_root=/mnt/SSD8T/home/wjj/dataset/standard_coco +pretrain_ckpt=checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt +model_name=TinyCLIP-ViT-39M-16-Text-19M +embed_path=metadata/coco_panoptic_clip_hand_craft_TinyCLIP-ViT-39M-16-Text-19M.npy +ann_file=${data_root}/annotations/panoptic_val2017.json + +echo "Generating text embeddings for ${model_name}" +echo "Model checkpoint: ${pretrain_ckpt}" +echo "Annotation file: ${ann_file}" +echo "Output path: ${embed_path}" + +python tools/generate_text_embeddings_tinyclip.py \ + --model_version ${model_name} \ + --pretrained ${pretrain_ckpt} \ + --ann ${ann_file} \ + --out_path ${embed_path} \ + --cache_dir checkpoints + +echo "Done! Embeddings saved to ${embed_path}" + diff --git a/tools/generate_text_embeddings.py b/tools/generate_text_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..fe63d5dcf0798c960827a19f5ba2a05560005c88 --- /dev/null +++ b/tools/generate_text_embeddings.py @@ -0,0 +1,197 @@ +# Modified from [ViLD](https://github.com/tensorflow/tpu/tree/master/models/official/detection/projects/vild) +import numpy as np +import torch +import torch.nn.functional as F +from tqdm import tqdm +import open_clip + + +def article(name): + return 'an' if name[0] in 'aeiou' else 'a' + +def processed_name(name, rm_dot=False): + # _ for lvis + # / for obj365 + res = name.replace('_', ' ').replace('/', ' or ').lower() + if rm_dot: + res = res.rstrip('.') + return res + + +single_template = [ + 'a photo of {article} {}.' +] + +multiple_templates = [ + 'There is {article} {} in the scene.', + 'There is the {} in the scene.', + 'a photo of {article} {} in the scene.', + 'a photo of the {} in the scene.', + 'a photo of one {} in the scene.', + + + 'itap of {article} {}.', + 'itap of my {}.', # itap: I took a picture of + 'itap of the {}.', + 'a photo of {article} {}.', + 'a photo of my {}.', + 'a photo of the {}.', + 'a photo of one {}.', + 'a photo of many {}.', + + 'a good photo of {article} {}.', + 'a good photo of the {}.', + 'a bad photo of {article} {}.', + 'a bad photo of the {}.', + 'a photo of a nice {}.', + 'a photo of the nice {}.', + 'a photo of a cool {}.', + 'a photo of the cool {}.', + 'a photo of a weird {}.', + 'a photo of the weird {}.', + + 'a photo of a small {}.', + 'a photo of the small {}.', + 'a photo of a large {}.', + 'a photo of the large {}.', + + 'a photo of a clean {}.', + 'a photo of the clean {}.', + 'a photo of a dirty {}.', + 'a photo of the dirty {}.', + + 'a bright photo of {article} {}.', + 'a bright photo of the {}.', + 'a dark photo of {article} {}.', + 'a dark photo of the {}.', + + 'a photo of a hard to see {}.', + 'a photo of the hard to see {}.', + 'a low resolution photo of {article} {}.', + 'a low resolution photo of the {}.', + 'a cropped photo of {article} {}.', + 'a cropped photo of the {}.', + 'a close-up photo of {article} {}.', + 'a close-up photo of the {}.', + 'a jpeg corrupted photo of {article} {}.', + 'a jpeg corrupted photo of the {}.', + 'a blurry photo of {article} {}.', + 'a blurry photo of the {}.', + 'a pixelated photo of {article} {}.', + 'a pixelated photo of the {}.', + + 'a black and white photo of the {}.', + 'a black and white photo of {article} {}.', + + 'a plastic {}.', + 'the plastic {}.', + + 'a toy {}.', + 'the toy {}.', + 'a plushie {}.', + 'the plushie {}.', + 'a cartoon {}.', + 'the cartoon {}.', + + 'an embroidered {}.', + 'the embroidered {}.', + + 'a painting of the {}.', + 'a painting of a {}.', +] + + +def build_text_embedding_coco(categories, model): + templates = multiple_templates + with torch.no_grad(): + zeroshot_weights = [] + attn12_weights = [] + for category in categories: + texts = [ + template.format(processed_name(category, rm_dot=True), article=article(category)) + for template in templates + ] + texts = [ + "This is " + text if text.startswith("a") or text.startswith("the") else text + for text in texts + ] + texts = open_clip.tokenize(texts).cuda() # tokenize + text_embeddings = model.encode_text(texts) + text_attnfeatures, _, _ = model.encode_text_endk(texts, stepk=12, normalize=True) + + text_embeddings /= text_embeddings.norm(dim=-1, keepdim=True) + text_embedding = text_embeddings.mean(dim=0) + text_embedding /= text_embedding.norm() + + text_attnfeatures = text_attnfeatures.mean(0) + text_attnfeatures = F.normalize(text_attnfeatures, dim=0) + attn12_weights.append(text_attnfeatures) + zeroshot_weights.append(text_embedding) + zeroshot_weights = torch.stack(zeroshot_weights, dim=0) + attn12_weights = torch.stack(attn12_weights, dim=0) + + return zeroshot_weights, attn12_weights + + +def build_text_embedding_lvis(categories, model, tokenizer): + templates = multiple_templates + + with torch.no_grad(): + all_text_embeddings = [] + for category in tqdm(categories): + texts = [ + template.format( + processed_name(category, rm_dot=True), article=article(category) + ) + for template in templates + ] + texts = [ + "This is " + text if text.startswith("a") or text.startswith("the") else text + for text in texts + ] + texts = tokenizer(texts).cuda() # tokenize + + text_embeddings = model.encode_text(texts) + text_embeddings /= text_embeddings.norm(dim=-1, keepdim=True) + text_embedding = text_embeddings.mean(dim=0) + text_embedding /= text_embedding.norm() + + all_text_embeddings.append(text_embedding) + all_text_embeddings = torch.stack(all_text_embeddings, dim=0) + + return all_text_embeddings + + +# voc_cats = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', +# 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', +# 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', +# 'tvmonitor') +# text_embeddings, _ = build_text_embedding_coco(voc_cats) +# np.save('datasets/metadata/voc_clip_hand_craft.npy', text_embeddings.cpu().numpy()) + +import argparse +import json + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--model_version', default='ViT-L-14-336') + parser.add_argument('--ann', default='data/coco/annotations/panoptic_val2017.json') + parser.add_argument('--out_path', default='metadata/coco_panoptic_clip_hand_craft_ViTL14x336.npy') + parser.add_argument('--pretrained', default='openai') + parser.add_argument('--cache_dir', default='checkpoints') + + args = parser.parse_args() + + model = open_clip.create_model( + args.model_version, pretrained=args.pretrained, cache_dir=args.cache_dir + ) + tokenizer = open_clip.get_tokenizer(args.model_version) + model.cuda() + + print('Loading', args.ann) + data = json.load(open(args.ann, 'r')) + cat_names = [x['name'] for x in \ + sorted(data['categories'], key=lambda x: x['id'])] + out_path = args.out_path + text_embeddings = build_text_embedding_lvis(cat_names, model, tokenizer) + np.save(out_path, text_embeddings.cpu().numpy()) diff --git a/tools/generate_text_embeddings_siglip.py b/tools/generate_text_embeddings_siglip.py new file mode 100644 index 0000000000000000000000000000000000000000..c0fcc5552a13a4ea888d6ba5406066139d9c3e1f --- /dev/null +++ b/tools/generate_text_embeddings_siglip.py @@ -0,0 +1,185 @@ +# Modified from [ViLD](https://github.com/tensorflow/tpu/tree/master/models/official/detection/projects/vild) +import numpy as np +import torch +import torch.nn.functional as F +from tqdm import tqdm +import open_clip + + +def article(name): + return 'an' if name[0] in 'aeiou' else 'a' + +def processed_name(name, rm_dot=False): + # _ for lvis + # / for obj365 + res = name.replace('_', ' ').replace('/', ' or ').lower() + if rm_dot: + res = res.rstrip('.') + return res + + +single_template = [ + 'a photo of {article} {}.' +] + +multiple_templates = [ + 'There is {article} {} in the scene.', + 'There is the {} in the scene.', + 'a photo of {article} {} in the scene.', + 'a photo of the {} in the scene.', + 'a photo of one {} in the scene.', + + + 'itap of {article} {}.', + 'itap of my {}.', # itap: I took a picture of + 'itap of the {}.', + 'a photo of {article} {}.', + 'a photo of my {}.', + 'a photo of the {}.', + 'a photo of one {}.', + 'a photo of many {}.', + + 'a good photo of {article} {}.', + 'a good photo of the {}.', + 'a bad photo of {article} {}.', + 'a bad photo of the {}.', + 'a photo of a nice {}.', + 'a photo of the nice {}.', + 'a photo of a cool {}.', + 'a photo of the cool {}.', + 'a photo of a weird {}.', + 'a photo of the weird {}.', + + 'a photo of a small {}.', + 'a photo of the small {}.', + 'a photo of a large {}.', + 'a photo of the large {}.', + + 'a photo of a clean {}.', + 'a photo of the clean {}.', + 'a photo of a dirty {}.', + 'a photo of the dirty {}.', + + 'a bright photo of {article} {}.', + 'a bright photo of the {}.', + 'a dark photo of {article} {}.', + 'a dark photo of the {}.', + + 'a photo of a hard to see {}.', + 'a photo of the hard to see {}.', + 'a low resolution photo of {article} {}.', + 'a low resolution photo of the {}.', + 'a cropped photo of {article} {}.', + 'a cropped photo of the {}.', + 'a close-up photo of {article} {}.', + 'a close-up photo of the {}.', + 'a jpeg corrupted photo of {article} {}.', + 'a jpeg corrupted photo of the {}.', + 'a blurry photo of {article} {}.', + 'a blurry photo of the {}.', + 'a pixelated photo of {article} {}.', + 'a pixelated photo of the {}.', + + 'a black and white photo of the {}.', + 'a black and white photo of {article} {}.', + + 'a plastic {}.', + 'the plastic {}.', + + 'a toy {}.', + 'the toy {}.', + 'a plushie {}.', + 'the plushie {}.', + 'a cartoon {}.', + 'the cartoon {}.', + + 'an embroidered {}.', + 'the embroidered {}.', + + 'a painting of the {}.', + 'a painting of a {}.', +] + + +def build_text_embedding_coco(categories, model): + templates = multiple_templates + with torch.no_grad(): + zeroshot_weights = [] + attn12_weights = [] + for category in categories: + texts = [ + template.format(processed_name(category, rm_dot=True), article=article(category)) + for template in templates + ] + texts = [ + "This is " + text if text.startswith("a") or text.startswith("the") else text + for text in texts + ] + texts = open_clip.tokenize(texts).cuda() # tokenize + text_embeddings = model.encode_text(texts) + text_attnfeatures, _, _ = model.encode_text_endk(texts, stepk=12, normalize=True) + + text_embeddings /= text_embeddings.norm(dim=-1, keepdim=True) + text_embedding = text_embeddings.mean(dim=0) + text_embedding /= text_embedding.norm() + + text_attnfeatures = text_attnfeatures.mean(0) + text_attnfeatures = F.normalize(text_attnfeatures, dim=0) + attn12_weights.append(text_attnfeatures) + zeroshot_weights.append(text_embedding) + zeroshot_weights = torch.stack(zeroshot_weights, dim=0) + attn12_weights = torch.stack(attn12_weights, dim=0) + + return zeroshot_weights, attn12_weights + + +def build_text_embedding_lvis(categories, model, tokenizer): + templates = multiple_templates + with torch.no_grad(): + all_text_embeddings = [] + for category in tqdm(categories): + texts = [ + template.format( + processed_name(category, rm_dot=True), article=article(category) + ) + for template in templates + ] + texts = [ + "This is " + text if text.startswith("a") or text.startswith("the") else text + for text in texts + ] + texts = tokenizer(texts, + truncation=None, + padding="max_length", + return_tensors="pt", + max_length=None)['input_ids'].cuda() + text_embeddings = model.text_model(texts)[1] + text_embeddings /= text_embeddings.norm(dim=-1, keepdim=True) + text_embedding = text_embeddings.mean(dim=0) + text_embedding /= text_embedding.norm() + + all_text_embeddings.append(text_embedding) + all_text_embeddings = torch.stack(all_text_embeddings, dim=0) + + return all_text_embeddings + +import argparse +import json +from transformers import SiglipProcessor, SiglipModel +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--ann', default='data/coco/annotations/panoptic_val2017.json') + parser.add_argument('--out_path', default='metadata/coco_panoptic_clip_hand_craft_ViTL14x336.npy') + args = parser.parse_args() + device = "cuda" + model = SiglipModel.from_pretrained("google/siglip-so400m-patch14-384", + torch_dtype=torch.float16, + device_map=device) + processor = SiglipProcessor.from_pretrained("google/siglip-so400m-patch14-384") + tokenizer=processor.tokenizer + print('Loading', args.ann) + data = json.load(open(args.ann, 'r')) + cat_names = [x['name'] for x in sorted(data['categories'], key=lambda x: x['id'])] + out_path = args.out_path + text_embeddings = build_text_embedding_lvis(cat_names, model, tokenizer) + np.save(out_path, text_embeddings.cpu().numpy()) diff --git a/tools/generate_text_embeddings_tinyclip.py b/tools/generate_text_embeddings_tinyclip.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6e8b7fc1ee0138e525a70b4fa26600af667dc3 --- /dev/null +++ b/tools/generate_text_embeddings_tinyclip.py @@ -0,0 +1,195 @@ +# Modified from [ViLD](https://github.com/tensorflow/tpu/tree/master/models/official/detection/projects/vild) +# TinyCLIP version for generating text embeddings +import numpy as np +import torch +import torch.nn.functional as F +from tqdm import tqdm +import sys +import os + +# Add src to path +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src')) +import open_clip + + +def article(name): + return 'an' if name[0] in 'aeiou' else 'a' + + +def processed_name(name, rm_dot=False): + # _ for lvis + # / for obj365 + res = name.replace('_', ' ').replace('/', ' or ').lower() + if rm_dot: + res = res.rstrip('.') + return res + + +single_template = [ + 'a photo of {article} {}.' +] + +multiple_templates = [ + 'There is {article} {} in the scene.', + 'There is the {} in the scene.', + 'a photo of {article} {} in the scene.', + 'a photo of the {} in the scene.', + 'a photo of one {} in the scene.', + + 'itap of {article} {}.', + 'itap of my {}.', # itap: I took a picture of + 'itap of the {}.', + 'a photo of {article} {}.', + 'a photo of my {}.', + 'a photo of the {}.', + 'a photo of one {}.', + 'a photo of many {}.', + + 'a good photo of {article} {}.', + 'a good photo of the {}.', + 'a bad photo of {article} {}.', + 'a bad photo of the {}.', + 'a photo of a nice {}.', + 'a photo of the nice {}.', + 'a photo of a cool {}.', + 'a photo of the cool {}.', + 'a photo of a weird {}.', + 'a photo of the weird {}.', + + 'a photo of a small {}.', + 'a photo of the small {}.', + 'a photo of a large {}.', + 'a photo of the large {}.', + + 'a photo of a clean {}.', + 'a photo of the clean {}.', + 'a photo of a dirty {}.', + 'a photo of the dirty {}.', + + 'a bright photo of {article} {}.', + 'a bright photo of the {}.', + 'a dark photo of {article} {}.', + 'a dark photo of the {}.', + + 'a photo of a hard to see {}.', + 'a photo of the hard to see {}.', + 'a low resolution photo of {article} {}.', + 'a low resolution photo of the {}.', + 'a cropped photo of {article} {}.', + 'a cropped photo of the {}.', + 'a close-up photo of {article} {}.', + 'a close-up photo of the {}.', + 'a jpeg corrupted photo of {article} {}.', + 'a jpeg corrupted photo of the {}.', + 'a blurry photo of {article} {}.', + 'a blurry photo of the {}.', + 'a pixelated photo of {article} {}.', + 'a pixelated photo of the {}.', + + 'a black and white photo of the {}.', + 'a black and white photo of {article} {}.', + + 'a plastic {}.', + 'the plastic {}.', + + 'a toy {}.', + 'the toy {}.', + 'a plushie {}.', + 'the plushie {}.', + 'a cartoon {}.', + 'the cartoon {}.', + + 'an embroidered {}.', + 'the embroidered {}.', + + 'a painting of the {}.', + 'a painting of a {}.', +] + + +def build_text_embedding_lvis(categories, model, tokenizer): + """Build text embeddings for categories using TinyCLIP""" + templates = multiple_templates + + with torch.no_grad(): + all_text_embeddings = [] + for category in tqdm(categories, desc="Generating embeddings"): + texts = [ + template.format( + processed_name(category, rm_dot=True), article=article(category) + ) + for template in templates + ] + texts = [ + "This is " + text if text.startswith("a") or text.startswith("the") else text + for text in texts + ] + # Tokenize texts - tokenizer returns tensor (same as inference.py) + text_tokens = tokenizer(texts).cuda() + + text_embeddings = model.encode_text(text_tokens, normalized=True) + # Average over all templates + text_embedding = text_embeddings.mean(dim=0) + text_embedding /= text_embedding.norm() + + all_text_embeddings.append(text_embedding) + all_text_embeddings = torch.stack(all_text_embeddings, dim=0) + + return all_text_embeddings + + +import argparse +import json + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Generate text embeddings for TinyCLIP models') + parser.add_argument('--model_version', + default='TinyCLIP-auto-ViT-63M-32-Text-31M', + help='TinyCLIP model name') + parser.add_argument('--ann', + default='dataset/coco/annotations/panoptic_val2017.json', + help='Path to COCO panoptic annotation file') + parser.add_argument('--out_path', + default=None, + help='Output path for embeddings (auto-generated if not specified)') + parser.add_argument('--pretrained', + default='', + help='Path to pretrained checkpoint or pretrained tag') + parser.add_argument('--cache_dir', + default='checkpoints', + help='Cache directory for pretrained models') + + args = parser.parse_args() + + # Auto-generate output path if not specified + if args.out_path is None: + model_name_safe = args.model_version.replace('/', '-').replace(' ', '_') + args.out_path = f'metadata/coco_panoptic_clip_hand_craft_{model_name_safe}.npy' + + print(f'Loading TinyCLIP model: {args.model_version}') + print(f'Pretrained: {args.pretrained if args.pretrained else "None"}') + + # Create model and tokenizer using tiny_clip module directly + from open_clip import tiny_clip + model, _, _ = tiny_clip.create_model_and_transforms( + args.model_version, + pretrained=args.pretrained if args.pretrained else None, + cache_dir=args.cache_dir + ) + tokenizer = tiny_clip.get_tokenizer(args.model_version) + model.cuda() + model.eval() + print('Loading', args.ann) + data = json.load(open(args.ann, 'r')) + cat_names = [x['name'] for x in + sorted(data['categories'], key=lambda x: x['id'])] + + print(f'Found {len(cat_names)} categories') + print(f'Generating embeddings...') + + text_embeddings = build_text_embedding_lvis(cat_names, model, tokenizer) + + print(f'Saving embeddings to {args.out_path}') + np.save(args.out_path, text_embeddings.cpu().numpy()) + print(f'Done! Embeddings shape: {text_embeddings.shape}') + diff --git a/tools/generate_tinyclip_embeddings.sh b/tools/generate_tinyclip_embeddings.sh new file mode 100644 index 0000000000000000000000000000000000000000..767eb355265b266804a22b12a1edb9d731caa038 --- /dev/null +++ b/tools/generate_tinyclip_embeddings.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# 生成 TinyCLIP 文本嵌入的示例脚本 + +# 设置模型和路径 +model_version="TinyCLIP-auto-ViT-63M-32-Text-31M" +pretrained_ckpt="checkpoints/TinyCLIP-auto-ViT-63M-32-Text-31M-LAIONYFCC400M.pt" +ann_file="/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/panoptic_val2017.json" + +# 生成嵌入 +python tools/generate_text_embeddings_tinyclip.py \ + --model_version ${model_version} \ + --pretrained ${pretrained_ckpt} \ + --ann ${ann_file} + +# 也可以为其他 TinyCLIP 模型生成: +# python tools/generate_text_embeddings_tinyclip.py \ +# --model_version TinyCLIP-auto-ViT-45M-32-Text-18M \ +# --pretrained checkpoints/TinyCLIP-auto-ViT-45M-32-Text-18M-LAIONYFCC400M.pt \ +# --ann ${ann_file} + diff --git a/tools/k_means.py b/tools/k_means.py new file mode 100644 index 0000000000000000000000000000000000000000..4317d95d6ee86c8c7d843769b76d61c732f2bed7 --- /dev/null +++ b/tools/k_means.py @@ -0,0 +1,88 @@ +import logging +import cv2 +from sklearn.cluster import KMeans +import torch +import torch.nn.functional as F +import numpy as np +from tqdm import tqdm +from open_clip.model import get_cast_dtype +from training.distributed import is_master +from training.precision import get_autocast +from training.zero_shot import multi_gpu_sync +import os + +def run_kmeans(model, data, args): + model.eval() + def _process_cluster(cluster, h, w): + cluster = cluster.reshape(h, w).astype(np.float32) + cluster = cv2.medianBlur(cluster, 5) + return cluster.reshape(h*w) > 0.5 + + def _per_image_kmeans(feature_map, masks, image_name, image_shape): + f_h, f_w = feature_map.shape[1:] # 64, 64 + tar_h,tar_w = tuple(image_shape.tolist())# 1024, 1024 + tar_h,tar_w=tar_h//4,tar_w//4 + # scale_factor = min(f_h/ori_h, f_w/ori_w) # 0.0625 + # tar_h, tar_w = min(int(ori_h * scale_factor), f_h), min(int(ori_w * scale_factor), f_w) + # feature_map = feature_map[:, :tar_h, :tar_w].contiguous().view(-1, tar_h * tar_w).T + feature_map = F.interpolate(feature_map.unsqueeze(0), size=(tar_h, tar_w),mode="bilinear").squeeze(0).contiguous().view(-1, tar_h * tar_w).T + valid = masks.sum((-2, -1)) > 0 + masks = masks[valid, :tar_h, :tar_w] + if masks.shape[0] == 0: + return torch.tensor([]).to(feature_map) + masks = masks.view(-1, tar_h * tar_w).to(feature_map) + # TODO: kmeans on feature_map + feature_map = F.normalize(feature_map, dim=-1).cpu().numpy() + cluster_method = KMeans(n_clusters=len(masks), n_init=10) + # fit model and predict clusters + results = cluster_method.fit_predict(feature_map) + cluster_ids = np.unique(results) + clusters = np.stack([_process_cluster(results == cluster_id, tar_h, tar_w) for cluster_id in cluster_ids if cluster_id >= 0]) + clusters = torch.from_numpy(clusters).to(masks) + union = torch.clamp(clusters[:, None] + masks[None], max=1.0).sum(-1) + intersection = (clusters[:, None] * masks[None]).sum(-1) + iofs = intersection / (union + 1e-12) + max_iofs = iofs.max(dim=-1).values + # TODO: save the results + results = results.reshape(tar_h, tar_w) + log_base_path = os.path.join(args.logs, args.name) + np.save(f"{log_base_path}/{image_name.split('.')[0]}.npy", results) + return max_iofs + + autocast = get_autocast(args.precision) + cast_dtype = get_cast_dtype(args.precision) + with torch.no_grad(): + best_overlaps = [] + # _, images, bboxes, image_crops, gt_masks, masked_image_crops, proxy_imgs + # for images, gt_masks, image_names, image_shapes in tqdm(dataloader, disable=not is_master(args)): + logging.info('Region classifier') + for image_names, images, _, _, gt_masks, _, _ in tqdm(data['val'].dataloader, disable=not is_master(args)): + image_shapes=[] + for image in images: + image_shapes.append(torch.tensor([image.shape[-2],image.shape[-1]],device=images.device)) + image_shapes=torch.stack(image_shapes,dim=0) + images = images.to(args.device) + if cast_dtype is not None: + images = images.to(dtype=cast_dtype) + with autocast(): + # predict + if args.distributed and not args.horovod: + module = model.module + else: + module = model + feature_maps = module.encode_dense(images, + normalize=True, + keep_shape=True, + mode="ss", + ex_feats=None) + best_overlaps += list(map(_per_image_kmeans, feature_maps, gt_masks, image_names, image_shapes)) + best_overlaps = torch.cat(best_overlaps) + if args.distributed and not args.horovod: + best_overlaps = multi_gpu_sync(best_overlaps) + + return best_overlaps.mean() + + + +if __name__=="__main__": + pass \ No newline at end of file diff --git a/tools/plot_box.py b/tools/plot_box.py new file mode 100644 index 0000000000000000000000000000000000000000..1ec81e424d259ff4156acb93dbf04fb9e4f9b5db --- /dev/null +++ b/tools/plot_box.py @@ -0,0 +1,80 @@ +import matplotlib.pyplot as plt +from PIL import Image +import matplotlib.patches as patches + +# 加载图像 +image_path = "demo_images/yidali.jpg" # 替换为实际图像路径 +output_path = "output_image.jpg" # 设置保存路径 +image = Image.open(image_path) + +# 边界框和类别数据 +data = [ + {"bbox_2d": [165, 198, 274, 350], "label": "curtain"}, + {"bbox_2d": [138, 150, 305, 400], "label": "window"}, + {"bbox_2d": [495, 181, 585, 408], "label": "window"}, + {"bbox_2d": [263, 347, 500, 508], "label": "bicycle"}, + {"bbox_2d": [101, 430, 235, 509], "label": "flowerpot"}, + {"bbox_2d": [235, 400, 299, 487], "label": "flowerpot"}, + {"bbox_2d": [359, 328, 408, 452], "label": "flowerpot"}, + {"bbox_2d": [654, 376, 696, 428], "label": "flowerpot"}, + {"bbox_2d": [689, 403, 711, 429], "label": "flowerpot"}, + {"bbox_2d": [711, 399, 731, 425], "label": "flowerpot"}, + {"bbox_2d": [731, 356, 759, 382], "label": "flowerpot"}, + {"bbox_2d": [0, 402, 69, 552], "label": "flowerpot"} +] + +# 定义颜色 +color_map = { + "curtain": "#eb60b2", + "window": "#4adde5", + "bicycle": "#e3d820", + "flowerpot": "#2adac0" +} + +# 创建绘图 +fig, ax = plt.subplots(1, figsize=(12, 8)) +ax.imshow(image) + +# 绘制边界框 +instance_count = {} +for item in data: + bbox = item["bbox_2d"] + label = item["label"] + + # 计算颜色深度 + if label not in instance_count: + instance_count[label] = 0 + color_depth = 1 - (instance_count[label] * 0.1) # 每个实例颜色变暗 + base_color = color_map[label] + color = base_color + instance_count[label] += 1 + + # 绘制矩形 + rect = patches.Rectangle( + (bbox[0], bbox[1]), + bbox[2] - bbox[0], + bbox[3] - bbox[1], + linewidth=4, + edgecolor=color, + facecolor="none" + ) + ax.add_patch(rect) + + # 添加标签 + ax.text( + bbox[0], + bbox[1] - 10, + label, + color="white", + fontsize=13, + bbox=dict(facecolor=color, edgecolor="none", boxstyle="round,pad=0.2") + ) + +# 隐藏坐标轴 +ax.axis("off") + +# 保存结果 +plt.savefig(output_path, bbox_inches="tight", pad_inches=0, dpi=300) +plt.close() + +print(f"Image saved to {output_path}") \ No newline at end of file diff --git a/tools/plot_box2.py b/tools/plot_box2.py new file mode 100644 index 0000000000000000000000000000000000000000..7f53b3fd6058f1138673b8d16cc084c7bf590c84 --- /dev/null +++ b/tools/plot_box2.py @@ -0,0 +1,75 @@ +import matplotlib.pyplot as plt +from PIL import Image +import matplotlib.patches as patches + +# 加载图像 +image_path = "demo_images/yidali2.jpg" # 替换为第二张图像的实际路径 +output_path = "output_image_2.jpg" # 设置保存路径 +image = Image.open(image_path) + +# 第二张图像的边界框和类别数据 +data = [ + {"bbox_2d": [668, 240, 799, 538], "label": "Person"}, + {"bbox_2d": [531, 319, 703, 580], "label": "Person"}, + {"bbox_2d": [207, 235, 348, 569], "label": "Person"}, + {"bbox_2d": [623, 344, 691, 389], "label": "Violin"}, + {"bbox_2d": [281, 195, 425, 560], "label": "cello"}, + {"bbox_2d": [0, 302, 208, 492], "label": "bicycle"}, + {"bbox_2d": [338, 316, 432, 449], "label": "bicycle"}, + {"bbox_2d": [679, 270, 840, 384], "label": "guitar"} +] + +# 定义颜色(添加 guitar 的颜色) +color_map = { + "Person": "#ff5733", # 亮橙色 + "Violin": "#33ff57", # 亮绿色 + "cello": "#5733ff", # 亮蓝色 + "bicycle": "#e3d820", # 黄色 + "guitar": "#ff33a1" # 亮粉色(新增颜色) +} + +# 创建绘图 +fig, ax = plt.subplots(1, figsize=(12, 8)) +ax.imshow(image) + +# 绘制边界框 +instance_count = {} +for item in data: + bbox = item["bbox_2d"] + label = item["label"] + + # 计算颜色(暂未调整深度) + if label not in instance_count: + instance_count[label] = 0 + color = color_map[label] + instance_count[label] += 1 + + # 绘制矩形 + rect = patches.Rectangle( + (bbox[0], bbox[1]), + bbox[2] - bbox[0], + bbox[3] - bbox[1], + linewidth=4, + edgecolor=color, + facecolor="none" + ) + ax.add_patch(rect) + + # 添加标签 + ax.text( + bbox[0], + bbox[1] - 10, + label, + color="white", + fontsize=13, + bbox=dict(facecolor=color, edgecolor="none", boxstyle="round,pad=0.2") + ) + +# 隐藏坐标轴 +ax.axis("off") + +# 保存结果 +plt.savefig(output_path, bbox_inches="tight", pad_inches=0, dpi=300) +plt.close() + +print(f"Image saved to {output_path}") \ No newline at end of file diff --git a/tools/plot_cc3m.py b/tools/plot_cc3m.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf8435521c1c98612073fdf41b2613ac6b052b1 --- /dev/null +++ b/tools/plot_cc3m.py @@ -0,0 +1,54 @@ +import matplotlib.pyplot as plt +import seaborn as sns + +# 设置数据 +data_size = ["30K", "60K", "120K", "240K", "480K"] +avg_segmentation_MIoU = [37.05, 41.7, 42.0, 41.9, 41.8] +# COCO Distill 数据 +coco_distill_avg_segmentation_MIoU = [None, None, 41.9, None, None] # 只画一个点 + +# 设置绘图风格和颜色 +sns.set_style("whitegrid") + +# 定义新的颜色、线条样式和标记符号 +color_palette = ['#1f77b4', '#ff7f0e', '#2ca02c'] # 为 COCO 添加新颜色 +line_styles = ['--', '-.', ':'] # 为 COCO 添加新线条样式 +markers = ['o', 's', 'D'] # 为 COCO 添加新标记符号 + +# 设置全局字体和线宽 +plt.rcParams.update({ + 'font.size': 10, # 字体大小 + 'axes.labelsize': 10, + 'lines.linewidth': 2.0, # 线条宽度 + 'legend.fontsize': 8, # 图例字体大小 + 'xtick.labelsize': 8, # x轴刻度字体大小 + 'ytick.labelsize': 8, # y轴刻度字体大小 + 'grid.color': 'gray', # 网格线颜色 + 'grid.alpha': 0.3, # 调整网格线透明度 +}) + +# 绘制折线图 +plt.figure(figsize=(4, 2)) # 调整图的大小 +plt.plot(data_size, avg_segmentation_MIoU, linestyle=line_styles[0], marker=markers[0], color=color_palette[0], label='Avg mIoU (CC3M Distillation)') + +# 绘制 COCO 点(空心红色散点) +plt.scatter( + data_size, + coco_distill_avg_segmentation_MIoU, + edgecolor='red', # 散点边框颜色 + facecolor='none', # 空心 + marker=markers[2], # 标记样式 + s=50, # 散点大小(增大) + linewidths=2, # 边框宽度(加粗) + label='Avg mIoU (COCO Distillation)', + zorder=5 +) + +# 设置轴标签并调整标签与坐标轴的距离 +plt.xlabel('Data Size (sample from CC3M)', labelpad=0) # 横坐标标签,设置距离 +plt.ylabel('Performance (ViT-B)', labelpad=0) # 纵坐标标签,设置距离 +plt.grid(True, linestyle='--', color='gray', alpha=0.3) # 更淡的网格 +plt.legend(loc='best', fontsize=10) # 图例位置和字体大小 +plt.tight_layout() +plt.savefig('data_size_metrics.pdf', dpi=300) # 保存为PDF +plt.close() \ No newline at end of file diff --git a/tools/plot_cc3mv2.py b/tools/plot_cc3mv2.py new file mode 100644 index 0000000000000000000000000000000000000000..c9d016c7e96458a7427c107f1c979a7bc40dbefc --- /dev/null +++ b/tools/plot_cc3mv2.py @@ -0,0 +1,44 @@ +import matplotlib.pyplot as plt + +data_size = ["30K", "60K", "120K", "240K", "480K"] +avg_segmentation_MIoU = [38.99, 43.88, 44.20, 44.1, 43.99] +coco_distill_avg_segmentation_MIoU = [None, None, 44.1, None, None] + +colors = ['#2077b4', '#d62728'] +markers = ['o', 'D'] +linestyle = '--' + +plt.figure(figsize=(4, 3)) # 压缩高度 + +plt.plot( + data_size, avg_segmentation_MIoU, + label="Avg mIoU (CC3M)", + linestyle=linestyle, + marker=markers[0], + color=colors[0], + linewidth=4, + markersize=8, + zorder=3, +) + +for idx, y in enumerate(coco_distill_avg_segmentation_MIoU): + if y is not None: + plt.scatter( + data_size[idx], y, + label="Avg mIoU (COCO)" if idx == 2 else "", + marker=markers[1], + s=120, + facecolors='none', + edgecolors=colors[1], + linewidths=2.5, + zorder=5, + ) + +plt.ylim(38, 45) # 压缩y轴区间 +plt.grid(True, linestyle='--', alpha=0.6) +plt.tick_params(axis='x', labelsize=14) # x轴刻度大 +plt.tick_params(axis='y', labelsize=12) # y轴刻度不变 +plt.tight_layout() +plt.legend(fontsize=16, loc='lower right') +plt.savefig('data_size.pdf', dpi=300) +plt.close() \ No newline at end of file diff --git a/tools/plot_histogram.py b/tools/plot_histogram.py new file mode 100644 index 0000000000000000000000000000000000000000..6672b0888552b2a9a307fae75e71be5a32422d29 --- /dev/null +++ b/tools/plot_histogram.py @@ -0,0 +1,41 @@ +import matplotlib.pyplot as plt +import numpy as np + +# 数据 +categories = ['DINO-B/8', 'DINO-B/16', 'SAM-B/16', 'SAM-L/16', 'DINOv2-B/14', 'DINOv2-L/14'] +x = np.arange(len(categories)) +OV_COCO = [42.0, 41.8, 42.6, 42.5, 43.3, 43.3] +VOC21 = [59.7, 61.5, 55.0, 58.9, 64.1, 62.8] +COCO_Obj = [31.2, 32.3, 25.8, 30.7, 38.7, 36.7] + +# 设置柱状图宽度 +width = 0.25 # 调整宽度以适应更多类别 + +# 创建图形 +fig, ax = plt.subplots(figsize=(12, 6)) # 调整图形大小以适应更多类别 + +# 绘制柱状图,调整颜色和填充 +bars1 = ax.bar(x - width, OV_COCO, width, label=r'OV-COCO (AP_novel)', color='#1f77b4', edgecolor='white', hatch='X') # 第1组 +bars2 = ax.bar(x, VOC21, width, label=r'VOC21 (mIoU)', color='#ff7f0e', edgecolor='white', hatch='X') # 第2组 +bars3 = ax.bar(x + width, COCO_Obj, width, label=r'COCO-Obj (mIoU)', color='#2ca02c', edgecolor='white', hatch='X') # 第3组 + +# 添加标题和标签 +ax.set_xticks(x) +# ax.set_xticklabels(categories, fontsize=14, rotation=45, ha='center') # 调整字体大小并居中显示 +ax.set_xticklabels(categories, fontsize=14, ha='center') # 调整字体大小并居中显示 + +# 自动放置 legend +ax.legend(fontsize=14, loc='best') + +# 在柱状图上添加数值 +ax.bar_label(bars1, fmt='%.2f', fontsize=12, padding=3) # 格式化数值显示为小数点后两位 +ax.bar_label(bars2, fmt='%.2f', fontsize=12, padding=3) +ax.bar_label(bars3, fmt='%.2f', fontsize=12, padding=3) + +# 美化图形 +ax.spines['top'].set_visible(False) +ax.spines['right'].set_visible(False) + +# 保存为图片 +plt.tight_layout() +plt.savefig('vfm_ablations.pdf', dpi=300) \ No newline at end of file diff --git a/tools/plot_histogramv2.py b/tools/plot_histogramv2.py new file mode 100644 index 0000000000000000000000000000000000000000..ef1db1fbaaa9a3e6ee063d8e33d9bc4eaac4efe1 --- /dev/null +++ b/tools/plot_histogramv2.py @@ -0,0 +1,65 @@ +import matplotlib.pyplot as plt +import numpy as np + +# 数据 +categories = ['DINO-B/8', 'DINO-B/16', 'SAM-B/16', 'SAM-L/16', 'DINOv2-B/14', 'DINOv2-L/14'] +x = np.arange(len(categories)) - 0.6 # 整体向左平移,使得第一组更靠近 y 轴 + +# 每个分组的结果数据(去掉 CityScape) +VOC21 = [59.7, 61.5, 55.0, 58.9, 64.1, 62.8] +COCO_Obj = [31.2, 32.3, 25.8, 30.7, 38.7, 36.7] +OV_COCO = [42.0, 41.8, 42.6, 42.5, 43.3, 43.3] + +# 设置柱状图宽度 +width = 0.25 # 调整宽度以适应更少的类别 + +# 创建图形 +fig, ax = plt.subplots(figsize=(8, 4)) # 调整图形大小 + +# 绘制柱状图,调整颜色和填充 +bars1 = ax.bar(x - width, VOC21, width, label=r'VOC21', color='#1f77b4', edgecolor='white', hatch='X') # 第1组 +bars2 = ax.bar(x, COCO_Obj, width, label=r'COCO-Obj', color="#ff7f0e", edgecolor='white', hatch='X') # 第2组 +bars3 = ax.bar(x + width, OV_COCO, width, label=r'OV-COCO', color='#2ca02c', edgecolor='white', hatch='X') # 第3组 + +# 添加标题和标签 +ax.set_xticks(x) +ax.set_xticklabels(categories, fontsize=16, ha='center') # 调整字体大小并居中显示 + +# 自动放置 legend,略微调大方块显示 +ax.legend(fontsize=14, loc='upper center', bbox_to_anchor=(0.46, 1.0), ncol=3, frameon=True, + handletextpad=0.5, columnspacing=1.0, handlelength=1.5, handleheight=1.3) +# handlelength 和 handleheight 稍微调大 + +# 在柱状图上添加数值,并标注最大值 +highlight_fontsize = 15 # 可手动调整红色加粗文本的字体大小 +for bar, value in zip(bars1, VOC21): + if value == max(VOC21): + ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:.1f}', + ha='center', va='bottom', fontsize=highlight_fontsize, color='red', fontweight='bold') + else: + ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:.1f}', + ha='center', va='bottom', fontsize=14) + +for bar, value in zip(bars2, COCO_Obj): + if value == max(COCO_Obj): + ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:.1f}', + ha='center', va='bottom', fontsize=highlight_fontsize, color='red', fontweight='bold') + else: + ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:.1f}', + ha='center', va='bottom', fontsize=14) + +for bar, value in zip(bars3, OV_COCO): + if value == max(OV_COCO): # 两个最大值都加粗 + ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:.1f}', + ha='center', va='bottom', fontsize=highlight_fontsize, color='red', fontweight='bold') + else: + ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:.1f}', + ha='center', va='bottom', fontsize=14) + +# 美化图形 +ax.spines['top'].set_visible(False) +ax.spines['right'].set_visible(False) + +# 保存为图片 +plt.tight_layout() +plt.savefig('vfm_ablation.png', dpi=300) \ No newline at end of file diff --git a/tools/plot_histogramv3.py b/tools/plot_histogramv3.py new file mode 100644 index 0000000000000000000000000000000000000000..b64817167e3c5f4d5198bb89ab6eb307f0f418d2 --- /dev/null +++ b/tools/plot_histogramv3.py @@ -0,0 +1,47 @@ +import matplotlib.pyplot as plt +import numpy as np + +# 数据 +categories = ['DINO/8', 'DINO/16', 'SAM-B', 'SAM-L', 'DINOv2-B', 'DINOv2-L'] +x = np.arange(len(categories)) - 0.2 + +OV_COCO = [42.0, 41.8, 42.6, 42.5, 43.3, 43.3] +avg_iou = [40.3, 41.4, 37.9, 40.4, 44.1, 42.9] + +width = 0.35 + +fig, ax = plt.subplots(figsize=(8, 4)) + +bars1 = ax.bar(x - width/2, OV_COCO, width, label='mAP (Novel)', color='#1f77b4', edgecolor='white', hatch='X') +bars2 = ax.bar(x + width/2, avg_iou, width, label='Avg. mIoU', color='#ff7f0e', edgecolor='white', hatch='X') + +ax.set_xticks(x) +ax.set_xticklabels(categories, fontsize=13, ha='center') # 调小一号 + +ax.legend(fontsize=14, loc='upper center', bbox_to_anchor=(0.35, 1.09), ncol=2, frameon=False, + handletextpad=0.5, columnspacing=1.0) + +highlight_fontsize = 12.5 # 调小一号 + +# 在柱状图上添加数值,并标注最大值 +for bar, value in zip(bars1, OV_COCO): + if value == max(OV_COCO): + ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:.1f}', + ha='center', va='bottom', fontsize=highlight_fontsize, color='red', fontweight='bold') + else: + ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:.1f}', + ha='center', va='bottom', fontsize=12) # 调小一号 + +for bar, value in zip(bars2, avg_iou): + if value == max(avg_iou): + ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:.1f}', + ha='center', va='bottom', fontsize=highlight_fontsize, color='red', fontweight='bold') + else: + ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(), f'{value:.1f}', + ha='center', va='bottom', fontsize=12) # 调小一号 + +ax.spines['top'].set_visible(False) +ax.spines['right'].set_visible(False) +plt.tick_params(axis='y', labelsize=12) # y轴刻度不变 +plt.tight_layout() +plt.savefig('vfm_ablation.png', dpi=300) \ No newline at end of file diff --git a/tools/plot_hyper.py b/tools/plot_hyper.py new file mode 100644 index 0000000000000000000000000000000000000000..e1a88b7ff42a3fefb5198ddd525d149e9c20aff0 --- /dev/null +++ b/tools/plot_hyper.py @@ -0,0 +1,78 @@ +import matplotlib.pyplot as plt +import numpy as np + +# 数据集 +datasets = { + "COCO-Stuff": [25.44, 26.07, 26.64, 26.82, 26.91, 27.05, 27.0, 27.13, 27.17, 27.21], + "ADE": [21.88, 22.54, 23.03, 23.14, 23.16, 23.24, 23.17, 23.24, 23.24, 23.22], + "CityScape": [34.53, 35.62, 35.81, 35.75, 35.71, 35.59, 35.37, 35.37, 35.36, 35.38], + "COCO-Obj": [37.01, 37.9, 38.55, 38.7, 38.71, 38.76, 38.58, 38.79, 38.79, 38.82], + "Context 60": [35.82, 36.71, 37.69, 37.9, 38.05, 38.25, 38.48, 38.53, 38.59, 38.65], + "Context 59": [39.64, 40.46, 41.41, 41.63, 41.75, 41.94, 42.2, 42.2, 42.25, 42.32], + "VOC 20": [83.53, 84.57, 85.29, 85.33, 85.43, 85.58, 85.17, 85.62, 85.63, 85.58], + "VOC 21": [61.44, 62.58, 63.74, 64.1, 64.39, 64.74, 64.91, 65.19, 65.33, 65.44], + "OV-COCO": [41.7, 42.8, 43.3, 42.7, 42.4, 42.0, 42.2, 41.8, 42.0, 41.5], +} + +hyperparams = np.linspace(0.1, 1.0, 10) + +# 可自定义 +colors = ['#9467bd', '#ff7f0e', '#2ca02c', '#2077b4', '#8c564b'] +markers = ['o', 's', '^', 'D', 'P'] +linestyle = '--' + +groups = [ + ["COCO-Stuff", "ADE"], # 组1 + ["COCO-Obj", "Context 60", "Context 59", "CityScape", "OV-COCO"], # 组2 + ["VOC 20", "VOC 21"], # 组3 +] + +# 组的文件名 +group_filenames = ["group1.png", "group2.png", "group3.png"] + +# OV-COCO 专属样式 +ov_coco_color = '#d62728' +ov_coco_marker = 'o' +ov_coco_linestyle = '-' + +for group_idx, group in enumerate(groups): + plt.figure(figsize=(6, 4)) + for idx, dataset_name in enumerate(group): + if dataset_name == "OV-COCO": + plt.plot( + hyperparams, datasets[dataset_name], + label=dataset_name, + linestyle=ov_coco_linestyle, # 实线 + marker=ov_coco_marker, + color=ov_coco_color, + linewidth=5, + markersize=10, + zorder=10, + ) + else: + color = colors[idx % len(colors)] + marker = markers[idx % len(markers)] + plt.plot( + hyperparams, datasets[dataset_name], + label=dataset_name, + linestyle=linestyle, + marker=marker, + color=color, + linewidth=4, + markersize=8, + ) + plt.xlabel("") + plt.ylabel("") + plt.grid(True, linestyle='--', alpha=0.6) + plt.tick_params(axis='both', which='major', labelsize=8) + plt.tight_layout() + + # 针对第二组手动设置 legend 位置 + if group_idx == 1: + # 你可以在这里调整 loc 和 bbox_to_anchor + plt.legend(fontsize=9, loc='upper left', bbox_to_anchor=(0.5, 0.38),ncol=2) + else: + plt.legend(fontsize=9,loc='center right') + + plt.savefig(group_filenames[group_idx], dpi=300) + plt.close() \ No newline at end of file diff --git a/tools/plot_hyperv2.py b/tools/plot_hyperv2.py new file mode 100644 index 0000000000000000000000000000000000000000..f3d41a21c43a3b0c4b8b50320e5f7d15416370d6 --- /dev/null +++ b/tools/plot_hyperv2.py @@ -0,0 +1,78 @@ +import matplotlib.pyplot as plt +import numpy as np + +# 数据集 +datasets = { + "COCO-Stuff": [25.44, 26.07, 26.64, 26.82, 26.91, 27.05, 27.0, 27.13, 27.17, 27.21], + "ADE": [21.88, 22.54, 23.03, 23.14, 23.16, 23.24, 23.17, 23.24, 23.24, 23.22], + "CityScape": [34.53, 35.62, 35.81, 35.75, 35.71, 35.59, 35.37, 35.37, 35.36, 35.38], + "COCO-Obj": [37.01, 37.9, 38.55, 38.7, 38.71, 38.76, 38.58, 38.79, 38.79, 38.82], + "Context 60": [35.82, 36.71, 37.69, 37.9, 38.05, 38.25, 38.48, 38.53, 38.59, 38.65], + "Context 59": [39.64, 40.46, 41.41, 41.63, 41.75, 41.94, 42.2, 42.2, 42.25, 42.32], + "VOC 20": [83.53, 84.57, 85.29, 85.33, 85.43, 85.58, 85.17, 85.62, 85.63, 85.58], + "VOC 21": [61.44, 62.58, 63.74, 64.1, 64.39, 64.74, 64.91, 65.19, 65.33, 65.44], + "OV-COCO": [41.7, 42.8, 43.3, 42.7, 42.4, 42.0, 42.2, 41.8, 42.0, 41.5], +} + +hyperparams = np.linspace(0.1, 1.0, 10) + +# 可自定义 +colors = ['#9467bd', '#ff7f0e', '#2ca02c', '#2077b4', '#8c564b'] +markers = ['o', 's', '^', 'D', 'P'] +linestyle = '--' + +groups = [ + ["COCO-Stuff", "ADE"], # 组1 + ["COCO-Obj", "Context 60", "Context 59", "CityScape", "OV-COCO"], # 组2 + ["VOC 20", "VOC 21"], # 组3 +] + +# 组的文件名 +group_filenames = ["group1.png", "group2.png", "group3.png"] + +# OV-COCO 专属样式 +ov_coco_color = '#d62728' +ov_coco_marker = 'o' +ov_coco_linestyle = '-' + +for group_idx, group in enumerate(groups): + plt.figure(figsize=(6, 4)) + for idx, dataset_name in enumerate(group): + if dataset_name == "OV-COCO": + plt.plot( + hyperparams, datasets[dataset_name], + label=dataset_name, + linestyle=ov_coco_linestyle, # 实线 + marker=ov_coco_marker, + color=ov_coco_color, + linewidth=5, + markersize=10, + zorder=10, + ) + else: + color = colors[idx % len(colors)] + marker = markers[idx % len(markers)] + plt.plot( + hyperparams, datasets[dataset_name], + label=dataset_name, + linestyle=linestyle, + marker=marker, + color=color, + linewidth=4, + markersize=8, + ) + plt.xlabel("") + plt.ylabel("") + plt.grid(True, linestyle='--', alpha=0.6) + plt.tick_params(axis='both', which='major', labelsize=8) + plt.tight_layout() + + # 针对第二组手动设置 legend 位置 + if group_idx == 1: + # 你可以在这里调整 loc 和 bbox_to_anchor + plt.legend(fontsize=10, loc='upper left', bbox_to_anchor=(0.5, 0.41),ncol=2) + else: + plt.legend(fontsize=15,loc='center right') + + plt.savefig(group_filenames[group_idx], dpi=300) + plt.close() \ No newline at end of file diff --git a/tools/plot_hyperv3.py b/tools/plot_hyperv3.py new file mode 100644 index 0000000000000000000000000000000000000000..bc99084af4b4cce3e501ee6178efd4bb9e43eb58 --- /dev/null +++ b/tools/plot_hyperv3.py @@ -0,0 +1,66 @@ +import matplotlib.pyplot as plt +import numpy as np + +# 数据集 +datasets = { + "COCO-Stuff": [25.44, 26.07, 26.64, 26.82, 26.91, 27.05, 27.0, 27.13, 27.17, 27.21], + "ADE": [21.88, 22.54, 23.03, 23.14, 23.16, 23.24, 23.17, 23.24, 23.24, 23.22], + "CityScape": [34.53, 35.62, 35.81, 35.75, 35.71, 35.59, 35.37, 35.37, 35.36, 35.38], + "COCO-Obj": [37.01, 37.9, 38.55, 38.7, 38.71, 38.76, 38.58, 38.79, 38.79, 38.82], + "Context 60": [35.82, 36.71, 37.69, 37.9, 38.05, 38.25, 38.48, 38.53, 38.59, 38.65], + "Context 59": [39.64, 40.46, 41.41, 41.63, 41.75, 41.94, 42.2, 42.2, 42.25, 42.32], + "VOC 20": [83.53, 84.57, 85.29, 85.33, 85.43, 85.58, 85.17, 85.62, 85.63, 85.58], + "VOC 21": [61.44, 62.58, 63.74, 64.1, 64.39, 64.74, 64.91, 65.19, 65.33, 65.44], + "OV-COCO": [41.7, 42.8, 43.3, 42.7, 42.4, 42.0, 42.2, 41.8, 42.0, 41.5], +} + +hyperparams = np.linspace(0.1, 1.0, 10) + +# 获取除OV-COCO外的所有分割数据集 +seg_datasets = [k for k in datasets if k != "OV-COCO"] + +# 计算每个超参下的平均mIoU +seg_results = np.array([datasets[k] for k in seg_datasets]) +avg_miou = np.mean(seg_results, axis=0) + +plt.figure(figsize=(4, 3)) # 将高度压缩 + +# avg mIoU 曲线 +plt.plot( + hyperparams, avg_miou, + label="DeCLIP Avg. mIoU", + color="#2077b4", + marker="o", + linestyle='--', + linewidth=3, + markersize=6, + zorder=5 +) + +# OV-COCO 曲线 +plt.plot( + hyperparams, datasets["OV-COCO"], + label="DeCLIP mAP (Novel)", + color="#d62728", + marker="s", + linestyle='--', + linewidth=3, + markersize=6, + zorder=10 +) + +# 添加14.1的横虚线(CLIP avg baseline) +plt.axhline(14.1, color="#2ca02c", linestyle="--", linewidth=2, label="CLIP Avg. mIoU") + +# 添加17.5的横虚线(CLIP OV-COCO baseline) +plt.axhline(17.5, color="#d62728", linestyle="--", linewidth=2, label="CLIP mAP (Novel)") + +# plt.xlabel("Hyperparameter Value", fontsize=13) +# plt.ylabel("mIoU (%)", fontsize=13) +plt.grid(True, linestyle='--', alpha=0.6) +plt.tick_params(axis='x', labelsize=14) # x轴刻度大 +plt.tick_params(axis='y', labelsize=12) # y轴刻度不变 +plt.legend(fontsize=14, loc='best') +plt.tight_layout() +plt.savefig("hyperparameter.pdf", dpi=300) +plt.close() \ No newline at end of file diff --git a/tools/plot_layers.py b/tools/plot_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..93b98f18b76c5de0007a1c51c7e2edc91faedefa --- /dev/null +++ b/tools/plot_layers.py @@ -0,0 +1,65 @@ +import matplotlib.pyplot as plt +import numpy as np + +# 层数和数据 +layers = ["3", "6", "9", "12"] +segmentation_MIoU = [39.58625, 43.8675, 43.6925, 44.1] +detection_ap = [31.4, 35.6, 39.5, 43.3] + +# 曲线样式(继承原风格) +curve_configs = [ + { + "label": "Avg. mIoU", + "color": "#2077b4", # 蓝色 + "marker": "o", + "linestyle": "--", + "linewidth": 3, + "markersize": 9, + "zorder": 3, + }, + { + "label": "mAP (Novel)", + "color": "#ff7f0e", # 橙色 + "marker": "s", + "linestyle": "--", + "linewidth": 3, + "markersize": 9, + "zorder": 2, + }, +] + +plt.figure(figsize=(4, 3)) + +# 画两条折线 +plt.plot( + layers, segmentation_MIoU, + label=curve_configs[0]["label"], + linestyle=curve_configs[0]["linestyle"], + marker=curve_configs[0]["marker"], + color=curve_configs[0]["color"], + linewidth=curve_configs[0]["linewidth"], + markersize=curve_configs[0]["markersize"], + zorder=curve_configs[0]["zorder"], +) +plt.plot( + layers, detection_ap, + label=curve_configs[1]["label"], + linestyle=curve_configs[1]["linestyle"], + marker=curve_configs[1]["marker"], + color=curve_configs[1]["color"], + linewidth=curve_configs[1]["linewidth"], + markersize=curve_configs[1]["markersize"], + zorder=curve_configs[1]["zorder"], +) + +# plt.xlabel("Layer Number", fontsize=12) +# plt.ylabel("Score", fontsize=12) +plt.grid(True, linestyle='--', alpha=0.6) +# plt.tick_params(axis='both', which='major', labelsize=12) +plt.tick_params(axis='x', labelsize=14) # x轴刻度大 +plt.tick_params(axis='y', labelsize=12) # y轴刻度不变 +plt.tight_layout() + +plt.legend(fontsize=14, loc='best') +plt.savefig("layers_effect.pdf", dpi=300) +plt.close() \ No newline at end of file diff --git a/tools/plot_linear.py b/tools/plot_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd60ca862c9df15697abc94749c67c9d4ad6358 --- /dev/null +++ b/tools/plot_linear.py @@ -0,0 +1,100 @@ +import matplotlib.pyplot as plt +import seaborn as sns +import pandas as pd + +# 设置数据 +resolution = [336.00, 448.00, 560.00, 672.00, 784.00, 896.00, 1024.00] + +# 数据:RoI Thing +roi_thing = { + "Resolution": resolution, + "CLIPself": [65.90, 69.50, 70.90, 71.70, 72.00, 72.60, 72.30], + "RegionCLIP": [66.40, 70.00, 71.20, 72.10, 72.10, 72.00, 71.90], + "DeCLIP": [68.90, 72.10, 74.30, 75.20, 75.50, 75.70, 75.40] +} + +# 数据:Mask Thing +mask_thing = { + "Resolution": resolution, + "CLIPself": [60.10, 66.00, 69.50, 71.40, 72.70, 74.00, 74.60], + "RegionCLIP": [60.60, 66.90, 69.70, 72.50, 73.50, 73.90, 74.70], + "DeCLIP": [62.00, 68.40, 72.20, 74.50, 75.80, 76.80, 77.20] +} + +# 数据:Mask Stuff +mask_stuff = { + "Resolution": resolution, + "CLIPself": [40.80, 43.10, 44.60, 45.40, 45.90, 46.50, 46.90], + "RegionCLIP": [28.20, 30.10, 30.30, 31.10, 32.50, 35.00, 34.80], + "DeCLIP": [45.50, 49.10, 50.40, 51.20, 51.30, 52.70, 52.50] +} + +# 将数据转换为 pandas DataFrame +df_roi_thing = pd.DataFrame(roi_thing) +df_mask_thing = pd.DataFrame(mask_thing) +df_mask_stuff = pd.DataFrame(mask_stuff) + +# 设置绘图风格和颜色 +sns.set_style("whitegrid") + +# 定义新的颜色、线条样式和标记符号 +color_palette = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd'] # 参考图的颜色 +line_styles = ['--', '-.', ':'] +markers = ['o', 's', '^'] + +# 设置全局字体和线宽 +plt.rcParams.update({ + 'font.size': 10, # 字体大小 + 'axes.labelsize': 10, + 'lines.linewidth': 2.0, # 线条宽度 + 'legend.fontsize': 8, # 图例字体大小 + 'xtick.labelsize': 8, # x轴刻度字体大小 + 'ytick.labelsize': 8, # y轴刻度字体大小 + 'grid.color': 'gray', # 网格线颜色 + 'grid.alpha': 0.3, # 调整网格线透明度 +}) + +# 绘制 RoI Thing 折线图并保存 +plt.figure(figsize=(4, 3)) # 调整图的大小 +plt.plot(df_roi_thing['Resolution'], df_roi_thing['DeCLIP'], linestyle=line_styles[2], marker=markers[2], color=color_palette[2], label='DeCLIP') +plt.plot(df_roi_thing['Resolution'], df_roi_thing['CLIPself'], linestyle=line_styles[0], marker=markers[0], color=color_palette[0], label='CLIPself') +plt.plot(df_roi_thing['Resolution'], df_roi_thing['RegionCLIP'], linestyle=line_styles[1], marker=markers[1], color=color_palette[1], label='RegionCLIP') +plt.xlabel('Resolution') +plt.ylabel(' RoI Align (Thing) mAcc') # 统一纵坐标标签 +plt.xticks(resolution) +plt.grid(True, linestyle='--', color='gray', alpha=0.3) # 更淡的网格 +# plt.legend(loc='lower right') +plt.legend(loc='best',fontsize=10) +plt.tight_layout() +plt.savefig('roi_thing.pdf', dpi=300) # 保存为PDF +plt.close() + +# 绘制 Mask Thing 折线图并保存 +plt.figure(figsize=(4, 3)) +plt.plot(df_mask_thing['Resolution'], df_mask_thing['DeCLIP'], linestyle=line_styles[2], marker=markers[2], color=color_palette[2], label='DeCLIP') +plt.plot(df_mask_thing['Resolution'], df_mask_thing['CLIPself'], linestyle=line_styles[0], marker=markers[0], color=color_palette[0], label='CLIPself') +plt.plot(df_mask_thing['Resolution'], df_mask_thing['RegionCLIP'], linestyle=line_styles[1], marker=markers[1], color=color_palette[1], label='RegionCLIP') +plt.xlabel('Resolution') +plt.ylabel(' Mask Pooling (Thing) mAcc') # 统一纵坐标标签 +plt.xticks(resolution) +plt.grid(True, linestyle='--', color='gray', alpha=0.3) # 更淡的网格 +# plt.legend(loc='lower right') +plt.legend(loc='best',fontsize=10) +plt.tight_layout() +plt.savefig('mask_thing.pdf', dpi=300) # 保存为PDF +plt.close() + +# 绘制 Mask Stuff 折线图并保存 +plt.figure(figsize=(4, 3)) +plt.plot(df_mask_stuff['Resolution'], df_mask_stuff['DeCLIP'], linestyle=line_styles[2], marker=markers[2], color=color_palette[2], label='DeCLIP') +plt.plot(df_mask_stuff['Resolution'], df_mask_stuff['CLIPself'], linestyle=line_styles[0], marker=markers[0], color=color_palette[0], label='CLIPself') +plt.plot(df_mask_stuff['Resolution'], df_mask_stuff['RegionCLIP'], linestyle=line_styles[1], marker=markers[1], color=color_palette[1], label='RegionCLIP') +plt.xlabel('Resolution') +plt.ylabel('Mask Pooling (Stuff) mAcc') # 统一纵坐标标签 +plt.xticks(resolution) +plt.grid(True, linestyle='--', color='gray', alpha=0.3) # 更淡的网格 +# plt.legend(loc='lower right') +plt.legend(loc='best', fontsize=10) +plt.tight_layout() +plt.savefig('mask_stuff.pdf', dpi=300) # 保存为PDF +plt.close() \ No newline at end of file diff --git a/tools/plot_linearv1.1.py b/tools/plot_linearv1.1.py new file mode 100644 index 0000000000000000000000000000000000000000..db36727bdf3da5fe67a69ded7f78d124e276a850 --- /dev/null +++ b/tools/plot_linearv1.1.py @@ -0,0 +1,100 @@ +import matplotlib.pyplot as plt +import seaborn as sns +import pandas as pd + +# 设置数据 +resolution = [336.00, 448.00, 560.00, 672.00, 784.00, 896.00, 1024.00] + +# 数据:RoI Thing +roi_thing = { + "Resolution": resolution, + "CLIPself": [65.90, 69.50, 70.90, 71.70, 72.00, 72.60, 72.30], + "RegionCLIP": [66.40, 70.00, 71.20, 72.10, 72.10, 72.00, 71.90], + "DeCLIP": [68.90, 72.10, 74.30, 75.20, 75.50, 75.70, 75.40] +} + +# 数据:Mask Thing +mask_thing = { + "Resolution": resolution, + "CLIPself": [60.10, 66.00, 69.50, 71.40, 72.70, 74.00, 74.60], + "RegionCLIP": [60.60, 66.90, 69.70, 72.50, 73.50, 73.90, 74.70], + "DeCLIP": [62.9, 69.0, 72.10, 75.2, 76.3, 77.5, 77.20] +} + +# 数据:Mask Stuff +mask_stuff = { + "Resolution": resolution, + "CLIPself": [40.80, 43.10, 44.60, 45.40, 45.90, 46.50, 46.90], + "RegionCLIP": [28.20, 30.10, 30.30, 31.10, 32.50, 35.00, 34.80], + "DeCLIP": [47.4, 50.6, 52.2, 54.0, 54.4, 55.9, 56.0] +} + +# 将数据转换为 pandas DataFrame +df_roi_thing = pd.DataFrame(roi_thing) +df_mask_thing = pd.DataFrame(mask_thing) +df_mask_stuff = pd.DataFrame(mask_stuff) + +# 设置绘图风格和颜色 +sns.set_style("whitegrid") + +# 定义新的颜色、线条样式和标记符号 +color_palette = ['#1f77b4', '#ff7f0e', '#2ca02c'] # 参考图的颜色 +line_styles = ['--', '--', '--'] +markers = ['o', 's', '^'] + +# 设置全局字体和线宽 +plt.rcParams.update({ + 'font.size': 10, # 字体大小 + 'axes.labelsize': 10, + 'lines.linewidth': 2.5, # 线条宽度 + 'legend.fontsize': 12, # 图例字体大小 + 'xtick.labelsize': 10, # x轴刻度字体大小 + 'ytick.labelsize': 10, # y轴刻度字体大小 + 'grid.color': 'gray', # 网格线颜色 + 'grid.alpha': 0.3, # 调整网格线透明度 +}) + +# 绘制 RoI Thing 折线图并保存 +plt.figure(figsize=(4, 3)) # 调整图的大小 +plt.plot(df_roi_thing['Resolution'], df_roi_thing['DeCLIP'], linestyle=line_styles[2], marker=markers[2], color=color_palette[2], label='DeCLIP') +plt.plot(df_roi_thing['Resolution'], df_roi_thing['CLIPself'], linestyle=line_styles[0], marker=markers[0], color=color_palette[0], label='CLIPself') +plt.plot(df_roi_thing['Resolution'], df_roi_thing['RegionCLIP'], linestyle=line_styles[1], marker=markers[1], color=color_palette[1], label='RegionCLIP') +plt.xlabel('Resolution') +plt.ylabel(' RoI Align (Thing) mAcc') # 统一纵坐标标签 +plt.xticks(resolution) +plt.grid(True, linestyle='--', color='gray', alpha=0.3) # 更淡的网格 +# plt.legend(loc='lower right') +plt.legend(loc='best',fontsize=12,framealpha=0.5) +plt.tight_layout() +plt.savefig('roi_thing.pdf', dpi=300) # 保存为PDF +plt.close() + +# 绘制 Mask Thing 折线图并保存 +plt.figure(figsize=(4, 3)) +plt.plot(df_mask_thing['Resolution'], df_mask_thing['DeCLIP'], linestyle=line_styles[2], marker=markers[2], color=color_palette[2], label='DeCLIP') +plt.plot(df_mask_thing['Resolution'], df_mask_thing['CLIPself'], linestyle=line_styles[0], marker=markers[0], color=color_palette[0], label='CLIPself') +plt.plot(df_mask_thing['Resolution'], df_mask_thing['RegionCLIP'], linestyle=line_styles[1], marker=markers[1], color=color_palette[1], label='RegionCLIP') +plt.xlabel('Resolution') +plt.ylabel(' Mask Pooling (Thing) mAcc') # 统一纵坐标标签 +plt.xticks(resolution) +plt.grid(True, linestyle='--', color='gray', alpha=0.3) # 更淡的网格 +# plt.legend(loc='lower right') +plt.legend(loc='best',fontsize=12,framealpha=0.5) +plt.tight_layout() +plt.savefig('mask_thing.pdf', dpi=300) # 保存为PDF +plt.close() + +# 绘制 Mask Stuff 折线图并保存 +plt.figure(figsize=(4, 3)) +plt.plot(df_mask_stuff['Resolution'], df_mask_stuff['DeCLIP'], linestyle=line_styles[2], marker=markers[2], color=color_palette[2], label='DeCLIP') +plt.plot(df_mask_stuff['Resolution'], df_mask_stuff['CLIPself'], linestyle=line_styles[0], marker=markers[0], color=color_palette[0], label='CLIPself') +plt.plot(df_mask_stuff['Resolution'], df_mask_stuff['RegionCLIP'], linestyle=line_styles[1], marker=markers[1], color=color_palette[1], label='RegionCLIP') +plt.xlabel('Resolution') +plt.ylabel('Mask Pooling (Stuff) mAcc') # 统一纵坐标标签 +plt.xticks(resolution) +plt.grid(True, linestyle='--', color='gray', alpha=0.3) # 更淡的网格 +# plt.legend(loc='lower right') +plt.legend(loc='best', fontsize=12,framealpha=0.5) +plt.tight_layout() +plt.savefig('mask_stuff.pdf', dpi=300) # 保存为PDF +plt.close() \ No newline at end of file diff --git a/tools/plot_linearv2.py b/tools/plot_linearv2.py new file mode 100644 index 0000000000000000000000000000000000000000..bcabca36b9887cd84b4011501becc8ec3eb08baf --- /dev/null +++ b/tools/plot_linearv2.py @@ -0,0 +1,108 @@ +import matplotlib.pyplot as plt +import seaborn as sns +import pandas as pd + +# -------------------------------------------------------------- +# 1. 数据 +# -------------------------------------------------------------- +resolution = [336.00, 448.00, 560.00, 672.00, 784.00, 896.00, 1024.00] + +roi_thing = { + "Resolution": resolution, + "CLIPself": [65.90, 69.50, 70.90, 71.70, 72.00, 72.60, 72.30], + "RegionCLIP": [66.40, 70.00, 71.20, 72.10, 72.10, 72.00, 71.90], + "DeCLIP": [68.90, 72.10, 74.30, 75.20, 75.50, 75.70, 75.40] +} + +mask_thing = { + "Resolution": resolution, + "CLIPself": [60.10, 66.00, 69.50, 71.40, 72.70, 74.00, 74.60], + "RegionCLIP": [60.60, 66.90, 69.70, 72.50, 73.50, 73.90, 74.70], + "DeCLIP": [62.00, 68.40, 72.20, 74.50, 75.80, 76.80, 77.20] +} + +mask_stuff = { + "Resolution": resolution, + "CLIPself": [40.80, 43.10, 44.60, 45.40, 45.90, 46.50, 46.90], + "RegionCLIP": [28.20, 30.10, 30.30, 31.10, 32.50, 35.00, 34.80], + "DeCLIP": [45.50, 49.10, 50.40, 51.20, 51.30, 52.70, 52.50] +} + +df_roi_thing = pd.DataFrame(roi_thing) +df_mask_thing = pd.DataFrame(mask_thing) +df_mask_stuff = pd.DataFrame(mask_stuff) + +# -------------------------------------------------------------- +# 2. 全局风格 +# -------------------------------------------------------------- +sns.set_style('white') +plt.rcParams.update({ + 'font.size' : 10, + 'axes.labelsize' : 10, + 'xtick.labelsize' : 8, + 'ytick.labelsize' : 8, + + # 折线 & 标记 + 'lines.linewidth' : 1.5, # 更细的折线 + 'lines.markersize' : 8, # 更大的数据点 + 'lines.markeredgewidth': 0.8, # 更细描边 + + # 图例 + 'legend.fontsize' : 9, + + # 网格 + 'axes.grid' : True, + 'grid.linestyle' : '--', + 'grid.alpha' : 0.3, # 更淡 + 'grid.color' : 'gray', + 'grid.linewidth' : 0.5, # 更细 + + # 坐标轴外框 + 'axes.spines.right': False, + 'axes.spines.top' : False, + 'axes.linewidth' : 1.2 +}) + +# 调色盘与标记 +palette = { + 'CLIPself' : '#80b1d3', # 浅蓝 + 'RegionCLIP': '#fb8072', # 珊瑚红 + 'DeCLIP' : '#8dd3c7' # 青绿 +} +markers = { + 'CLIPself' : 'o', + 'RegionCLIP': '^', + 'DeCLIP' : 'D' +} + +# -------------------------------------------------------------- +# 3. 画图函数 +# -------------------------------------------------------------- +def plot_and_save(df, y_label, filename): + fig, ax = plt.subplots(figsize=(4, 3)) + + for key in ['CLIPself', 'RegionCLIP', 'DeCLIP']: + ax.plot( + df['Resolution'], df[key], + linestyle='-', # 实线 + marker=markers[key], + color=palette[key], + markeredgecolor='black', + label=key + ) + + ax.set_xlabel('Resolution') + ax.set_ylabel(y_label) + ax.set_xticks(resolution) + + ax.legend(frameon=False, loc='best') + fig.tight_layout() + fig.savefig(filename, dpi=300) + plt.close(fig) + +# -------------------------------------------------------------- +# 4. 生成三张图 +# -------------------------------------------------------------- +plot_and_save(df_roi_thing, 'RoI Align (Thing) mAcc', 'roi_thing.png') +plot_and_save(df_mask_thing, 'Mask Pooling (Thing) mAcc', 'mask_thing.png') +plot_and_save(df_mask_stuff, 'Mask Pooling (Stuff) mAcc', 'mask_stuff.png') \ No newline at end of file